title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Packages In Scala - GeeksforGeeks
|
28 May, 2019
Package in Scala is a mechanism to encapsulate a group of classes, sub packages, traits and package objects. It basically provides namespace to put our code in a different files and directories. Packages is a easy way to maintain our code which prevents naming conflicts of members of different packages. Providing access control to members of packages like private, protected, package specific controlling scope restricts the access of member to other packages, while the members with no modifier can be used inside any other package with some reference.
Packages are declared as a first statement at the top of a Scala file.Syntax :
package package_name
// Scala classes
// traits
// objects..
Defining a package can be done in different ways:-
Chained methodspackage x.y.z
// members of z
or can be used as:-package x
package y
package z
// member of z
package x.y.z
// members of z
or can be used as:-
package x
package y
package z
// member of z
Nesting packagespackage x{
// members of x {as required}
package y{
// members of y{as required}
package z{
// members of z{as required}
}
}
}
package x{
// members of x {as required}
package y{
// members of y{as required}
package z{
// members of z{as required}
}
}
}
Packages binds together the data in a single file or works as data encapsulation, when a file is saved it comes under default package or under a package name as specified at the top of the file. Package names and directory structure are closely related. For example if a package name is college.student.cse, then there will be 3 directories, college, student and cse. Such that cse is present in student and student is present in college.
college
+student
+cse
The idea is to make sure that files are easy to locate in directories while using the packages.Package naming conventions for domain names are in reverse order as i.e. org.geeksforgeeks.practice, org.geeksforgeeks.contribute.
We can add any numbers of members in a package such as classes, subclasses, traits, object containing the main method and sub packages. Unlike the java packages we can add a declared packages in different scala files i.e. different scala files can be written can for the same package.Example:
// file named as faculty.scala
package college
class faculty{
def faculymethod(){}
}
// file named as student.scala// containing the main method // using the college package name againpackage college class student{ def studentmethod(){}} // Creating objectobject Main{ // Main method def main(args: Array[String]) { val stu= new student() val fac= new faculty() // faculty class can be accessed while // in different file but in same package. }}
What is actually created in directory structure is as below:-
college
+faculty.scala
+student.scala
Packages can be used by different ways in a program. Import clauses are quite flexible in Scala than in java. Such as import clauses can be used any where in the program as an independent statement in the program using the keyword import, Java does not allow that.
// base.scala// bb directorypackage bb // creating a classclass geek{ private var id=0 def method() { println("welcome to geek class") println("id="+id) }}
Below is the example of Package using import clauses.
// main.scala// aa directorypackage aa // Creating objectobject Main{ // Main method def main(args: Array[String]) { // importing in main method import bb.geek // using the member injected using import statement val obj = new geek() obj.method(); }}
Importing all public members of package.import college._
//imports all college members students, faculties, houseKeeping etc.
import college._
//imports all college members students, faculties, houseKeeping etc.
Imports only selected members of a package.import college.{faculty, houseKeeping}
//member student is not selected hence cannot be used in current file
import college.{faculty, houseKeeping}
//member student is not selected hence cannot be used in current file
Imports and rename the members.import college.{student => stu}
//stu is used in-place of student
import college.{student => stu}
//stu is used in-place of student
Picked
Scala
Scala-Packages
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
For Loop in Scala
Scala | flatMap Method
Scala | map() method
Scala List filter() method with example
Scala | reduce() Function
String concatenation in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List contains() method with example
Scala String substring() method with example
|
[
{
"code": null,
"e": 26063,
"s": 26035,
"text": "\n28 May, 2019"
},
{
"code": null,
"e": 26619,
"s": 26063,
"text": "Package in Scala is a mechanism to encapsulate a group of classes, sub packages, traits and package objects. It basically provides namespace to put our code in a different files and directories. Packages is a easy way to maintain our code which prevents naming conflicts of members of different packages. Providing access control to members of packages like private, protected, package specific controlling scope restricts the access of member to other packages, while the members with no modifier can be used inside any other package with some reference."
},
{
"code": null,
"e": 26698,
"s": 26619,
"text": "Packages are declared as a first statement at the top of a Scala file.Syntax :"
},
{
"code": null,
"e": 26760,
"s": 26698,
"text": "package package_name\n// Scala classes\n// traits\n// objects..\n"
},
{
"code": null,
"e": 26811,
"s": 26760,
"text": "Defining a package can be done in different ways:-"
},
{
"code": null,
"e": 26921,
"s": 26811,
"text": "Chained methodspackage x.y.z\n// members of z\nor can be used as:-package x\npackage y\npackage z\n// member of z\n"
},
{
"code": null,
"e": 26952,
"s": 26921,
"text": "package x.y.z\n// members of z\n"
},
{
"code": null,
"e": 26972,
"s": 26952,
"text": "or can be used as:-"
},
{
"code": null,
"e": 27018,
"s": 26972,
"text": "package x\npackage y\npackage z\n// member of z\n"
},
{
"code": null,
"e": 27198,
"s": 27018,
"text": "Nesting packagespackage x{\n // members of x {as required}\n package y{\n // members of y{as required}\n package z{\n // members of z{as required}\n }\n }\n}\n"
},
{
"code": null,
"e": 27362,
"s": 27198,
"text": "package x{\n // members of x {as required}\n package y{\n // members of y{as required}\n package z{\n // members of z{as required}\n }\n }\n}\n"
},
{
"code": null,
"e": 27801,
"s": 27362,
"text": "Packages binds together the data in a single file or works as data encapsulation, when a file is saved it comes under default package or under a package name as specified at the top of the file. Package names and directory structure are closely related. For example if a package name is college.student.cse, then there will be 3 directories, college, student and cse. Such that cse is present in student and student is present in college."
},
{
"code": null,
"e": 27839,
"s": 27801,
"text": "college\n +student\n +cse\n"
},
{
"code": null,
"e": 28065,
"s": 27839,
"text": "The idea is to make sure that files are easy to locate in directories while using the packages.Package naming conventions for domain names are in reverse order as i.e. org.geeksforgeeks.practice, org.geeksforgeeks.contribute."
},
{
"code": null,
"e": 28358,
"s": 28065,
"text": "We can add any numbers of members in a package such as classes, subclasses, traits, object containing the main method and sub packages. Unlike the java packages we can add a declared packages in different scala files i.e. different scala files can be written can for the same package.Example:"
},
{
"code": null,
"e": 28447,
"s": 28358,
"text": "// file named as faculty.scala\npackage college\nclass faculty{\n def faculymethod(){}\n}\n"
},
{
"code": "// file named as student.scala// containing the main method // using the college package name againpackage college class student{ def studentmethod(){}} // Creating objectobject Main{ // Main method def main(args: Array[String]) { val stu= new student() val fac= new faculty() // faculty class can be accessed while // in different file but in same package. }}",
"e": 28857,
"s": 28447,
"text": null
},
{
"code": null,
"e": 28919,
"s": 28857,
"text": "What is actually created in directory structure is as below:-"
},
{
"code": null,
"e": 28968,
"s": 28919,
"text": "college\n +faculty.scala\n +student.scala\n"
},
{
"code": null,
"e": 29233,
"s": 28968,
"text": "Packages can be used by different ways in a program. Import clauses are quite flexible in Scala than in java. Such as import clauses can be used any where in the program as an independent statement in the program using the keyword import, Java does not allow that."
},
{
"code": "// base.scala// bb directorypackage bb // creating a classclass geek{ private var id=0 def method() { println(\"welcome to geek class\") println(\"id=\"+id) }} ",
"e": 29419,
"s": 29233,
"text": null
},
{
"code": null,
"e": 29473,
"s": 29419,
"text": "Below is the example of Package using import clauses."
},
{
"code": "// main.scala// aa directorypackage aa // Creating objectobject Main{ // Main method def main(args: Array[String]) { // importing in main method import bb.geek // using the member injected using import statement val obj = new geek() obj.method(); }}",
"e": 29784,
"s": 29473,
"text": null
},
{
"code": null,
"e": 29911,
"s": 29784,
"text": "Importing all public members of package.import college._\n//imports all college members students, faculties, houseKeeping etc.\n"
},
{
"code": null,
"e": 29998,
"s": 29911,
"text": "import college._\n//imports all college members students, faculties, houseKeeping etc.\n"
},
{
"code": null,
"e": 30151,
"s": 29998,
"text": "Imports only selected members of a package.import college.{faculty, houseKeeping}\n//member student is not selected hence cannot be used in current file\n"
},
{
"code": null,
"e": 30261,
"s": 30151,
"text": "import college.{faculty, houseKeeping}\n//member student is not selected hence cannot be used in current file\n"
},
{
"code": null,
"e": 30359,
"s": 30261,
"text": "Imports and rename the members.import college.{student => stu}\n//stu is used in-place of student\n"
},
{
"code": null,
"e": 30426,
"s": 30359,
"text": "import college.{student => stu}\n//stu is used in-place of student\n"
},
{
"code": null,
"e": 30433,
"s": 30426,
"text": "Picked"
},
{
"code": null,
"e": 30439,
"s": 30433,
"text": "Scala"
},
{
"code": null,
"e": 30454,
"s": 30439,
"text": "Scala-Packages"
},
{
"code": null,
"e": 30460,
"s": 30454,
"text": "Scala"
},
{
"code": null,
"e": 30558,
"s": 30460,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30576,
"s": 30558,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 30599,
"s": 30576,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 30620,
"s": 30599,
"text": "Scala | map() method"
},
{
"code": null,
"e": 30660,
"s": 30620,
"text": "Scala List filter() method with example"
},
{
"code": null,
"e": 30686,
"s": 30660,
"text": "Scala | reduce() Function"
},
{
"code": null,
"e": 30716,
"s": 30686,
"text": "String concatenation in Scala"
},
{
"code": null,
"e": 30738,
"s": 30716,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 30791,
"s": 30738,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 30833,
"s": 30791,
"text": "Scala List contains() method with example"
}
] |
Generate string by incrementing character of given string by number present at corresponding index of second string - GeeksforGeeks
|
07 Jan, 2022
Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices.
Examples:
Input: S = “sun”, N = “966”Output: bat
Input: S = “apple”, N = “12580”Output: brute
Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to the ASCII value of string S[]. If the value exceeds 122, which is the ASCII value of the last alphabet ‘z’. Then subtract the value by 26, which is the total count of English alphabets. Update string S with the character of ASCII value obtained. Follow the steps below to solve the problem:
Iterate over the range [0, S.size()) using the variable i and perform the following tasks:Initialize the variables a and b as the integer and ascii value of N[i] and S[i].If b is greater than 122 then subtract 26 from b.Set S[i] as char(b).
Initialize the variables a and b as the integer and ascii value of N[i] and S[i].
If b is greater than 122 then subtract 26 from b.
Set S[i] as char(b).
After performing the above steps, print the value of S[] as the answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to update stringstring updateStr(string S, string N){ for (int i = 0; i < S.size(); i++) { // Get ASCII value int a = int(N[i]) - '0'; int b = int(S[i]) + a; if (b > 122) b -= 26; S[i] = char(b); } return S;} // Driver Codeint main(){ string S = "sun"; string N = "966"; cout << updateStr(S, N); return 0;}
// Java code to implement above approachimport java.util.*;public class GFG { // Function to update string static String updateStr(String S, String N) { String t = ""; for (int i = 0; i < S.length(); i++) { // Get ASCII value int a = (int)(N.charAt(i) - '0'); int b = (int)(S.charAt(i) + a); if (b > 122) b -= 26; char x = (char)b; t +=x; } return t; } // Driver code public static void main(String args[]) { String S = "sun"; String N = "966"; System.out.println(updateStr(S, N)); }} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Function to update stringdef updateStr(S, N): S = list(S) for i in range(len(S)): # Get ASCII value a = ord(N[i]) - ord('0') b = ord(S[i]) + a if (b > 122): b -= 26 S[i] = chr(b) return "".join(S) # Driver Code S = "sun"N = "966"print(updateStr(S, N)) # This code is contributed by Saurabh Jaiswal
// C# code to implement above approachusing System;public class GFG { // Function to update string static String updateStr(String S, String N) { String t = ""; for (int i = 0; i < S.Length; i++) { // Get ASCII value int a = (int)(N[i] - '0'); int b = (int)(S[i] + a); if (b > 122) b -= 26; char x = (char)b; t +=x; } return t; } // Driver code public static void Main(String []args) { String S = "sun"; String N = "966"; Console.WriteLine(updateStr(S, N)); }} // This code is contributed by shikhasingrajput
<script> // JavaScript code for the above approach // Function to update string function updateStr(S, N) { S = S.split('') for (let i = 0; i < S.length; i++) { // Get ASCII value let a = (N[i].charCodeAt(0) - '0'.charCodeAt(0)); let b = (S[i].charCodeAt(0)) + a; if (b > 122) b -= 26; S[i] = String.fromCharCode(b); } return S.join(''); } // Driver Code let S = "sun"; let N = "966"; document.write(updateStr(S, N)); // This code is contributed by Potta Lokesh </script>
bat
Time Complexity: O(|S|)Auxiliary Space: O(1)
lokeshpotta20
_saurabh_jaiswal
samim2000
shikhasingrajput
gulshankumarar231
ASCII
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Modular multiplicative inverse
Count all possible paths from top left to bottom right of a mXn matrix
Fizz Buzz Implementation
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 26075,
"s": 25937,
"text": "Given two strings S[] and N[] of the same size, the task is to update string S[] by adding the digit of string N[] of respective indices."
},
{
"code": null,
"e": 26085,
"s": 26075,
"text": "Examples:"
},
{
"code": null,
"e": 26124,
"s": 26085,
"text": "Input: S = “sun”, N = “966”Output: bat"
},
{
"code": null,
"e": 26169,
"s": 26124,
"text": "Input: S = “apple”, N = “12580”Output: brute"
},
{
"code": null,
"e": 26577,
"s": 26169,
"text": "Approach: The idea is to traverse the string S[] from left to right. Get the ASCII value of string N[] and add it to the ASCII value of string S[]. If the value exceeds 122, which is the ASCII value of the last alphabet ‘z’. Then subtract the value by 26, which is the total count of English alphabets. Update string S with the character of ASCII value obtained. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26818,
"s": 26577,
"text": "Iterate over the range [0, S.size()) using the variable i and perform the following tasks:Initialize the variables a and b as the integer and ascii value of N[i] and S[i].If b is greater than 122 then subtract 26 from b.Set S[i] as char(b)."
},
{
"code": null,
"e": 26900,
"s": 26818,
"text": "Initialize the variables a and b as the integer and ascii value of N[i] and S[i]."
},
{
"code": null,
"e": 26950,
"s": 26900,
"text": "If b is greater than 122 then subtract 26 from b."
},
{
"code": null,
"e": 26971,
"s": 26950,
"text": "Set S[i] as char(b)."
},
{
"code": null,
"e": 27043,
"s": 26971,
"text": "After performing the above steps, print the value of S[] as the answer."
},
{
"code": null,
"e": 27094,
"s": 27043,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 27098,
"s": 27094,
"text": "C++"
},
{
"code": null,
"e": 27103,
"s": 27098,
"text": "Java"
},
{
"code": null,
"e": 27111,
"s": 27103,
"text": "Python3"
},
{
"code": null,
"e": 27114,
"s": 27111,
"text": "C#"
},
{
"code": null,
"e": 27125,
"s": 27114,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to update stringstring updateStr(string S, string N){ for (int i = 0; i < S.size(); i++) { // Get ASCII value int a = int(N[i]) - '0'; int b = int(S[i]) + a; if (b > 122) b -= 26; S[i] = char(b); } return S;} // Driver Codeint main(){ string S = \"sun\"; string N = \"966\"; cout << updateStr(S, N); return 0;}",
"e": 27597,
"s": 27125,
"text": null
},
{
"code": "// Java code to implement above approachimport java.util.*;public class GFG { // Function to update string static String updateStr(String S, String N) { String t = \"\"; for (int i = 0; i < S.length(); i++) { // Get ASCII value int a = (int)(N.charAt(i) - '0'); int b = (int)(S.charAt(i) + a); if (b > 122) b -= 26; char x = (char)b; t +=x; } return t; } // Driver code public static void main(String args[]) { String S = \"sun\"; String N = \"966\"; System.out.println(updateStr(S, N)); }} // This code is contributed by Samim Hossain Mondal.",
"e": 28207,
"s": 27597,
"text": null
},
{
"code": "# Python code for the above approach # Function to update stringdef updateStr(S, N): S = list(S) for i in range(len(S)): # Get ASCII value a = ord(N[i]) - ord('0') b = ord(S[i]) + a if (b > 122): b -= 26 S[i] = chr(b) return \"\".join(S) # Driver Code S = \"sun\"N = \"966\"print(updateStr(S, N)) # This code is contributed by Saurabh Jaiswal",
"e": 28602,
"s": 28207,
"text": null
},
{
"code": "// C# code to implement above approachusing System;public class GFG { // Function to update string static String updateStr(String S, String N) { String t = \"\"; for (int i = 0; i < S.Length; i++) { // Get ASCII value int a = (int)(N[i] - '0'); int b = (int)(S[i] + a); if (b > 122) b -= 26; char x = (char)b; t +=x; } return t; } // Driver code public static void Main(String []args) { String S = \"sun\"; String N = \"966\"; Console.WriteLine(updateStr(S, N)); }} // This code is contributed by shikhasingrajput",
"e": 29182,
"s": 28602,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to update string function updateStr(S, N) { S = S.split('') for (let i = 0; i < S.length; i++) { // Get ASCII value let a = (N[i].charCodeAt(0) - '0'.charCodeAt(0)); let b = (S[i].charCodeAt(0)) + a; if (b > 122) b -= 26; S[i] = String.fromCharCode(b); } return S.join(''); } // Driver Code let S = \"sun\"; let N = \"966\"; document.write(updateStr(S, N)); // This code is contributed by Potta Lokesh </script>",
"e": 29730,
"s": 29182,
"text": null
},
{
"code": null,
"e": 29734,
"s": 29730,
"text": "bat"
},
{
"code": null,
"e": 29779,
"s": 29734,
"text": "Time Complexity: O(|S|)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 29793,
"s": 29779,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 29810,
"s": 29793,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 29820,
"s": 29810,
"text": "samim2000"
},
{
"code": null,
"e": 29837,
"s": 29820,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 29855,
"s": 29837,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 29861,
"s": 29855,
"text": "ASCII"
},
{
"code": null,
"e": 29874,
"s": 29861,
"text": "Mathematical"
},
{
"code": null,
"e": 29882,
"s": 29874,
"text": "Strings"
},
{
"code": null,
"e": 29890,
"s": 29882,
"text": "Strings"
},
{
"code": null,
"e": 29903,
"s": 29890,
"text": "Mathematical"
},
{
"code": null,
"e": 30001,
"s": 29903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30045,
"s": 30001,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 30087,
"s": 30045,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 30118,
"s": 30087,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 30189,
"s": 30118,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 30214,
"s": 30189,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 30260,
"s": 30214,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30285,
"s": 30260,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30319,
"s": 30285,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30394,
"s": 30319,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Sort the string as per ASCII values of the characters - GeeksforGeeks
|
26 Apr, 2022
Given a string S of size N, the task is to sort the string based on their ASCII values.
Examples:
Input: S = “Geeks7”Output: 7GeeksExplanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets.
Input: S = “GeeksForGeeks”Output: FGGeeeekkorss
Approach: The idea to solve this problem is to maintain an array to store the frequency of each character and then add them accordingly in the resultant string. Since there are at max 256 characters which make the space complexity constant. Follow the steps below to solve this problem:
Initialize a vector freq[] of size 256 with values 0 to store the frequency of each character of the string.
Iterate over the range [0, N) using the variable i and increase the count of s[i] in the array freq[] by 1.
Make the string S as an empty string.
Iterate over the range [0, N) using the variable i and iterate over the range [0, freq[i]) using the variable j and adding the character corresponding to the i-th ASCII value in the string s[].
After performing the above steps, print the string S as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the string based// on their ASCII valuesvoid sortString(string s){ int N = s.length(); // Stores the frequency of each // character of the string vector<int> freq(256, 0); // Count and store the frequency for (int i = 0; i < N; i++) { freq[s[i]]++; } s = ""; // Store the result for (int i = 0; i < 256; i++) { for (int j = 0; j < freq[i]; j++) s = s + (char)i; } // Print the result cout << s << "\n"; return;} // Driver Codeint main(){ string S = "GeeksForGeeks"; sortString(S); return 0;}
// java program for the above approachimport java.util.*; class Main{ // Function to sort the string based// on their ASCII valuesstatic void sortString(String s){ int N = s.length(); // Stores the frequency of each // character of the string int [] freq = new int [256]; for(int i = 0; i < 256; i++){ freq[i] = 0; } // Count and store the frequency for (int i = 0; i < N; i++) { char character = s.charAt(i); int val = (int) character; freq[val]++; } // Store the result for (int i = 0; i < 256; i++) { for (int j = 0; j < freq[i]; j++) // s = s + (char)i; System.out.print((char)i); }} // Driver Codepublic static void main(String [] args){ String S = "GeeksForGeeks"; sortString(S);}} // This code is contributed by amreshkumar3.
# Python Program to implement# the above approach # Function to sort the string based# on their ASCII valuesdef sortString(s): N = len(s) # Stores the frequency of each # character of the string freq = [0] * 256 # Count and store the frequency for i in range(0, N) : freq[ord(s[i])] += 1 s = "" # Store the result for i in range(256): for j in range(freq[i]): s = s + chr(i) # Print the result print(s) return # Driver CodeS = "GeeksForGeeks"sortString(S) # This code is contributed by gfgking.
// C# implementation for the above approachusing System;class GFG{ // Function to sort the string based// on their ASCII valuesstatic void sortString(string s){ int N = s.Length; // Stores the frequency of each // character of the string int [] freq = new int[256]; for(int i = 0; i < 256; i++){ freq[i] = 0; } // Count and store the frequency for (int i = 0; i < N; i++) { char character = s[i]; int val = (int) character; freq[val]++; } // Store the result for (int i = 0; i < 256; i++) { for (int j = 0; j < freq[i]; j++) // s = s + (char)i; Console.Write((char)i); }} // Driver Code public static void Main() { string S = "GeeksForGeeks"; sortString(S); }} // This code is contributed by sanjoy_62.
<script> // JavaScript Program to implement // the above approach // Function to sort the string based // on their ASCII values function sortString(s) { let N = s.length; // Stores the frequency of each // character of the string let freq = new Array(256).fill(0) // Count and store the frequency for (let i = 0; i < N; i++) { freq[s[i].charCodeAt(0)]++; } s = ""; // Store the result for (let i = 0; i < 256; i++) { for (let j = 0; j < freq[i]; j++) s = s + String.fromCharCode(i); } // Print the result document.write(s); return; } // Driver Code let S = "GeeksForGeeks"; sortString(S); // This code is contributed by Potta Lokesh </script>
FGGeeeekkorss
Time Complexity: O(256*N)Auxiliary Space: O(256)
Alternate Approach: The given problem can also be solved by using the comparator function with the inbuilt sort() function to sort the given string as per their ASCII values.
Below is the implementation of the above approach:
C++
Python3
// C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Comparator Function to sort the given// string in increasing order of their// ASCII valuebool cmp(char ch, char chh) { return int(ch) <= int(chh); } // Function to sort the string based// on their ASCII valuesstring sortString(string S){ // Sort the string S sort(S.begin(), S.end(), cmp); return S;} // Driver Codeint main(){ string S = "GeeksForGeeks"; cout << sortString(S); return 0;}
S = "GeeksForGeeks" #Sorted is a in-built pyhton function to sort and#using join we can create the new sorted stringstring = ''.join(sorted(S)) print(string) # This code is contributed by Susobhan Akhuli
FGGeeeekkorss
Time Complexity: O(N*log N)Auxiliary Space: O(1)
lokeshpotta20
gfgking
amreshkumar3
sanjoy_62
code_hunt
susobhanakhuli
ASCII
school-programming
strings
Mathematical
Sorting
Strings
Strings
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Count all possible paths from top left to bottom right of a mXn matrix
Modular multiplicative inverse
Fizz Buzz Implementation
|
[
{
"code": null,
"e": 25937,
"s": 25909,
"text": "\n26 Apr, 2022"
},
{
"code": null,
"e": 26025,
"s": 25937,
"text": "Given a string S of size N, the task is to sort the string based on their ASCII values."
},
{
"code": null,
"e": 26035,
"s": 26025,
"text": "Examples:"
},
{
"code": null,
"e": 26182,
"s": 26035,
"text": "Input: S = “Geeks7”Output: 7GeeksExplanation: According to the ASCII values, integers comes first, then capital alphabets and the small alphabets."
},
{
"code": null,
"e": 26230,
"s": 26182,
"text": "Input: S = “GeeksForGeeks”Output: FGGeeeekkorss"
},
{
"code": null,
"e": 26517,
"s": 26230,
"text": "Approach: The idea to solve this problem is to maintain an array to store the frequency of each character and then add them accordingly in the resultant string. Since there are at max 256 characters which make the space complexity constant. Follow the steps below to solve this problem:"
},
{
"code": null,
"e": 26626,
"s": 26517,
"text": "Initialize a vector freq[] of size 256 with values 0 to store the frequency of each character of the string."
},
{
"code": null,
"e": 26734,
"s": 26626,
"text": "Iterate over the range [0, N) using the variable i and increase the count of s[i] in the array freq[] by 1."
},
{
"code": null,
"e": 26772,
"s": 26734,
"text": "Make the string S as an empty string."
},
{
"code": null,
"e": 26966,
"s": 26772,
"text": "Iterate over the range [0, N) using the variable i and iterate over the range [0, freq[i]) using the variable j and adding the character corresponding to the i-th ASCII value in the string s[]."
},
{
"code": null,
"e": 27034,
"s": 26966,
"text": "After performing the above steps, print the string S as the result."
},
{
"code": null,
"e": 27085,
"s": 27034,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27089,
"s": 27085,
"text": "C++"
},
{
"code": null,
"e": 27094,
"s": 27089,
"text": "Java"
},
{
"code": null,
"e": 27102,
"s": 27094,
"text": "Python3"
},
{
"code": null,
"e": 27105,
"s": 27102,
"text": "C#"
},
{
"code": null,
"e": 27116,
"s": 27105,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the string based// on their ASCII valuesvoid sortString(string s){ int N = s.length(); // Stores the frequency of each // character of the string vector<int> freq(256, 0); // Count and store the frequency for (int i = 0; i < N; i++) { freq[s[i]]++; } s = \"\"; // Store the result for (int i = 0; i < 256; i++) { for (int j = 0; j < freq[i]; j++) s = s + (char)i; } // Print the result cout << s << \"\\n\"; return;} // Driver Codeint main(){ string S = \"GeeksForGeeks\"; sortString(S); return 0;}",
"e": 27793,
"s": 27116,
"text": null
},
{
"code": "// java program for the above approachimport java.util.*; class Main{ // Function to sort the string based// on their ASCII valuesstatic void sortString(String s){ int N = s.length(); // Stores the frequency of each // character of the string int [] freq = new int [256]; for(int i = 0; i < 256; i++){ freq[i] = 0; } // Count and store the frequency for (int i = 0; i < N; i++) { char character = s.charAt(i); int val = (int) character; freq[val]++; } // Store the result for (int i = 0; i < 256; i++) { for (int j = 0; j < freq[i]; j++) // s = s + (char)i; System.out.print((char)i); }} // Driver Codepublic static void main(String [] args){ String S = \"GeeksForGeeks\"; sortString(S);}} // This code is contributed by amreshkumar3.",
"e": 28631,
"s": 27793,
"text": null
},
{
"code": "# Python Program to implement# the above approach # Function to sort the string based# on their ASCII valuesdef sortString(s): N = len(s) # Stores the frequency of each # character of the string freq = [0] * 256 # Count and store the frequency for i in range(0, N) : freq[ord(s[i])] += 1 s = \"\" # Store the result for i in range(256): for j in range(freq[i]): s = s + chr(i) # Print the result print(s) return # Driver CodeS = \"GeeksForGeeks\"sortString(S) # This code is contributed by gfgking.",
"e": 29193,
"s": 28631,
"text": null
},
{
"code": "// C# implementation for the above approachusing System;class GFG{ // Function to sort the string based// on their ASCII valuesstatic void sortString(string s){ int N = s.Length; // Stores the frequency of each // character of the string int [] freq = new int[256]; for(int i = 0; i < 256; i++){ freq[i] = 0; } // Count and store the frequency for (int i = 0; i < N; i++) { char character = s[i]; int val = (int) character; freq[val]++; } // Store the result for (int i = 0; i < 256; i++) { for (int j = 0; j < freq[i]; j++) // s = s + (char)i; Console.Write((char)i); }} // Driver Code public static void Main() { string S = \"GeeksForGeeks\"; sortString(S); }} // This code is contributed by sanjoy_62.",
"e": 30021,
"s": 29193,
"text": null
},
{
"code": "<script> // JavaScript Program to implement // the above approach // Function to sort the string based // on their ASCII values function sortString(s) { let N = s.length; // Stores the frequency of each // character of the string let freq = new Array(256).fill(0) // Count and store the frequency for (let i = 0; i < N; i++) { freq[s[i].charCodeAt(0)]++; } s = \"\"; // Store the result for (let i = 0; i < 256; i++) { for (let j = 0; j < freq[i]; j++) s = s + String.fromCharCode(i); } // Print the result document.write(s); return; } // Driver Code let S = \"GeeksForGeeks\"; sortString(S); // This code is contributed by Potta Lokesh </script>",
"e": 30928,
"s": 30021,
"text": null
},
{
"code": null,
"e": 30943,
"s": 30928,
"text": "FGGeeeekkorss\n"
},
{
"code": null,
"e": 30993,
"s": 30943,
"text": " Time Complexity: O(256*N)Auxiliary Space: O(256)"
},
{
"code": null,
"e": 31168,
"s": 30993,
"text": "Alternate Approach: The given problem can also be solved by using the comparator function with the inbuilt sort() function to sort the given string as per their ASCII values."
},
{
"code": null,
"e": 31219,
"s": 31168,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 31223,
"s": 31219,
"text": "C++"
},
{
"code": null,
"e": 31231,
"s": 31223,
"text": "Python3"
},
{
"code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Comparator Function to sort the given// string in increasing order of their// ASCII valuebool cmp(char ch, char chh) { return int(ch) <= int(chh); } // Function to sort the string based// on their ASCII valuesstring sortString(string S){ // Sort the string S sort(S.begin(), S.end(), cmp); return S;} // Driver Codeint main(){ string S = \"GeeksForGeeks\"; cout << sortString(S); return 0;}",
"e": 31725,
"s": 31231,
"text": null
},
{
"code": "S = \"GeeksForGeeks\" #Sorted is a in-built pyhton function to sort and#using join we can create the new sorted stringstring = ''.join(sorted(S)) print(string) # This code is contributed by Susobhan Akhuli",
"e": 31930,
"s": 31725,
"text": null
},
{
"code": null,
"e": 31944,
"s": 31930,
"text": "FGGeeeekkorss"
},
{
"code": null,
"e": 31994,
"s": 31944,
"text": " Time Complexity: O(N*log N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 32008,
"s": 31994,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 32016,
"s": 32008,
"text": "gfgking"
},
{
"code": null,
"e": 32029,
"s": 32016,
"text": "amreshkumar3"
},
{
"code": null,
"e": 32039,
"s": 32029,
"text": "sanjoy_62"
},
{
"code": null,
"e": 32049,
"s": 32039,
"text": "code_hunt"
},
{
"code": null,
"e": 32064,
"s": 32049,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 32070,
"s": 32064,
"text": "ASCII"
},
{
"code": null,
"e": 32089,
"s": 32070,
"text": "school-programming"
},
{
"code": null,
"e": 32097,
"s": 32089,
"text": "strings"
},
{
"code": null,
"e": 32110,
"s": 32097,
"text": "Mathematical"
},
{
"code": null,
"e": 32118,
"s": 32110,
"text": "Sorting"
},
{
"code": null,
"e": 32126,
"s": 32118,
"text": "Strings"
},
{
"code": null,
"e": 32134,
"s": 32126,
"text": "Strings"
},
{
"code": null,
"e": 32147,
"s": 32134,
"text": "Mathematical"
},
{
"code": null,
"e": 32155,
"s": 32147,
"text": "Sorting"
},
{
"code": null,
"e": 32253,
"s": 32155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32297,
"s": 32253,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32339,
"s": 32297,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 32410,
"s": 32339,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 32441,
"s": 32410,
"text": "Modular multiplicative inverse"
}
] |
Python | sympy.Function() method - GeeksforGeeks
|
19 Jul, 2019
With the help of sympy.Function() method, we can find the various functions in the whole mathematical expression like f(x), sin(x), log(x), etc by using sympy.Function() method.
Syntax : sympy.Function()Return : Return the list of functions in mathematical operation.
Example #1 :In this example we can see that by using sympy.Function() method, we are able to find the function in the mathematical operation.
# import sympyfrom sympy import * x, y = symbols('x y')f = Function('f') # Use sympy.Function() methodgfg = (f(x) + 2 * tan(y + I * pi) + log(2 * x)).atoms(Function) print(gfg)
Output :
{f(x), tan(y + I*pi), log(2*x)}
Example #2 :
# import sympyfrom sympy import * x, y = symbols('x y')f = Function('f') # Use sympy.Function() methodgfg = (2 + 3 * cos(y) + 5 * log(2 * x)).atoms(Function) print(gfg)
Output :
{cos(y), log(2*x)}
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25827,
"s": 25799,
"text": "\n19 Jul, 2019"
},
{
"code": null,
"e": 26005,
"s": 25827,
"text": "With the help of sympy.Function() method, we can find the various functions in the whole mathematical expression like f(x), sin(x), log(x), etc by using sympy.Function() method."
},
{
"code": null,
"e": 26095,
"s": 26005,
"text": "Syntax : sympy.Function()Return : Return the list of functions in mathematical operation."
},
{
"code": null,
"e": 26237,
"s": 26095,
"text": "Example #1 :In this example we can see that by using sympy.Function() method, we are able to find the function in the mathematical operation."
},
{
"code": "# import sympyfrom sympy import * x, y = symbols('x y')f = Function('f') # Use sympy.Function() methodgfg = (f(x) + 2 * tan(y + I * pi) + log(2 * x)).atoms(Function) print(gfg)",
"e": 26420,
"s": 26237,
"text": null
},
{
"code": null,
"e": 26429,
"s": 26420,
"text": "Output :"
},
{
"code": null,
"e": 26461,
"s": 26429,
"text": "{f(x), tan(y + I*pi), log(2*x)}"
},
{
"code": null,
"e": 26474,
"s": 26461,
"text": "Example #2 :"
},
{
"code": "# import sympyfrom sympy import * x, y = symbols('x y')f = Function('f') # Use sympy.Function() methodgfg = (2 + 3 * cos(y) + 5 * log(2 * x)).atoms(Function) print(gfg)",
"e": 26649,
"s": 26474,
"text": null
},
{
"code": null,
"e": 26658,
"s": 26649,
"text": "Output :"
},
{
"code": null,
"e": 26677,
"s": 26658,
"text": "{cos(y), log(2*x)}"
},
{
"code": null,
"e": 26683,
"s": 26677,
"text": "SymPy"
},
{
"code": null,
"e": 26690,
"s": 26683,
"text": "Python"
},
{
"code": null,
"e": 26788,
"s": 26690,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26806,
"s": 26788,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26841,
"s": 26806,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26873,
"s": 26841,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26895,
"s": 26873,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26937,
"s": 26895,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26967,
"s": 26937,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26993,
"s": 26967,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27022,
"s": 26993,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27066,
"s": 27022,
"text": "Reading and Writing to text files in Python"
}
] |
JavaScript String lastIndexOf() Method - GeeksforGeeks
|
05 Oct, 2021
Below is the example of the String lastIndexOf() Method.
Example:<script> function func() { var str = 'GeeksforGeeks'; var index = str.lastIndexOf('for'); document.write(index); } func(); </script>
<script> function func() { var str = 'GeeksforGeeks'; var index = str.lastIndexOf('for'); document.write(index); } func(); </script>
Output:5
5
str.lastIndexOf() method finds the index of the last occurrence of the argument string in the given string. The value returned is 0-based.
Syntax:
str.lastIndexOf(searchValue , index)
searchValue: searchValue is the string that is to be searched in the base string.
index defines the starting index from where the searchValue is to be searched in the base string backwards.
Return value: This method returns the index of the string (0-based) where the searchValue is found for the last time. If the searchValue cannot be found in the string then the method returns -1.
Examples for the above method are provided below:
Example 1:
var str = 'Departed Train';
var index = str.lastIndexOf('Train');
print(index);
Output:
9
In this example the method lastIndexOf() finds the last index of the string ‘Train’ in the string str. Since the only index of the string is 9, therefore this method returns 9 as the answer.
Example 2:
var str = 'Departed Train';
var index = str.lastIndexOf('ed Tr');
print(index);
Output:
6
In this example the method lastIndexOf() finds the last index of the string ‘ed Tr’ in the string str. Since the only index of where this string is present is 6, therefore this method returns 6 as the answer.
Example 3:
print('Departed Train'.lastIndexOf('train'));
Output:
-1
In this example the method lastIndexOf() finds the last index of the string ‘train’ in the string str. Since the string is not present in any index in str, therefore this method returns -1 as the answer.
Example 4:
print('Departed Train before another Train'.lastIndexOf('Train')); ;
Output:
6
In this example the method lastIndexOf() finds the last index of the string Train in the string str. Since the string is present two time in the string str and the index 30, is the last index of Train, therefore this method returns 30 as the answer.
Codes for the above method are provided below:
Program 1:
<script>// JavaScript to illustrate lastIndexOf() method function func() { //Original string var str = 'Departed Train'; //Finding the index of the string var index = str.lastIndexOf('Train'); document.write(index);}func();</script>
Output:
9
Program 2:
<script>// JavaScript to illustrate lastIndexOf() method function func() { // Original string var str = 'Departed Train'; // Finding the index of the string var index = str.lastIndexOf('ed Tr'); document.write(index); }func();</script>
Output:
6
Program 3:
<script>// JavaScript to illustrate lastIndexOf() method function func() { // Original string var str = 'Departed Train'; // Finding index of occurrence of 'train' var index = str.lastIndexOf('train'); document.write(index);}func();</script>
Output:
-1
Program 4:
<script>// JavaScript to illustrate lastIndexOf() method function func() { // Original string var str = 'Departed Train before another Train'; // Finding index of occurrence of 'Train' var index = str.lastIndexOf('Train'); document.write(index); ;}func();</script>
Output:
30
Supported Browsers:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 6 and above
Opera 3 and above
Safari 1 and above
makinenidharmendra
ysachin2314
JavaScript-Methods
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25879,
"s": 25851,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 25936,
"s": 25879,
"text": "Below is the example of the String lastIndexOf() Method."
},
{
"code": null,
"e": 26089,
"s": 25936,
"text": "Example:<script> function func() { var str = 'GeeksforGeeks'; var index = str.lastIndexOf('for'); document.write(index); } func(); </script>"
},
{
"code": "<script> function func() { var str = 'GeeksforGeeks'; var index = str.lastIndexOf('for'); document.write(index); } func(); </script>",
"e": 26234,
"s": 26089,
"text": null
},
{
"code": null,
"e": 26244,
"s": 26234,
"text": "Output:5\n"
},
{
"code": null,
"e": 26247,
"s": 26244,
"text": "5\n"
},
{
"code": null,
"e": 26386,
"s": 26247,
"text": "str.lastIndexOf() method finds the index of the last occurrence of the argument string in the given string. The value returned is 0-based."
},
{
"code": null,
"e": 26394,
"s": 26386,
"text": "Syntax:"
},
{
"code": null,
"e": 26432,
"s": 26394,
"text": "str.lastIndexOf(searchValue , index)\n"
},
{
"code": null,
"e": 26514,
"s": 26432,
"text": "searchValue: searchValue is the string that is to be searched in the base string."
},
{
"code": null,
"e": 26622,
"s": 26514,
"text": "index defines the starting index from where the searchValue is to be searched in the base string backwards."
},
{
"code": null,
"e": 26817,
"s": 26622,
"text": "Return value: This method returns the index of the string (0-based) where the searchValue is found for the last time. If the searchValue cannot be found in the string then the method returns -1."
},
{
"code": null,
"e": 26867,
"s": 26817,
"text": "Examples for the above method are provided below:"
},
{
"code": null,
"e": 26878,
"s": 26867,
"text": "Example 1:"
},
{
"code": null,
"e": 26960,
"s": 26878,
"text": "var str = 'Departed Train';\nvar index = str.lastIndexOf('Train');\nprint(index); \n"
},
{
"code": null,
"e": 26968,
"s": 26960,
"text": "Output:"
},
{
"code": null,
"e": 26971,
"s": 26968,
"text": "9\n"
},
{
"code": null,
"e": 27162,
"s": 26971,
"text": "In this example the method lastIndexOf() finds the last index of the string ‘Train’ in the string str. Since the only index of the string is 9, therefore this method returns 9 as the answer."
},
{
"code": null,
"e": 27173,
"s": 27162,
"text": "Example 2:"
},
{
"code": null,
"e": 27255,
"s": 27173,
"text": "var str = 'Departed Train';\nvar index = str.lastIndexOf('ed Tr');\nprint(index); \n"
},
{
"code": null,
"e": 27263,
"s": 27255,
"text": "Output:"
},
{
"code": null,
"e": 27266,
"s": 27263,
"text": "6\n"
},
{
"code": null,
"e": 27475,
"s": 27266,
"text": "In this example the method lastIndexOf() finds the last index of the string ‘ed Tr’ in the string str. Since the only index of where this string is present is 6, therefore this method returns 6 as the answer."
},
{
"code": null,
"e": 27486,
"s": 27475,
"text": "Example 3:"
},
{
"code": null,
"e": 27534,
"s": 27486,
"text": "print('Departed Train'.lastIndexOf('train')); \n"
},
{
"code": null,
"e": 27542,
"s": 27534,
"text": "Output:"
},
{
"code": null,
"e": 27546,
"s": 27542,
"text": "-1\n"
},
{
"code": null,
"e": 27750,
"s": 27546,
"text": "In this example the method lastIndexOf() finds the last index of the string ‘train’ in the string str. Since the string is not present in any index in str, therefore this method returns -1 as the answer."
},
{
"code": null,
"e": 27761,
"s": 27750,
"text": "Example 4:"
},
{
"code": null,
"e": 27832,
"s": 27761,
"text": "print('Departed Train before another Train'.lastIndexOf('Train')); ; \n"
},
{
"code": null,
"e": 27840,
"s": 27832,
"text": "Output:"
},
{
"code": null,
"e": 27843,
"s": 27840,
"text": "6\n"
},
{
"code": null,
"e": 28093,
"s": 27843,
"text": "In this example the method lastIndexOf() finds the last index of the string Train in the string str. Since the string is present two time in the string str and the index 30, is the last index of Train, therefore this method returns 30 as the answer."
},
{
"code": null,
"e": 28140,
"s": 28093,
"text": "Codes for the above method are provided below:"
},
{
"code": null,
"e": 28151,
"s": 28140,
"text": "Program 1:"
},
{
"code": "<script>// JavaScript to illustrate lastIndexOf() method function func() { //Original string var str = 'Departed Train'; //Finding the index of the string var index = str.lastIndexOf('Train'); document.write(index);}func();</script>",
"e": 28412,
"s": 28151,
"text": null
},
{
"code": null,
"e": 28420,
"s": 28412,
"text": "Output:"
},
{
"code": null,
"e": 28423,
"s": 28420,
"text": "9\n"
},
{
"code": null,
"e": 28434,
"s": 28423,
"text": "Program 2:"
},
{
"code": "<script>// JavaScript to illustrate lastIndexOf() method function func() { // Original string var str = 'Departed Train'; // Finding the index of the string var index = str.lastIndexOf('ed Tr'); document.write(index); }func();</script> ",
"e": 28699,
"s": 28434,
"text": null
},
{
"code": null,
"e": 28707,
"s": 28699,
"text": "Output:"
},
{
"code": null,
"e": 28710,
"s": 28707,
"text": "6\n"
},
{
"code": null,
"e": 28721,
"s": 28710,
"text": "Program 3:"
},
{
"code": "<script>// JavaScript to illustrate lastIndexOf() method function func() { // Original string var str = 'Departed Train'; // Finding index of occurrence of 'train' var index = str.lastIndexOf('train'); document.write(index);}func();</script>",
"e": 28990,
"s": 28721,
"text": null
},
{
"code": null,
"e": 28998,
"s": 28990,
"text": "Output:"
},
{
"code": null,
"e": 29002,
"s": 28998,
"text": "-1\n"
},
{
"code": null,
"e": 29013,
"s": 29002,
"text": "Program 4:"
},
{
"code": "<script>// JavaScript to illustrate lastIndexOf() method function func() { // Original string var str = 'Departed Train before another Train'; // Finding index of occurrence of 'Train' var index = str.lastIndexOf('Train'); document.write(index); ;}func();</script>",
"e": 29307,
"s": 29013,
"text": null
},
{
"code": null,
"e": 29315,
"s": 29307,
"text": "Output:"
},
{
"code": null,
"e": 29319,
"s": 29315,
"text": "30\n"
},
{
"code": null,
"e": 29339,
"s": 29319,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 29358,
"s": 29339,
"text": "Chrome 1 and above"
},
{
"code": null,
"e": 29376,
"s": 29358,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 29396,
"s": 29376,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 29426,
"s": 29396,
"text": "Internet Explorer 6 and above"
},
{
"code": null,
"e": 29444,
"s": 29426,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 29463,
"s": 29444,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 29482,
"s": 29463,
"text": "makinenidharmendra"
},
{
"code": null,
"e": 29494,
"s": 29482,
"text": "ysachin2314"
},
{
"code": null,
"e": 29513,
"s": 29494,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 29531,
"s": 29513,
"text": "javascript-string"
},
{
"code": null,
"e": 29542,
"s": 29531,
"text": "JavaScript"
},
{
"code": null,
"e": 29559,
"s": 29542,
"text": "Web Technologies"
},
{
"code": null,
"e": 29657,
"s": 29559,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29697,
"s": 29657,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29742,
"s": 29697,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29803,
"s": 29742,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29875,
"s": 29803,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29927,
"s": 29875,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29967,
"s": 29927,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30000,
"s": 29967,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30045,
"s": 30000,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30088,
"s": 30045,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Hash Table in LISP - GeeksforGeeks
|
07 Sep, 2021
A hash table is a type of collection in Common LISP, that is used to map keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
There are three types of hashtables in lisp, which are listed below:
eq : It is used for comparison when the hashing of the hash table is done on LISP objects.eql: It is also used for comparison when the hashing of the hash table is done on LISP objects.equal: It is used for comparison when the hashing of the hash table is done on LISP tree structures.
eq : It is used for comparison when the hashing of the hash table is done on LISP objects.
eql: It is also used for comparison when the hashing of the hash table is done on LISP objects.
equal: It is used for comparison when the hashing of the hash table is done on LISP tree structures.
The make-hash-table function is used in Common LISP to create a hash table.
Syntax:
make-hash-table &key :test :size :rehash-size : rehash-threshold
Here,
key:- It is the key name.
:test:- It is used to determine how the keys are compared. It takes one of the three types of hash table values mentioned above(ie, eq, eql, equal).
:size:- It is used to set the initial size of the hash table.
:rehash-size:- It is used to set the increment in the size of the hash table once it gets full and more data needs to be added.
:rehash-threshold:- It is used to set the maximum size of the hashtable after which the increment can be done to its size.
The gethash function is used to fetch data from a hash table in LISP.
Syntax:
gethash key hash-table &optional default
Here,
key: It is the key name.
hash-table: It is the name of the hashtable
default: It is the return type. If not set it returns nil if the value is not found.
The setf function is used with the gethash function to add data to a hash table in LISP.
Syntax:
setf (gethash 'key hash-table-name) '(value)
Here,
key: It is the key name.
hash-table-name: It is the name of the hashtable
value: It is the value to be associated with the key
Example: Creating a hash table, adding data, and fetching data from it.
Lisp
; call make-hash-table function(setq makeHashTable (make-hash-table)) ; 1st entry(setf (gethash 'gfg makeHashTable) '(Geeksforgeeks)) ; 2nd entry(setf (gethash 'DSA makeHashTable) '(Data Structure & Algorithms)) ; output 1(write (gethash 'gfg makeHashTable)) (terpri) ; output 2(write (gethash 'DSA makeHashTable))
Output:
(GEEKSFORGEEKS)
(DATA STRUCTURE & ALGORITHMS)
The remhash function is used to remove key-value entries from a hash table.
Syntax:
remhash key hash-table
Here,
key: It is the name of the key.
hash-table: It is the name of the hash table from where the entries are to be removed.
Example: Here we will remove the 1st entry done in the previous example and print out the result.
Lisp
; call make-hash-table function(setq makeHashTable (make-hash-table)) ; 1st entry(setf (gethash 'gfg makeHashTable) '(Geeksforgeeks)) ; 2nd entry(setf (gethash 'DSA makeHashTable) '(Data Structure & Algorithms)) ; output 1(write (gethash 'gfg makeHashTable)) (terpri) ; output 2(write (gethash 'DSA makeHashTable)) ; remove 1st entry(remhash 'gfg makeHashTable)(terpri) ; output the first entry(write (gethash 'gfg makeHashTable))
Output:
(GEEKSFORGEEKS)
(DATA STRUCTURE & ALGORITHMS)
NIL
Blogathon-2021
LISP-Control-Structures
Picked
Blogathon
LISP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
SQL Query to Convert Datetime to Date
Introduction to LISP
Decision Making in LISP
Functions in LISP
Lists in LISP
Loops in LISP
|
[
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 26388,
"s": 26097,
"text": "A hash table is a type of collection in Common LISP, that is used to map keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. "
},
{
"code": null,
"e": 26457,
"s": 26388,
"text": "There are three types of hashtables in lisp, which are listed below:"
},
{
"code": null,
"e": 26745,
"s": 26457,
"text": "eq : It is used for comparison when the hashing of the hash table is done on LISP objects.eql: It is also used for comparison when the hashing of the hash table is done on LISP objects.equal: It is used for comparison when the hashing of the hash table is done on LISP tree structures."
},
{
"code": null,
"e": 26836,
"s": 26745,
"text": "eq : It is used for comparison when the hashing of the hash table is done on LISP objects."
},
{
"code": null,
"e": 26933,
"s": 26836,
"text": "eql: It is also used for comparison when the hashing of the hash table is done on LISP objects."
},
{
"code": null,
"e": 27035,
"s": 26933,
"text": "equal: It is used for comparison when the hashing of the hash table is done on LISP tree structures."
},
{
"code": null,
"e": 27111,
"s": 27035,
"text": "The make-hash-table function is used in Common LISP to create a hash table."
},
{
"code": null,
"e": 27119,
"s": 27111,
"text": "Syntax:"
},
{
"code": null,
"e": 27184,
"s": 27119,
"text": "make-hash-table &key :test :size :rehash-size : rehash-threshold"
},
{
"code": null,
"e": 27190,
"s": 27184,
"text": "Here,"
},
{
"code": null,
"e": 27216,
"s": 27190,
"text": "key:- It is the key name."
},
{
"code": null,
"e": 27365,
"s": 27216,
"text": ":test:- It is used to determine how the keys are compared. It takes one of the three types of hash table values mentioned above(ie, eq, eql, equal)."
},
{
"code": null,
"e": 27427,
"s": 27365,
"text": ":size:- It is used to set the initial size of the hash table."
},
{
"code": null,
"e": 27555,
"s": 27427,
"text": ":rehash-size:- It is used to set the increment in the size of the hash table once it gets full and more data needs to be added."
},
{
"code": null,
"e": 27678,
"s": 27555,
"text": ":rehash-threshold:- It is used to set the maximum size of the hashtable after which the increment can be done to its size."
},
{
"code": null,
"e": 27748,
"s": 27678,
"text": "The gethash function is used to fetch data from a hash table in LISP."
},
{
"code": null,
"e": 27756,
"s": 27748,
"text": "Syntax:"
},
{
"code": null,
"e": 27797,
"s": 27756,
"text": "gethash key hash-table &optional default"
},
{
"code": null,
"e": 27803,
"s": 27797,
"text": "Here,"
},
{
"code": null,
"e": 27828,
"s": 27803,
"text": "key: It is the key name."
},
{
"code": null,
"e": 27872,
"s": 27828,
"text": "hash-table: It is the name of the hashtable"
},
{
"code": null,
"e": 27957,
"s": 27872,
"text": "default: It is the return type. If not set it returns nil if the value is not found."
},
{
"code": null,
"e": 28046,
"s": 27957,
"text": "The setf function is used with the gethash function to add data to a hash table in LISP."
},
{
"code": null,
"e": 28054,
"s": 28046,
"text": "Syntax:"
},
{
"code": null,
"e": 28099,
"s": 28054,
"text": "setf (gethash 'key hash-table-name) '(value)"
},
{
"code": null,
"e": 28105,
"s": 28099,
"text": "Here,"
},
{
"code": null,
"e": 28130,
"s": 28105,
"text": "key: It is the key name."
},
{
"code": null,
"e": 28179,
"s": 28130,
"text": "hash-table-name: It is the name of the hashtable"
},
{
"code": null,
"e": 28232,
"s": 28179,
"text": "value: It is the value to be associated with the key"
},
{
"code": null,
"e": 28304,
"s": 28232,
"text": "Example: Creating a hash table, adding data, and fetching data from it."
},
{
"code": null,
"e": 28309,
"s": 28304,
"text": "Lisp"
},
{
"code": "; call make-hash-table function(setq makeHashTable (make-hash-table)) ; 1st entry(setf (gethash 'gfg makeHashTable) '(Geeksforgeeks)) ; 2nd entry(setf (gethash 'DSA makeHashTable) '(Data Structure & Algorithms)) ; output 1(write (gethash 'gfg makeHashTable)) (terpri) ; output 2(write (gethash 'DSA makeHashTable))",
"e": 28630,
"s": 28309,
"text": null
},
{
"code": null,
"e": 28638,
"s": 28630,
"text": "Output:"
},
{
"code": null,
"e": 28684,
"s": 28638,
"text": "(GEEKSFORGEEKS)\n(DATA STRUCTURE & ALGORITHMS)"
},
{
"code": null,
"e": 28760,
"s": 28684,
"text": "The remhash function is used to remove key-value entries from a hash table."
},
{
"code": null,
"e": 28768,
"s": 28760,
"text": "Syntax:"
},
{
"code": null,
"e": 28791,
"s": 28768,
"text": "remhash key hash-table"
},
{
"code": null,
"e": 28797,
"s": 28791,
"text": "Here,"
},
{
"code": null,
"e": 28829,
"s": 28797,
"text": "key: It is the name of the key."
},
{
"code": null,
"e": 28916,
"s": 28829,
"text": "hash-table: It is the name of the hash table from where the entries are to be removed."
},
{
"code": null,
"e": 29014,
"s": 28916,
"text": "Example: Here we will remove the 1st entry done in the previous example and print out the result."
},
{
"code": null,
"e": 29019,
"s": 29014,
"text": "Lisp"
},
{
"code": "; call make-hash-table function(setq makeHashTable (make-hash-table)) ; 1st entry(setf (gethash 'gfg makeHashTable) '(Geeksforgeeks)) ; 2nd entry(setf (gethash 'DSA makeHashTable) '(Data Structure & Algorithms)) ; output 1(write (gethash 'gfg makeHashTable)) (terpri) ; output 2(write (gethash 'DSA makeHashTable)) ; remove 1st entry(remhash 'gfg makeHashTable)(terpri) ; output the first entry(write (gethash 'gfg makeHashTable))",
"e": 29458,
"s": 29019,
"text": null
},
{
"code": null,
"e": 29466,
"s": 29458,
"text": "Output:"
},
{
"code": null,
"e": 29516,
"s": 29466,
"text": "(GEEKSFORGEEKS)\n(DATA STRUCTURE & ALGORITHMS)\nNIL"
},
{
"code": null,
"e": 29531,
"s": 29516,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 29555,
"s": 29531,
"text": "LISP-Control-Structures"
},
{
"code": null,
"e": 29562,
"s": 29555,
"text": "Picked"
},
{
"code": null,
"e": 29572,
"s": 29562,
"text": "Blogathon"
},
{
"code": null,
"e": 29577,
"s": 29572,
"text": "LISP"
},
{
"code": null,
"e": 29675,
"s": 29577,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29732,
"s": 29675,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29773,
"s": 29732,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 29803,
"s": 29773,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 29838,
"s": 29803,
"text": "How to Install Tkinter in Windows?"
},
{
"code": null,
"e": 29876,
"s": 29838,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 29897,
"s": 29876,
"text": "Introduction to LISP"
},
{
"code": null,
"e": 29921,
"s": 29897,
"text": "Decision Making in LISP"
},
{
"code": null,
"e": 29939,
"s": 29921,
"text": "Functions in LISP"
},
{
"code": null,
"e": 29953,
"s": 29939,
"text": "Lists in LISP"
}
] |
What is a MongoDB Query? - GeeksforGeeks
|
08 Feb, 2021
MongoDB, the most popular open-source document-oriented database is a NoSQL type of database. NoSQL database stands for Non-Structured Query Database. MongoDB stores the data in the form of the structure(field:value pair) rather than tabular form. It stores data in BSON (Binary JSON) format just like JSON format.
A simple example of a MongoDB database collection.
{
“_id” : ObjectId(“6009585d35cce6b7b8f087f1”),
“title” : “Math”,
“author” : “Aditya”,
“level” : “basic”,
“length” : 230,
“example” : 11
}
MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries provide the simplicity in process of fetching data from the database, it’s similar to SQL queries in SQL Database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database.
MongoDB provides the function names as db.collection_name.find() to operate query operation on database. In this post, we discussed this function in many ways using different methods and operators.
Here, we are working with:
Database: geeksforgeeks
Collection: Article
Note: Here “pretty()” query method is using for only better readability of Document Database.(It’s not necessary)
The find() method displays the database collection in Non-Structured form({<Key> : <value>}) including auto-created <key> ” id ” by MongoDB and collection data inserted by user or admin.
Syntax:
db.collection_name.find()
Example:
db.article.find()
This method is used to display all the documents present in the article collection.
In MongoDB, we can find a single document using findOne() method, This method returns the first document that matches the given filter query expression.
Syntax:
db.collection_name.findOne ()
Example:
db.article.findOne()
Here, we are going to display the first document of the article collection.
In MongoDB, we can display documents of the specified collection in well-formatted way using pretty() method.
Syntax:
db.collection_name.find().pretty()
Example:
db.article.find().pretty()
Here, we are going to display the documents of the article collection in a well-formatted way using pretty() method.
The equality operator($eq) is used to match the documents where the value of the field is equal to the specified value. In other words, the $eq operator is used to specify the equality condition.
Syntax:
db.collection_name.find({< key > : {$eq : < value >}})
Example:
db.article.find({author:{$eq:"devil"}}).pretty()
Here, we are going to display the documents that matches the filter query(i.e., {author : {$eq : “devil”}}) from the article collection.
To get the specific numeric data using conditions like greater than equal or less than equal use the $gte or $lte operator in the find() method.
Syntax:
db.collection_name.find({< key > : {$gte : < value >}})
or
db.collection_name.find({< key > : {$lte : < value >}})
Example:
db.article.find({length:{$gte:510}}).pretty()
Here, we are querying to get documented data which has the length attribute value greater than 510. So, we pass a filter query that is {length : {$gte : 510}} in the find() method.
$exists operator shows all the collection documents if they exist on a given key.
Syntax:
db.collection_name.find({< key > : {$exists : < boolean >}})
Example:
db.article.find({time:{$exists:"true"}}).pretty()
Here, we are going to look all the documents which has the attribute named as time by passing a filter query that is {time : {$exists : “true”}} in the find() method.
$and operator comes under the type of MongoDB logical operator which perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array.
Syntax :
db.collection_name.find({$and : [{< key > : {$eq : < value1 >}}, {< key > : {$exists : < boolean >}}]})
Example:
db.article.find({$and:[{level:{$eq:"high"}},{level:{$exists : "true"}}]}).pretty()
In this query example we are using and operator and given two condition which are highlighted following
and operator: {$and : [ first condition, second condition]}
first condition(level == “high”): { level : {$eq : “high”}}
second condition: {level : {$exists : “true”}}
This query returned the result whatever we specify in parameter using 1 and 0
1: It indicated to return the result
0: It indicates to not return the result
These parameters called Projection Parameter.
Syntax:
db. collection_name. find({< key > : < value >}, {<key> : < Projection_Parameter >})
Example:
db. article. find({author : "devil"},{title : 0}).pretty()
This query example is requesting the data which have the author as named “devil” but in the record don’t want to show the title attribute by specifying it as projection parameter 0
Query to find a record having given attribute: { author : “devil”}
Projection Parameter: {title : 0}
This query method specifies a maximum number of documents for a cursor to return.
Syntax :
db.collection_name.find({< key > : < value >}).limit(< Integer_value >)
Example:
db. article. find({author : “devil” }). limit(2) . pretty()
This query method is simply the extension of the find method only provide a result at a maximum limited number(here is 2)
Query to find record having given attribute: find({author : “devil” })
Query to limit result: limit( 2)
Output :
In MongoDB, It returns the finding result in sorted order that can be ascending or descending. The order specifies by given parameter like
1 (Positive One): It indicates the Ascending order of having attribute value in the record.
-1 (Negative One): It indicates the Descending order of having attribute value in the record.
Syntax:
db.collection_name.find(). sort({< key > : 1})
Example:
db.article.find({author : "devil"}).sort({example : 1}).pretty()
This Example will show the resultant record which has the example attribute and it will show in ascending order because here we are passing value 1.
Query to finding record having given attribute: find ({author : “devil”})
Query to sort parameter: sort({example : 1})
MongoDB
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB Cursor
MongoDB - Update() Method
MongoDB updateMany() Method - db.Collection.updateMany()
|
[
{
"code": null,
"e": 25517,
"s": 25489,
"text": "\n08 Feb, 2021"
},
{
"code": null,
"e": 25833,
"s": 25517,
"text": "MongoDB, the most popular open-source document-oriented database is a NoSQL type of database. NoSQL database stands for Non-Structured Query Database. MongoDB stores the data in the form of the structure(field:value pair) rather than tabular form. It stores data in BSON (Binary JSON) format just like JSON format. "
},
{
"code": null,
"e": 25884,
"s": 25833,
"text": "A simple example of a MongoDB database collection."
},
{
"code": null,
"e": 25886,
"s": 25884,
"text": "{"
},
{
"code": null,
"e": 25936,
"s": 25886,
"text": " “_id” : ObjectId(“6009585d35cce6b7b8f087f1”),"
},
{
"code": null,
"e": 25958,
"s": 25936,
"text": " “title” : “Math”,"
},
{
"code": null,
"e": 25983,
"s": 25958,
"text": " “author” : “Aditya”,"
},
{
"code": null,
"e": 26006,
"s": 25983,
"text": " “level” : “basic”,"
},
{
"code": null,
"e": 26026,
"s": 26006,
"text": " “length” : 230,"
},
{
"code": null,
"e": 26045,
"s": 26026,
"text": " “example” : 11"
},
{
"code": null,
"e": 26047,
"s": 26045,
"text": "}"
},
{
"code": null,
"e": 26393,
"s": 26047,
"text": "MongoDB Query is a way to get the data from the MongoDB database. MongoDB queries provide the simplicity in process of fetching data from the database, it’s similar to SQL queries in SQL Database language. While performing a query operation, one can also use criteria or conditions which can be used to retrieve specific data from the database. "
},
{
"code": null,
"e": 26592,
"s": 26393,
"text": "MongoDB provides the function names as db.collection_name.find() to operate query operation on database. In this post, we discussed this function in many ways using different methods and operators. "
},
{
"code": null,
"e": 26619,
"s": 26592,
"text": "Here, we are working with:"
},
{
"code": null,
"e": 26645,
"s": 26619,
"text": "Database: geeksforgeeks "
},
{
"code": null,
"e": 26666,
"s": 26645,
"text": "Collection: Article "
},
{
"code": null,
"e": 26781,
"s": 26666,
"text": "Note: Here “pretty()” query method is using for only better readability of Document Database.(It’s not necessary) "
},
{
"code": null,
"e": 26969,
"s": 26781,
"text": "The find() method displays the database collection in Non-Structured form({<Key> : <value>}) including auto-created <key> ” id ” by MongoDB and collection data inserted by user or admin."
},
{
"code": null,
"e": 26977,
"s": 26969,
"text": "Syntax:"
},
{
"code": null,
"e": 27003,
"s": 26977,
"text": "db.collection_name.find()"
},
{
"code": null,
"e": 27013,
"s": 27003,
"text": "Example: "
},
{
"code": null,
"e": 27031,
"s": 27013,
"text": "db.article.find()"
},
{
"code": null,
"e": 27116,
"s": 27031,
"text": "This method is used to display all the documents present in the article collection. "
},
{
"code": null,
"e": 27269,
"s": 27116,
"text": "In MongoDB, we can find a single document using findOne() method, This method returns the first document that matches the given filter query expression."
},
{
"code": null,
"e": 27279,
"s": 27269,
"text": "Syntax: "
},
{
"code": null,
"e": 27309,
"s": 27279,
"text": "db.collection_name.findOne ()"
},
{
"code": null,
"e": 27318,
"s": 27309,
"text": "Example:"
},
{
"code": null,
"e": 27339,
"s": 27318,
"text": "db.article.findOne()"
},
{
"code": null,
"e": 27415,
"s": 27339,
"text": "Here, we are going to display the first document of the article collection."
},
{
"code": null,
"e": 27526,
"s": 27415,
"text": "In MongoDB, we can display documents of the specified collection in well-formatted way using pretty() method. "
},
{
"code": null,
"e": 27535,
"s": 27526,
"text": "Syntax: "
},
{
"code": null,
"e": 27572,
"s": 27535,
"text": " db.collection_name.find().pretty() "
},
{
"code": null,
"e": 27581,
"s": 27572,
"text": "Example:"
},
{
"code": null,
"e": 27609,
"s": 27581,
"text": "db.article.find().pretty() "
},
{
"code": null,
"e": 27726,
"s": 27609,
"text": "Here, we are going to display the documents of the article collection in a well-formatted way using pretty() method."
},
{
"code": null,
"e": 27922,
"s": 27726,
"text": "The equality operator($eq) is used to match the documents where the value of the field is equal to the specified value. In other words, the $eq operator is used to specify the equality condition."
},
{
"code": null,
"e": 27932,
"s": 27922,
"text": "Syntax: "
},
{
"code": null,
"e": 27988,
"s": 27932,
"text": "db.collection_name.find({< key > : {$eq : < value >}}) "
},
{
"code": null,
"e": 27998,
"s": 27988,
"text": "Example: "
},
{
"code": null,
"e": 28049,
"s": 27998,
"text": "db.article.find({author:{$eq:\"devil\"}}).pretty() "
},
{
"code": null,
"e": 28188,
"s": 28049,
"text": "Here, we are going to display the documents that matches the filter query(i.e., {author : {$eq : “devil”}}) from the article collection."
},
{
"code": null,
"e": 28334,
"s": 28188,
"text": "To get the specific numeric data using conditions like greater than equal or less than equal use the $gte or $lte operator in the find() method. "
},
{
"code": null,
"e": 28344,
"s": 28334,
"text": "Syntax: "
},
{
"code": null,
"e": 28401,
"s": 28344,
"text": "db.collection_name.find({< key > : {$gte : < value >}}) "
},
{
"code": null,
"e": 28405,
"s": 28401,
"text": "or "
},
{
"code": null,
"e": 28462,
"s": 28405,
"text": "db.collection_name.find({< key > : {$lte : < value >}}) "
},
{
"code": null,
"e": 28472,
"s": 28462,
"text": "Example: "
},
{
"code": null,
"e": 28518,
"s": 28472,
"text": "db.article.find({length:{$gte:510}}).pretty()"
},
{
"code": null,
"e": 28699,
"s": 28518,
"text": "Here, we are querying to get documented data which has the length attribute value greater than 510. So, we pass a filter query that is {length : {$gte : 510}} in the find() method."
},
{
"code": null,
"e": 28781,
"s": 28699,
"text": "$exists operator shows all the collection documents if they exist on a given key."
},
{
"code": null,
"e": 28791,
"s": 28781,
"text": "Syntax: "
},
{
"code": null,
"e": 28852,
"s": 28791,
"text": "db.collection_name.find({< key > : {$exists : < boolean >}})"
},
{
"code": null,
"e": 28863,
"s": 28852,
"text": "Example: "
},
{
"code": null,
"e": 28913,
"s": 28863,
"text": "db.article.find({time:{$exists:\"true\"}}).pretty()"
},
{
"code": null,
"e": 29080,
"s": 28913,
"text": "Here, we are going to look all the documents which has the attribute named as time by passing a filter query that is {time : {$exists : “true”}} in the find() method."
},
{
"code": null,
"e": 29313,
"s": 29080,
"text": "$and operator comes under the type of MongoDB logical operator which perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array."
},
{
"code": null,
"e": 29324,
"s": 29313,
"text": "Syntax : "
},
{
"code": null,
"e": 29428,
"s": 29324,
"text": "db.collection_name.find({$and : [{< key > : {$eq : < value1 >}}, {< key > : {$exists : < boolean >}}]})"
},
{
"code": null,
"e": 29437,
"s": 29428,
"text": "Example:"
},
{
"code": null,
"e": 29520,
"s": 29437,
"text": "db.article.find({$and:[{level:{$eq:\"high\"}},{level:{$exists : \"true\"}}]}).pretty()"
},
{
"code": null,
"e": 29625,
"s": 29520,
"text": "In this query example we are using and operator and given two condition which are highlighted following "
},
{
"code": null,
"e": 29685,
"s": 29625,
"text": "and operator: {$and : [ first condition, second condition]}"
},
{
"code": null,
"e": 29747,
"s": 29685,
"text": "first condition(level == “high”): { level : {$eq : “high”}}"
},
{
"code": null,
"e": 29795,
"s": 29747,
"text": "second condition: {level : {$exists : “true”}} "
},
{
"code": null,
"e": 29874,
"s": 29795,
"text": "This query returned the result whatever we specify in parameter using 1 and 0 "
},
{
"code": null,
"e": 29911,
"s": 29874,
"text": "1: It indicated to return the result"
},
{
"code": null,
"e": 29952,
"s": 29911,
"text": "0: It indicates to not return the result"
},
{
"code": null,
"e": 29999,
"s": 29952,
"text": "These parameters called Projection Parameter. "
},
{
"code": null,
"e": 30009,
"s": 29999,
"text": "Syntax: "
},
{
"code": null,
"e": 30094,
"s": 30009,
"text": "db. collection_name. find({< key > : < value >}, {<key> : < Projection_Parameter >})"
},
{
"code": null,
"e": 30104,
"s": 30094,
"text": "Example: "
},
{
"code": null,
"e": 30163,
"s": 30104,
"text": "db. article. find({author : \"devil\"},{title : 0}).pretty()"
},
{
"code": null,
"e": 30344,
"s": 30163,
"text": "This query example is requesting the data which have the author as named “devil” but in the record don’t want to show the title attribute by specifying it as projection parameter 0"
},
{
"code": null,
"e": 30412,
"s": 30344,
"text": "Query to find a record having given attribute: { author : “devil”}"
},
{
"code": null,
"e": 30449,
"s": 30412,
"text": "Projection Parameter: {title : 0} "
},
{
"code": null,
"e": 30532,
"s": 30449,
"text": "This query method specifies a maximum number of documents for a cursor to return. "
},
{
"code": null,
"e": 30542,
"s": 30532,
"text": "Syntax : "
},
{
"code": null,
"e": 30614,
"s": 30542,
"text": "db.collection_name.find({< key > : < value >}).limit(< Integer_value >)"
},
{
"code": null,
"e": 30624,
"s": 30614,
"text": "Example: "
},
{
"code": null,
"e": 30685,
"s": 30624,
"text": "db. article. find({author : “devil” }). limit(2) . pretty() "
},
{
"code": null,
"e": 30808,
"s": 30685,
"text": "This query method is simply the extension of the find method only provide a result at a maximum limited number(here is 2) "
},
{
"code": null,
"e": 30880,
"s": 30808,
"text": "Query to find record having given attribute: find({author : “devil” }) "
},
{
"code": null,
"e": 30913,
"s": 30880,
"text": "Query to limit result: limit( 2)"
},
{
"code": null,
"e": 30923,
"s": 30913,
"text": "Output : "
},
{
"code": null,
"e": 31063,
"s": 30923,
"text": "In MongoDB, It returns the finding result in sorted order that can be ascending or descending. The order specifies by given parameter like "
},
{
"code": null,
"e": 31155,
"s": 31063,
"text": "1 (Positive One): It indicates the Ascending order of having attribute value in the record."
},
{
"code": null,
"e": 31249,
"s": 31155,
"text": "-1 (Negative One): It indicates the Descending order of having attribute value in the record."
},
{
"code": null,
"e": 31257,
"s": 31249,
"text": "Syntax:"
},
{
"code": null,
"e": 31306,
"s": 31257,
"text": " db.collection_name.find(). sort({< key > : 1}) "
},
{
"code": null,
"e": 31317,
"s": 31306,
"text": "Example: "
},
{
"code": null,
"e": 31384,
"s": 31317,
"text": "db.article.find({author : \"devil\"}).sort({example : 1}).pretty() "
},
{
"code": null,
"e": 31533,
"s": 31384,
"text": "This Example will show the resultant record which has the example attribute and it will show in ascending order because here we are passing value 1."
},
{
"code": null,
"e": 31607,
"s": 31533,
"text": "Query to finding record having given attribute: find ({author : “devil”})"
},
{
"code": null,
"e": 31653,
"s": 31607,
"text": "Query to sort parameter: sort({example : 1}) "
},
{
"code": null,
"e": 31661,
"s": 31653,
"text": "MongoDB"
},
{
"code": null,
"e": 31668,
"s": 31661,
"text": "Picked"
},
{
"code": null,
"e": 31676,
"s": 31668,
"text": "MongoDB"
},
{
"code": null,
"e": 31774,
"s": 31676,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31812,
"s": 31774,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 31837,
"s": 31812,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 31864,
"s": 31837,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 31900,
"s": 31864,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 31924,
"s": 31900,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 31979,
"s": 31924,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 32036,
"s": 31979,
"text": "MongoDB insertMany() Method - db.Collection.insertMany()"
},
{
"code": null,
"e": 32051,
"s": 32036,
"text": "MongoDB Cursor"
},
{
"code": null,
"e": 32077,
"s": 32051,
"text": "MongoDB - Update() Method"
}
] |
How to Install MongoDB on AWS EC2 Instance? - GeeksforGeeks
|
02 Jan, 2022
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer
In this article, we will learn how to install MongoDB on AWS EC2.
AWS account.EC2 Instance.User with privileges to create Instance.
AWS account.
EC2 Instance.
User with privileges to create Instance.
Follow the steps below to install MongoDB on AWS EC2 :
Step 1: Create an AWS Elastic Cloud Compute Instance.
Step 2: Start the EC2 instance that you have created in Step 1.
Step 3: Connect to your EC2 Instance by clicking on Connect Button.
Step 4: A prompt will pop up after connecting.
Step 5: At first check, if MongoDB is already installed or not.
mongod --version
Step 6: If MongoDB is not installed on your virtual machine then at first Install the public key using the following command.
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
Step 7: Add sources.
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
Step 8: Reload the local package database using the following command.
sudo apt update
Step 9: Now install the MongoDB packages using the command.
sudo apt install -y mongodb-org
Step 10: Wait for the process to end.
Step 11: We have successfully installed MongoDB on our EC2 instance, to check if MongoDB is installed or not, verify using the following command.
mongod --version
To Start MongoDB:
sudo systemctl start mongod
To Verify that MongoDB has started successfully:
sudo systemctl status mongod
To Stop MongoDB:
sudo systemctl stop mongod
To restart MongoDB:
sudo systemctl restart mongod
MongoDB Commands
In this way, we can install MongoDB on our EC2 instance using EC2 Instance Connect. And if you also use a free tier account, make sure you delete all the resources you have used before logging out.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
|
[
{
"code": null,
"e": 26223,
"s": 26195,
"text": "\n02 Jan, 2022"
},
{
"code": null,
"e": 26654,
"s": 26223,
"text": "AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer"
},
{
"code": null,
"e": 26720,
"s": 26654,
"text": "In this article, we will learn how to install MongoDB on AWS EC2."
},
{
"code": null,
"e": 26786,
"s": 26720,
"text": "AWS account.EC2 Instance.User with privileges to create Instance."
},
{
"code": null,
"e": 26799,
"s": 26786,
"text": "AWS account."
},
{
"code": null,
"e": 26813,
"s": 26799,
"text": "EC2 Instance."
},
{
"code": null,
"e": 26854,
"s": 26813,
"text": "User with privileges to create Instance."
},
{
"code": null,
"e": 26909,
"s": 26854,
"text": "Follow the steps below to install MongoDB on AWS EC2 :"
},
{
"code": null,
"e": 26963,
"s": 26909,
"text": "Step 1: Create an AWS Elastic Cloud Compute Instance."
},
{
"code": null,
"e": 27027,
"s": 26963,
"text": "Step 2: Start the EC2 instance that you have created in Step 1."
},
{
"code": null,
"e": 27095,
"s": 27027,
"text": "Step 3: Connect to your EC2 Instance by clicking on Connect Button."
},
{
"code": null,
"e": 27142,
"s": 27095,
"text": "Step 4: A prompt will pop up after connecting."
},
{
"code": null,
"e": 27206,
"s": 27142,
"text": "Step 5: At first check, if MongoDB is already installed or not."
},
{
"code": null,
"e": 27223,
"s": 27206,
"text": "mongod --version"
},
{
"code": null,
"e": 27349,
"s": 27223,
"text": "Step 6: If MongoDB is not installed on your virtual machine then at first Install the public key using the following command."
},
{
"code": null,
"e": 27431,
"s": 27349,
"text": "wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -"
},
{
"code": null,
"e": 27452,
"s": 27431,
"text": "Step 7: Add sources."
},
{
"code": null,
"e": 27610,
"s": 27452,
"text": "echo \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list"
},
{
"code": null,
"e": 27681,
"s": 27610,
"text": "Step 8: Reload the local package database using the following command."
},
{
"code": null,
"e": 27697,
"s": 27681,
"text": "sudo apt update"
},
{
"code": null,
"e": 27757,
"s": 27697,
"text": "Step 9: Now install the MongoDB packages using the command."
},
{
"code": null,
"e": 27789,
"s": 27757,
"text": "sudo apt install -y mongodb-org"
},
{
"code": null,
"e": 27827,
"s": 27789,
"text": "Step 10: Wait for the process to end."
},
{
"code": null,
"e": 27974,
"s": 27827,
"text": "Step 11: We have successfully installed MongoDB on our EC2 instance, to check if MongoDB is installed or not, verify using the following command."
},
{
"code": null,
"e": 27991,
"s": 27974,
"text": "mongod --version"
},
{
"code": null,
"e": 28009,
"s": 27991,
"text": "To Start MongoDB:"
},
{
"code": null,
"e": 28038,
"s": 28009,
"text": " sudo systemctl start mongod"
},
{
"code": null,
"e": 28087,
"s": 28038,
"text": "To Verify that MongoDB has started successfully:"
},
{
"code": null,
"e": 28116,
"s": 28087,
"text": "sudo systemctl status mongod"
},
{
"code": null,
"e": 28133,
"s": 28116,
"text": "To Stop MongoDB:"
},
{
"code": null,
"e": 28160,
"s": 28133,
"text": "sudo systemctl stop mongod"
},
{
"code": null,
"e": 28180,
"s": 28160,
"text": "To restart MongoDB:"
},
{
"code": null,
"e": 28210,
"s": 28180,
"text": "sudo systemctl restart mongod"
},
{
"code": null,
"e": 28227,
"s": 28210,
"text": "MongoDB Commands"
},
{
"code": null,
"e": 28426,
"s": 28227,
"text": "In this way, we can install MongoDB on our EC2 instance using EC2 Instance Connect. And if you also use a free tier account, make sure you delete all the resources you have used before logging out. "
},
{
"code": null,
"e": 28441,
"s": 28426,
"text": "how-to-install"
},
{
"code": null,
"e": 28448,
"s": 28441,
"text": "Picked"
},
{
"code": null,
"e": 28455,
"s": 28448,
"text": "How To"
},
{
"code": null,
"e": 28474,
"s": 28455,
"text": "Installation Guide"
},
{
"code": null,
"e": 28572,
"s": 28474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28606,
"s": 28572,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28664,
"s": 28606,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 28713,
"s": 28664,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 28760,
"s": 28713,
"text": "How to create a nested RecyclerView in Android"
},
{
"code": null,
"e": 28802,
"s": 28760,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 28835,
"s": 28802,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28869,
"s": 28835,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 28904,
"s": 28869,
"text": "How to Install Pygame on Windows ?"
},
{
"code": null,
"e": 28962,
"s": 28904,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
}
] |
InputStreamReader class in Java - GeeksforGeeks
|
21 Feb, 2022
An InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted. Declaration :
public class InputStreamReader
extends Reader
Constructors :
InputStreamReader(InputStream in_strm) : Creates an InputStreamReader that uses the default charset.
InputStreamReader(InputStream in_strm, Charset cs) : creates an InputStreamReader that uses the given charset.
InputStreamReader(InputStream in_strm, CharsetDecoder dec) : Creates an InputStreamReader that uses the given charset decoder.
InputStreamReader(InputStream in_strm, String charsetName) : Creates an InputStreamReader that uses the named charset
Methods:
ready() : java.io.InputStreamReader.ready() tells whether the Character stream is ready to be read or not. An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream. Syntax :
public boolean ready()
Returns :
True : if the Character stream is ready to be read
False : if the Character stream is not ready to be read
close() : java.io.InputStreamReader.close() closes InputStreamReader and releases all the Streams associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Syntax :
public void close()
Returns :
No value is returned
Implementation of ready() and close() method :
Java
// Java program illustrating ready() and close() method import java.io.*;public class NewClass{ public static void main(String[] args) { try { // initializing FileInputStream FileInputStream geek = new FileInputStream("ABC.txt"); // Initializing InputStreamReader object InputStreamReader in_strm = new InputStreamReader(geek); int t; while((t=in_strm.read())!= -1) { // convert the integer true to character char r = (char)t; System.out.println("Character : "+r); // check if the stream in_strm ready boolean b = in_strm.ready(); // Use of ready() methods System.out.println("Ready? : "+b); } // Use of close() method to Close InputStreamReader in_strm.close(); // Closing FileInputStream geek.close(); } catch (FileNotFoundException fnfe) { System.out.println("NO Such File Exists"); } catch (IOException except) { System.out.println("IOException occurred"); } }}
Note : All the programs in this article won’t run on online IDE as no ‘ABC’ file exists. You can check this code on Java compiler on your system. To check this code, create a file ‘ABC’ on your system. ‘ABC’ file contains : Geeks For Geeks Output :
Character : G
Ready? : true
Character : e
Ready? : true
Character : e
Ready? : true
Character : k
Ready? : true
Character : s
Ready? : true
Character :
Ready? : true
Character :
Ready? : true
Character :
Ready? : true
Character : F
Ready? : true
Character : o
Ready? : true
Character : r
Ready? : true
Character :
Ready? : true
Character :
Ready? : true
Character :
Ready? : true
Character : G
Ready? : true
Character : e
Ready? : true
Character : e
Ready? : true
Character : k
Ready? : true
Character : s
Ready? : false
getEncoding() : java.io.InputStreamReader.getEncoding() returns the name of the character encoding being used by this stream. Syntax :
public String getEncoding()
Parameters :
Returns :
No value is returned
Implementation of getEncoding() method :
Java
// Java program illustrating getEncoding() method import java.io.*;public class NewClass{ public static void main(String[] args) { try { // initializing FileInputStream FileInputStream geek = new FileInputStream("ABC.txt"); // Initializing InputStreamReader object InputStreamReader in_strm = new InputStreamReader(geek); // Use of getEncoding() method // to get the character encoding present in the stream String encoding = in_strm.getEncoding(); System.out.println("Encoding used : "+encoding); // Closing InputStreamReader in_strm.close(); // Closing FileInputStream geek.close(); } catch (FileNotFoundException fnfe) { System.out.println("NO Such File Exists"); } catch (IOException except) { System.out.println("IOException occurred"); } }}
Output :
Encoding used : UTF8
read() : java.io.InputStreamReader.read() Returns single character after reading. Syntax :
public int read()
Returns :
Returns single character after reading or -1 if the end of the stream has been reached
Implementation :
Java
// Java program illustrating read() method import java.io.*;public class NewClass{ public static void main(String[] args) throws FileNotFoundException, IOException { // initializing FileInputStream FileInputStream geek = new FileInputStream("ABC.txt"); // Initializing InputStreamReader object InputStreamReader in_strm = new InputStreamReader(geek); int t; String read_reslt=""; // Use of read() method while((t = in_strm.read()) != -1) { read_reslt = read_reslt+(char)t; } // print the result read from the file System.out.println(read_reslt); }}
Note : ‘ABC’ file contains : 1 Geeks 2 For 3 Geeks Output :
1
Geeks
2
For
3
Geeks
This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gulshankumarar231
sumitgumber28
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 25603,
"s": 25575,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 25895,
"s": 25603,
"text": "An InputStreamReader is a bridge from byte streams to character streams. It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform’s default charset may be accepted. Declaration : "
},
{
"code": null,
"e": 25944,
"s": 25895,
"text": "public class InputStreamReader\n extends Reader"
},
{
"code": null,
"e": 25960,
"s": 25944,
"text": "Constructors : "
},
{
"code": null,
"e": 26061,
"s": 25960,
"text": "InputStreamReader(InputStream in_strm) : Creates an InputStreamReader that uses the default charset."
},
{
"code": null,
"e": 26172,
"s": 26061,
"text": "InputStreamReader(InputStream in_strm, Charset cs) : creates an InputStreamReader that uses the given charset."
},
{
"code": null,
"e": 26299,
"s": 26172,
"text": "InputStreamReader(InputStream in_strm, CharsetDecoder dec) : Creates an InputStreamReader that uses the given charset decoder."
},
{
"code": null,
"e": 26417,
"s": 26299,
"text": "InputStreamReader(InputStream in_strm, String charsetName) : Creates an InputStreamReader that uses the named charset"
},
{
"code": null,
"e": 26427,
"s": 26417,
"text": "Methods: "
},
{
"code": null,
"e": 26678,
"s": 26427,
"text": "ready() : java.io.InputStreamReader.ready() tells whether the Character stream is ready to be read or not. An InputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read from the underlying byte stream. Syntax : "
},
{
"code": null,
"e": 26818,
"s": 26678,
"text": "public boolean ready()\nReturns :\nTrue : if the Character stream is ready to be read\nFalse : if the Character stream is not ready to be read"
},
{
"code": null,
"e": 27070,
"s": 26818,
"text": "close() : java.io.InputStreamReader.close() closes InputStreamReader and releases all the Streams associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Syntax : "
},
{
"code": null,
"e": 27121,
"s": 27070,
"text": "public void close()\nReturns :\nNo value is returned"
},
{
"code": null,
"e": 27169,
"s": 27121,
"text": "Implementation of ready() and close() method : "
},
{
"code": null,
"e": 27174,
"s": 27169,
"text": "Java"
},
{
"code": "// Java program illustrating ready() and close() method import java.io.*;public class NewClass{ public static void main(String[] args) { try { // initializing FileInputStream FileInputStream geek = new FileInputStream(\"ABC.txt\"); // Initializing InputStreamReader object InputStreamReader in_strm = new InputStreamReader(geek); int t; while((t=in_strm.read())!= -1) { // convert the integer true to character char r = (char)t; System.out.println(\"Character : \"+r); // check if the stream in_strm ready boolean b = in_strm.ready(); // Use of ready() methods System.out.println(\"Ready? : \"+b); } // Use of close() method to Close InputStreamReader in_strm.close(); // Closing FileInputStream geek.close(); } catch (FileNotFoundException fnfe) { System.out.println(\"NO Such File Exists\"); } catch (IOException except) { System.out.println(\"IOException occurred\"); } }}",
"e": 28402,
"s": 27174,
"text": null
},
{
"code": null,
"e": 28652,
"s": 28402,
"text": "Note : All the programs in this article won’t run on online IDE as no ‘ABC’ file exists. You can check this code on Java compiler on your system. To check this code, create a file ‘ABC’ on your system. ‘ABC’ file contains : Geeks For Geeks Output : "
},
{
"code": null,
"e": 29183,
"s": 28652,
"text": "Character : G\nReady? : true\nCharacter : e\nReady? : true\nCharacter : e\nReady? : true\nCharacter : k\nReady? : true\nCharacter : s\nReady? : true\nCharacter : \nReady? : true\nCharacter : \nReady? : true\nCharacter : \n\nReady? : true\nCharacter : F\nReady? : true\nCharacter : o\nReady? : true\nCharacter : r\nReady? : true\nCharacter : \nReady? : true\nCharacter : \nReady? : true\nCharacter : \n\nReady? : true\nCharacter : G\nReady? : true\nCharacter : e\nReady? : true\nCharacter : e\nReady? : true\nCharacter : k\nReady? : true\nCharacter : s\nReady? : false"
},
{
"code": null,
"e": 29319,
"s": 29183,
"text": "getEncoding() : java.io.InputStreamReader.getEncoding() returns the name of the character encoding being used by this stream. Syntax : "
},
{
"code": null,
"e": 29392,
"s": 29319,
"text": "public String getEncoding()\nParameters : \nReturns :\nNo value is returned"
},
{
"code": null,
"e": 29434,
"s": 29392,
"text": "Implementation of getEncoding() method : "
},
{
"code": null,
"e": 29439,
"s": 29434,
"text": "Java"
},
{
"code": "// Java program illustrating getEncoding() method import java.io.*;public class NewClass{ public static void main(String[] args) { try { // initializing FileInputStream FileInputStream geek = new FileInputStream(\"ABC.txt\"); // Initializing InputStreamReader object InputStreamReader in_strm = new InputStreamReader(geek); // Use of getEncoding() method // to get the character encoding present in the stream String encoding = in_strm.getEncoding(); System.out.println(\"Encoding used : \"+encoding); // Closing InputStreamReader in_strm.close(); // Closing FileInputStream geek.close(); } catch (FileNotFoundException fnfe) { System.out.println(\"NO Such File Exists\"); } catch (IOException except) { System.out.println(\"IOException occurred\"); } }}",
"e": 30430,
"s": 29439,
"text": null
},
{
"code": null,
"e": 30440,
"s": 30430,
"text": "Output : "
},
{
"code": null,
"e": 30461,
"s": 30440,
"text": "Encoding used : UTF8"
},
{
"code": null,
"e": 30553,
"s": 30461,
"text": "read() : java.io.InputStreamReader.read() Returns single character after reading. Syntax : "
},
{
"code": null,
"e": 30668,
"s": 30553,
"text": "public int read()\nReturns :\nReturns single character after reading or -1 if the end of the stream has been reached"
},
{
"code": null,
"e": 30686,
"s": 30668,
"text": "Implementation : "
},
{
"code": null,
"e": 30691,
"s": 30686,
"text": "Java"
},
{
"code": "// Java program illustrating read() method import java.io.*;public class NewClass{ public static void main(String[] args) throws FileNotFoundException, IOException { // initializing FileInputStream FileInputStream geek = new FileInputStream(\"ABC.txt\"); // Initializing InputStreamReader object InputStreamReader in_strm = new InputStreamReader(geek); int t; String read_reslt=\"\"; // Use of read() method while((t = in_strm.read()) != -1) { read_reslt = read_reslt+(char)t; } // print the result read from the file System.out.println(read_reslt); }}",
"e": 31353,
"s": 30691,
"text": null
},
{
"code": null,
"e": 31414,
"s": 31353,
"text": "Note : ‘ABC’ file contains : 1 Geeks 2 For 3 Geeks Output : "
},
{
"code": null,
"e": 31438,
"s": 31414,
"text": "1\nGeeks \n2\nFor \n3\nGeeks"
},
{
"code": null,
"e": 31858,
"s": 31438,
"text": "This article is contributed by Mohit Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 31876,
"s": 31858,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 31890,
"s": 31876,
"text": "sumitgumber28"
},
{
"code": null,
"e": 31899,
"s": 31890,
"text": "Java-I/O"
},
{
"code": null,
"e": 31904,
"s": 31899,
"text": "Java"
},
{
"code": null,
"e": 31909,
"s": 31904,
"text": "Java"
},
{
"code": null,
"e": 32007,
"s": 31909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32058,
"s": 32007,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 32088,
"s": 32058,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 32103,
"s": 32088,
"text": "Stream In Java"
},
{
"code": null,
"e": 32122,
"s": 32103,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 32153,
"s": 32122,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 32171,
"s": 32153,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 32203,
"s": 32171,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 32223,
"s": 32203,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 32255,
"s": 32223,
"text": "Multidimensional Arrays in Java"
}
] |
C# Program to Find Greatest Numbers in an Array using WHERE Clause LINQ - GeeksforGeeks
|
18 Oct, 2021
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to find the greatest numbers in an array using WHERE Clause LINQ. Here, we will get the numbers that are greater than a particular number in the given array.
Example:
Input: Array of Integers: 100,200,300,450,324,56,77,890
Value: 500
Output: Numbers greater than 500 are: 890
Input: Array of Integers: 34,56,78,100,200,300,450,324,56,77,890
Value: 100
Output: Numbers greater than 100 are: 200,300,450,324,890
Approach:
To display the greatest numbers in an array using WHERE Clause LINQ follow the following approach:
Store integer(input) in an array.The sum of the elements is calculated using the for loop.The numbers which are greater than particular value is checked using where function.By using the LINQ query we will store the numbers in an iterator.Now the iterator is iterated and the integers are printed.
Store integer(input) in an array.
The sum of the elements is calculated using the for loop.
The numbers which are greater than particular value is checked using where function.
By using the LINQ query we will store the numbers in an iterator.
Now the iterator is iterated and the integers are printed.
Example:
C#
// C# program to print the greatest numbers in an array// using WHERE Clause LINQusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class GFG{ static void Main(){ // Array of numbers int[] array1 = { 34, 56, 78, 100, 200, 300, 450, 324, 56, 77, 890 }; // Now get the numbers greater than 100 and // store in big variable using where clause var big = from value in array1 where value > 100 select value; Console.WriteLine("Numbers that are greater than 100 are :"); // Get the greater numbers foreach (var s in big) { Console.Write(s.ToString() + " "); } Console.Read();}}
Output:
Numbers that are greater than 100 are :
200 300 450 324 890
CSharp LINQ
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Convert String to Character Array in C#
Linked List Implementation in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26078,
"s": 25547,
"text": "LINQ is known as Language Integrated Query and it is introduced in .NET 3.5. It gives the ability to .NET languages to generate queries to retrieve data from the data source. It removes the mismatch between programming languages and databases and the syntax used to create a query is the same no matter which type of data source is used. In this article, we will learn how to find the greatest numbers in an array using WHERE Clause LINQ. Here, we will get the numbers that are greater than a particular number in the given array."
},
{
"code": null,
"e": 26087,
"s": 26078,
"text": "Example:"
},
{
"code": null,
"e": 26337,
"s": 26087,
"text": "Input: Array of Integers: 100,200,300,450,324,56,77,890\nValue: 500\nOutput: Numbers greater than 500 are: 890\n \nInput: Array of Integers: 34,56,78,100,200,300,450,324,56,77,890\nValue: 100\nOutput: Numbers greater than 100 are: 200,300,450,324,890"
},
{
"code": null,
"e": 26347,
"s": 26337,
"text": "Approach:"
},
{
"code": null,
"e": 26446,
"s": 26347,
"text": "To display the greatest numbers in an array using WHERE Clause LINQ follow the following approach:"
},
{
"code": null,
"e": 26744,
"s": 26446,
"text": "Store integer(input) in an array.The sum of the elements is calculated using the for loop.The numbers which are greater than particular value is checked using where function.By using the LINQ query we will store the numbers in an iterator.Now the iterator is iterated and the integers are printed."
},
{
"code": null,
"e": 26778,
"s": 26744,
"text": "Store integer(input) in an array."
},
{
"code": null,
"e": 26836,
"s": 26778,
"text": "The sum of the elements is calculated using the for loop."
},
{
"code": null,
"e": 26921,
"s": 26836,
"text": "The numbers which are greater than particular value is checked using where function."
},
{
"code": null,
"e": 26987,
"s": 26921,
"text": "By using the LINQ query we will store the numbers in an iterator."
},
{
"code": null,
"e": 27046,
"s": 26987,
"text": "Now the iterator is iterated and the integers are printed."
},
{
"code": null,
"e": 27055,
"s": 27046,
"text": "Example:"
},
{
"code": null,
"e": 27058,
"s": 27055,
"text": "C#"
},
{
"code": "// C# program to print the greatest numbers in an array// using WHERE Clause LINQusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks; class GFG{ static void Main(){ // Array of numbers int[] array1 = { 34, 56, 78, 100, 200, 300, 450, 324, 56, 77, 890 }; // Now get the numbers greater than 100 and // store in big variable using where clause var big = from value in array1 where value > 100 select value; Console.WriteLine(\"Numbers that are greater than 100 are :\"); // Get the greater numbers foreach (var s in big) { Console.Write(s.ToString() + \" \"); } Console.Read();}}",
"e": 27774,
"s": 27058,
"text": null
},
{
"code": null,
"e": 27782,
"s": 27774,
"text": "Output:"
},
{
"code": null,
"e": 27844,
"s": 27782,
"text": "Numbers that are greater than 100 are :\n200 300 450 324 890 "
},
{
"code": null,
"e": 27856,
"s": 27844,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 27872,
"s": 27856,
"text": "CSharp-programs"
},
{
"code": null,
"e": 27879,
"s": 27872,
"text": "Picked"
},
{
"code": null,
"e": 27882,
"s": 27879,
"text": "C#"
},
{
"code": null,
"e": 27980,
"s": 27882,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28003,
"s": 27980,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28031,
"s": 28003,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28048,
"s": 28031,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28070,
"s": 28048,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28099,
"s": 28070,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 28139,
"s": 28099,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28182,
"s": 28139,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28205,
"s": 28182,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 28245,
"s": 28205,
"text": "Convert String to Character Array in C#"
}
] |
AngularJS | Form Validation - GeeksforGeeks
|
23 Apr, 2019
AngularJS performs form validation on the client-side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.Form input fields have the following states:
$untouched: It shows that field has not been touched yet.
$touched: It shows that field has been touched.
$pristine: It represents that the field has not been modified yet.
$dirty: It illustrates that the field has been modified.
$invalid:It specifies that the field content is not valid.
$valid:It specifies that the field content is valid.
These all are the properties of the input field which can be either true or false.Forms have the following states:
$pristine: It represents that the fields has not been modified yet.
$dirty: It illustrates that one or more fields has been modified.
$invalid:It specifies that the form content is not valid.
$valid:It specifies that the form content is valid.
$submitted:It specifies that the form is submitted.These all are the properties of the form which can be either true or false.This states can be used to show meaningful messages to the user.Example 1:<!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app=""><form name="form1"><p>Name:<input name="username" ng-model="username" required><span ng-show="form1.username.$pristine && form1.username.$invalid">The name is required.</span></p><p>Address:<input name="useraddress" ng-model="useraddress" required></p></form><p>We use the ng-show directive to only show the error message if the field has not modified yet AND content present in the field is invalid.</p></body></html>Output:Custom validation:To create your own validation function add a new directive to your application, and deal with the validation inside a function with certain specified arguments.Example 2:Create your own directive, containing a custom validation function, and refer to it by using app-directive. The field will only be valid if the value is greater than or equal to 18.<!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app="developapp"><form name="form1">Username:<input name="username" required><br><br>Age:<input name="userage" ng-model="userage" required app-directive></form> <p>The input's valid state is:</p><h1>{{form1.userage.$valid}}</h1><script>var app = angular.module('developapp', []);app.directive('appDirective', function() { return { require: 'ngModel', link: function(scope, element, attr, mCtrl) { function myValidation(value) { if (value >=18) { mCtrl.$setValidity('charE', true); } else { mCtrl.$setValidity('charE', false); } return value; } mCtrl.$parsers.push(myValidation); } };});</script> <p>The input field must have user age greater than 18 to be considered valid for voting.</p> </body></html>Output:My Personal Notes
arrow_drop_upSave
These all are the properties of the form which can be either true or false.This states can be used to show meaningful messages to the user.Example 1:
<!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app=""><form name="form1"><p>Name:<input name="username" ng-model="username" required><span ng-show="form1.username.$pristine && form1.username.$invalid">The name is required.</span></p><p>Address:<input name="useraddress" ng-model="useraddress" required></p></form><p>We use the ng-show directive to only show the error message if the field has not modified yet AND content present in the field is invalid.</p></body></html>
Output:Custom validation:To create your own validation function add a new directive to your application, and deal with the validation inside a function with certain specified arguments.
Example 2:Create your own directive, containing a custom validation function, and refer to it by using app-directive. The field will only be valid if the value is greater than or equal to 18.
<!DOCTYPE html><html><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body ng-app="developapp"><form name="form1">Username:<input name="username" required><br><br>Age:<input name="userage" ng-model="userage" required app-directive></form> <p>The input's valid state is:</p><h1>{{form1.userage.$valid}}</h1><script>var app = angular.module('developapp', []);app.directive('appDirective', function() { return { require: 'ngModel', link: function(scope, element, attr, mCtrl) { function myValidation(value) { if (value >=18) { mCtrl.$setValidity('charE', true); } else { mCtrl.$setValidity('charE', false); } return value; } mCtrl.$parsers.push(myValidation); } };});</script> <p>The input field must have user age greater than 18 to be considered valid for voting.</p> </body></html>
Output:
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 29516,
"s": 29488,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 29847,
"s": 29516,
"text": "AngularJS performs form validation on the client-side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.Form input fields have the following states:"
},
{
"code": null,
"e": 29905,
"s": 29847,
"text": "$untouched: It shows that field has not been touched yet."
},
{
"code": null,
"e": 29953,
"s": 29905,
"text": "$touched: It shows that field has been touched."
},
{
"code": null,
"e": 30020,
"s": 29953,
"text": "$pristine: It represents that the field has not been modified yet."
},
{
"code": null,
"e": 30077,
"s": 30020,
"text": "$dirty: It illustrates that the field has been modified."
},
{
"code": null,
"e": 30136,
"s": 30077,
"text": "$invalid:It specifies that the field content is not valid."
},
{
"code": null,
"e": 30189,
"s": 30136,
"text": "$valid:It specifies that the field content is valid."
},
{
"code": null,
"e": 30304,
"s": 30189,
"text": "These all are the properties of the input field which can be either true or false.Forms have the following states:"
},
{
"code": null,
"e": 30372,
"s": 30304,
"text": "$pristine: It represents that the fields has not been modified yet."
},
{
"code": null,
"e": 30438,
"s": 30372,
"text": "$dirty: It illustrates that one or more fields has been modified."
},
{
"code": null,
"e": 30496,
"s": 30438,
"text": "$invalid:It specifies that the form content is not valid."
},
{
"code": null,
"e": 30548,
"s": 30496,
"text": "$valid:It specifies that the form content is valid."
},
{
"code": null,
"e": 32704,
"s": 30548,
"text": "$submitted:It specifies that the form is submitted.These all are the properties of the form which can be either true or false.This states can be used to show meaningful messages to the user.Example 1:<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <body ng-app=\"\"><form name=\"form1\"><p>Name:<input name=\"username\" ng-model=\"username\" required><span ng-show=\"form1.username.$pristine && form1.username.$invalid\">The name is required.</span></p><p>Address:<input name=\"useraddress\" ng-model=\"useraddress\" required></p></form><p>We use the ng-show directive to only show the error message if the field has not modified yet AND content present in the field is invalid.</p></body></html>Output:Custom validation:To create your own validation function add a new directive to your application, and deal with the validation inside a function with certain specified arguments.Example 2:Create your own directive, containing a custom validation function, and refer to it by using app-directive. The field will only be valid if the value is greater than or equal to 18.<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <body ng-app=\"developapp\"><form name=\"form1\">Username:<input name=\"username\" required><br><br>Age:<input name=\"userage\" ng-model=\"userage\" required app-directive></form> <p>The input's valid state is:</p><h1>{{form1.userage.$valid}}</h1><script>var app = angular.module('developapp', []);app.directive('appDirective', function() { return { require: 'ngModel', link: function(scope, element, attr, mCtrl) { function myValidation(value) { if (value >=18) { mCtrl.$setValidity('charE', true); } else { mCtrl.$setValidity('charE', false); } return value; } mCtrl.$parsers.push(myValidation); } };});</script> <p>The input field must have user age greater than 18 to be considered valid for voting.</p> </body></html>Output:My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 32854,
"s": 32704,
"text": "These all are the properties of the form which can be either true or false.This states can be used to show meaningful messages to the user.Example 1:"
},
{
"code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <body ng-app=\"\"><form name=\"form1\"><p>Name:<input name=\"username\" ng-model=\"username\" required><span ng-show=\"form1.username.$pristine && form1.username.$invalid\">The name is required.</span></p><p>Address:<input name=\"useraddress\" ng-model=\"useraddress\" required></p></form><p>We use the ng-show directive to only show the error message if the field has not modified yet AND content present in the field is invalid.</p></body></html>",
"e": 33404,
"s": 32854,
"text": null
},
{
"code": null,
"e": 33590,
"s": 33404,
"text": "Output:Custom validation:To create your own validation function add a new directive to your application, and deal with the validation inside a function with certain specified arguments."
},
{
"code": null,
"e": 33782,
"s": 33590,
"text": "Example 2:Create your own directive, containing a custom validation function, and refer to it by using app-directive. The field will only be valid if the value is greater than or equal to 18."
},
{
"code": "<!DOCTYPE html><html><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> <body ng-app=\"developapp\"><form name=\"form1\">Username:<input name=\"username\" required><br><br>Age:<input name=\"userage\" ng-model=\"userage\" required app-directive></form> <p>The input's valid state is:</p><h1>{{form1.userage.$valid}}</h1><script>var app = angular.module('developapp', []);app.directive('appDirective', function() { return { require: 'ngModel', link: function(scope, element, attr, mCtrl) { function myValidation(value) { if (value >=18) { mCtrl.$setValidity('charE', true); } else { mCtrl.$setValidity('charE', false); } return value; } mCtrl.$parsers.push(myValidation); } };});</script> <p>The input field must have user age greater than 18 to be considered valid for voting.</p> </body></html>",
"e": 34771,
"s": 33782,
"text": null
},
{
"code": null,
"e": 34779,
"s": 34771,
"text": "Output:"
},
{
"code": null,
"e": 34786,
"s": 34779,
"text": "Picked"
},
{
"code": null,
"e": 34796,
"s": 34786,
"text": "AngularJS"
},
{
"code": null,
"e": 34813,
"s": 34796,
"text": "Web Technologies"
},
{
"code": null,
"e": 34911,
"s": 34813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34931,
"s": 34911,
"text": "Angular File Upload"
},
{
"code": null,
"e": 34966,
"s": 34931,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 34988,
"s": 34966,
"text": "Angular | keyup event"
},
{
"code": null,
"e": 35019,
"s": 34988,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 35107,
"s": 35019,
"text": "How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?"
},
{
"code": null,
"e": 35147,
"s": 35107,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35180,
"s": 35147,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35225,
"s": 35180,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35268,
"s": 35225,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java DIP - Image Compression Technique
|
An image can easily be compressed and stored through Java. Compression of image involves converting an image into jpg and storing it.
In order to compress an image, we read the image and convert into BufferedImage object.
Further, we get an ImageWriter from getImageWritersByFormatName() method found in the ImageIO class. From this ImageWriter, create an ImageWriteParam object. Its syntax is given below −
Iterator<ImageWriter> list = ImageIO.getImageWritersByFormatName("jpg");
ImageWriteParam obj = writer_From_List.getDefaultWriteParam();
From this ImageWriteParam object, you can set the compression by calling these two methods which are setCompressionMode() and setCompressionQuality(). Their syntaxes are as given below −
obj.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
obj.setCompressionQuality(0.05f);
The setCompressionMode() method takes Mode_EXPLICIT as the parameter. Some of the other MODES are described briefly −
MODE_DEFAULT
It is a constant value that may be passed into methods to enable that feature for future writes.
MODE_DISABLED
It is a constant value that may be passed into methods to disable that feature for future writes.
MODE_EXPLICIT
It is a constant value that may be passed into methods to enable that feature for future writes.
Apart from the compressions methods, there are other methods provided by the ImageWriteParam class. They are described briefly −
canOffsetTiles()
It returns true if the writer can perform tiling with non-zero grid offsets while writing.
getBitRate(float quality)
It returns a float indicating an estimate of the number of bits of output data for each bit of input image data at the given quality level.
getLocale()
It returns the currently set Locale, or null if only a default Locale is supported.
isCompressionLossless()
It returns true if the current compression type provides lossless compression.
unsetCompression()
It removes any previous compression type and quality settings.
unsetTiling()
It removes any previous tile grid parameters specified by calls to setTiling.
The following example demonstrates the use of ImageWriteParam class to compress an image −
import java.io.*;
import java.util.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;
class Compression {
public static void main(String[] args) throws IOException {
File input = new File("digital_image_processing.jpg");
BufferedImage image = ImageIO.read(input);
File compressedImageFile = new File("compress.jpg");
OutputStream os =new FileOutputStream(compressedImageFile);
Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = (ImageWriter) writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.05f);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
}
}
When you execute the given code, it compresses the image digital_image_processing.jpg to its equivalent compressed image and writes it on the hard disk with the name compress.jpg.
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": 2471,
"s": 2337,
"text": "An image can easily be compressed and stored through Java. Compression of image involves converting an image into jpg and storing it."
},
{
"code": null,
"e": 2559,
"s": 2471,
"text": "In order to compress an image, we read the image and convert into BufferedImage object."
},
{
"code": null,
"e": 2745,
"s": 2559,
"text": "Further, we get an ImageWriter from getImageWritersByFormatName() method found in the ImageIO class. From this ImageWriter, create an ImageWriteParam object. Its syntax is given below −"
},
{
"code": null,
"e": 2882,
"s": 2745,
"text": "Iterator<ImageWriter> list = ImageIO.getImageWritersByFormatName(\"jpg\");\nImageWriteParam obj = writer_From_List.getDefaultWriteParam();\n"
},
{
"code": null,
"e": 3069,
"s": 2882,
"text": "From this ImageWriteParam object, you can set the compression by calling these two methods which are setCompressionMode() and setCompressionQuality(). Their syntaxes are as given below −"
},
{
"code": null,
"e": 3159,
"s": 3069,
"text": "obj.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\nobj.setCompressionQuality(0.05f);\n"
},
{
"code": null,
"e": 3277,
"s": 3159,
"text": "The setCompressionMode() method takes Mode_EXPLICIT as the parameter. Some of the other MODES are described briefly −"
},
{
"code": null,
"e": 3290,
"s": 3277,
"text": "MODE_DEFAULT"
},
{
"code": null,
"e": 3387,
"s": 3290,
"text": "It is a constant value that may be passed into methods to enable that feature for future writes."
},
{
"code": null,
"e": 3401,
"s": 3387,
"text": "MODE_DISABLED"
},
{
"code": null,
"e": 3499,
"s": 3401,
"text": "It is a constant value that may be passed into methods to disable that feature for future writes."
},
{
"code": null,
"e": 3513,
"s": 3499,
"text": "MODE_EXPLICIT"
},
{
"code": null,
"e": 3610,
"s": 3513,
"text": "It is a constant value that may be passed into methods to enable that feature for future writes."
},
{
"code": null,
"e": 3739,
"s": 3610,
"text": "Apart from the compressions methods, there are other methods provided by the ImageWriteParam class. They are described briefly −"
},
{
"code": null,
"e": 3756,
"s": 3739,
"text": "canOffsetTiles()"
},
{
"code": null,
"e": 3847,
"s": 3756,
"text": "It returns true if the writer can perform tiling with non-zero grid offsets while writing."
},
{
"code": null,
"e": 3873,
"s": 3847,
"text": "getBitRate(float quality)"
},
{
"code": null,
"e": 4013,
"s": 3873,
"text": "It returns a float indicating an estimate of the number of bits of output data for each bit of input image data at the given quality level."
},
{
"code": null,
"e": 4025,
"s": 4013,
"text": "getLocale()"
},
{
"code": null,
"e": 4110,
"s": 4025,
"text": "It returns the currently set Locale, or null if only a default Locale is supported."
},
{
"code": null,
"e": 4134,
"s": 4110,
"text": "isCompressionLossless()"
},
{
"code": null,
"e": 4213,
"s": 4134,
"text": "It returns true if the current compression type provides lossless compression."
},
{
"code": null,
"e": 4232,
"s": 4213,
"text": "unsetCompression()"
},
{
"code": null,
"e": 4295,
"s": 4232,
"text": "It removes any previous compression type and quality settings."
},
{
"code": null,
"e": 4309,
"s": 4295,
"text": "unsetTiling()"
},
{
"code": null,
"e": 4387,
"s": 4309,
"text": "It removes any previous tile grid parameters specified by calls to setTiling."
},
{
"code": null,
"e": 4478,
"s": 4387,
"text": "The following example demonstrates the use of ImageWriteParam class to compress an image −"
},
{
"code": null,
"e": 5490,
"s": 4478,
"text": "import java.io.*;\nimport java.util.*;\nimport java.awt.image.*;\n\nimport javax.imageio.*;\nimport javax.imageio.stream.ImageOutputStream;\n\nclass Compression {\n\n public static void main(String[] args) throws IOException {\n \n File input = new File(\"digital_image_processing.jpg\");\n BufferedImage image = ImageIO.read(input);\n\n File compressedImageFile = new File(\"compress.jpg\");\n OutputStream os =new FileOutputStream(compressedImageFile);\n\n Iterator<ImageWriter>writers = ImageIO.getImageWritersByFormatName(\"jpg\");\n ImageWriter writer = (ImageWriter) writers.next();\n\n ImageOutputStream ios = ImageIO.createImageOutputStream(os);\n writer.setOutput(ios);\n\n ImageWriteParam param = writer.getDefaultWriteParam();\n \n param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n param.setCompressionQuality(0.05f);\n writer.write(null, new IIOImage(image, null, null), param);\n \n os.close();\n ios.close();\n writer.dispose();\n }\n}"
},
{
"code": null,
"e": 5670,
"s": 5490,
"text": "When you execute the given code, it compresses the image digital_image_processing.jpg to its equivalent compressed image and writes it on the hard disk with the name compress.jpg."
},
{
"code": null,
"e": 5703,
"s": 5670,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5719,
"s": 5703,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5752,
"s": 5719,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5768,
"s": 5752,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5803,
"s": 5768,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5817,
"s": 5803,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5851,
"s": 5817,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5865,
"s": 5851,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5902,
"s": 5865,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5917,
"s": 5902,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5950,
"s": 5917,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5969,
"s": 5950,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5976,
"s": 5969,
"text": " Print"
},
{
"code": null,
"e": 5987,
"s": 5976,
"text": " Add Notes"
}
] |
Efficient Frontier Portfolio Optimisation in Python | by Ricky Kim | Towards Data Science
|
My personal interest in finance has led me to take an online course on investment management in Coursera. It is a 5-course specialisation by the University of Geneva partnered with UBS. It is not specifically for financial modelling, but more for general introduction in investment strategies and the theories surrounding them. As someone who doesn’t have any experience in the industry, the course is really helpful to understand the big picture. I am currently on the 3rd course within the specialisation, and I learned something very interesting called “Modern Portfolio Theory”
While I was going through the course, I thought it would be a very good material to practice my Python skills. Even though the course did not provide any technical details of how to actually implement it, with some digging I found a couple of very useful blog posts I can refer to.
Series of Medium blog post by Bernard Brenyah
Markowitz’s Efficient Frontier in Python [Part 1/2]
Markowitz’s Efficient Frontier in Python [Part 2/2]
Blog post by Bradford Lynch
Investment Portfolio Optimization
Based on what I have learned through the course, and also from the above blog posts, I have tried to replicate it in my own way, tweaking bit and pieces along the way.
*In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post.
A good portfolio is more than a long list of good stocks and bonds. It is a balanced whole, providing the investor with protections and opportunities with respect to a wide range of contingencies. – Harry Markowitz
Modern Portfolio Theory (MPT) is an investment theory developed by Harry Markowitz and published under the title “Portfolio Selection” in the Journal of Finance in 1952.
There are a few underlying concepts that can help you understand MPT. If you are familiar with finance, you might know what the acronym “TANSTAAFL” stands for. It is a famous acronym for “There Ain’t No Such Thing As A Free Lunch”. This concept is also closely related to ‘risk-return trade-off’.
Higher risk is associated with greater probability of higher return and lower risk with a greater probability of smaller return. MPT assumes that investors are risk-averse, meaning that given two portfolios that offer the same expected return, investors will prefer the less risky one. Thus, an investor will take on increased risk only if compensated by higher expected returns.
Another factor comes in to play in MPT is “diversification”. Modern portfolio theory says that it is not enough to look at the expected risk and return of one particular stock. By investing in more than one stock, an investor can reap the benefits of diversification — chief among them, a reduction in the riskiness of the portfolio.
What you need to understand is that “risk of a portfolio is not equal to average/weighted-average of individual stocks in the portfolio”. In terms of return, yes it is the average/weighted average of individual stock’s returns, but that’s not the case for risk. The risk is about how volatile the asset is, if you have more than one stock in your portfolio, then you have to take count of how these stocks movement correlates with each other. The beauty of diversification is that you can even get lower risk than a stock with the lowest risk in your portfolio, by optimising the allocation.
I will try to explain as I go along with the actual code. First, let’s start by importing some libraries we need. “Quandl” is a financial platform which also offers Python library. If you haven’t installed it before, of course, you first need to install the package in your command line “pip install quandl”, and before you can use it, you also need to get an API key on Quandl’s website. Sign-up and getting an API key is free but has some limits. As a logged-in free user, you will be able to call 2,000 calls per 10 minutes maximum (speed limit), and 50,000 calls per day (volume limit).
import pandas as pd import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport quandlimport scipy.optimize as scoplt.style.use('fivethirtyeight')np.random.seed(777)%matplotlib inline%config InlineBackend.figure_format = 'retina'
In order to run the below code block, you will need your own API key. The stocks selected for this post is Apple, Amazon, Google, Facebook. Below code block will get daily adjusted closing price of each stock from 01/01/2016 to 31/12/2017 (2 years’ price data).
quandl.ApiConfig.api_key = 'your_api_key_here'stocks = ['AAPL','AMZN','GOOGL','FB']data = quandl.get_table('WIKI/PRICES', ticker = stocks, qopts = { 'columns': ['date', 'ticker', 'adj_close'] }, date = { 'gte': '2016-1-1', 'lte': '2017-12-31' }, paginate=True)data.head()
data.info()
By looking at the info() of data, it seems like the “date” column is already in datetime format. Let’s transform the data a little bit to make it easier to work with.
df = data.set_index('date')table = df.pivot(columns='ticker')# By specifying col[1] in below list comprehension# You can select the stock names under multi-level columntable.columns = [col[1] for col in table.columns]table.head()
It looks much better now. Let’s first look at how the price of each stock has evolved within the given time frame.
plt.figure(figsize=(14, 7))for c in table.columns.values: plt.plot(table.index, table[c], lw=3, alpha=0.8,label=c)plt.legend(loc='upper left', fontsize=12)plt.ylabel('price in $')
It looks like that Amazon and Google’s stock price is relatively more expensive than those of Facebook and Apple. But since Facebook and Apple are squashed at the bottom, it is hard to see the movement of these two.
Another way to plot this is plotting daily returns (percent change compared to the day before). By plotting daily returns instead of actual prices, we can see the stocks’ volatility.
returns = table.pct_change()plt.figure(figsize=(14, 7))for c in returns.columns.values: plt.plot(returns.index, returns[c], lw=3, alpha=0.8,label=c)plt.legend(loc='upper right', fontsize=12)plt.ylabel('daily returns')
Amazon has two distinctive positive spikes and a couple of negative ones. Facebook has one highest positive spike. And Apple also has some spikes stand out from the plot. From the above plot, we can roughly see that Amazon looks like a quite risky stock, and Google seems to be the most stable one among them.
We have 4 stocks in our portfolio. One decision we have to make is how we should allocate our budget to each of stock in our portfolio. If our total budget is 1, then we can decide the weights for each stock, so that the sum of weights will be 1. And the value for weights will be the portion of budget we allocate to a specific stock. For example, if weight is 0.5 for Amazon, it means that we allocate 50% of our budget to Amazon.
Let’s define some functions to simulate random weights to each stock in the portfolio, then calculate the portfolio’s overall annualised returns and annualised volatility.
“portfolio_annualised_performance” function will calculate the returns and volatility, and to make it as an annualised calculation I take into account 252 as the number of trading days in one year. “random_portfolios” function will generate portfolios with random weights assigned to each stock, and by giving num_portfolios argument, you can decide how many random portfolios you want to generate.
From the above code block, there are two things I want to point out.
The first is the calculation for portfolio’s volatility in “portfolio_annualised_performance” function. If you look up “portfolio standard deviation formula”, you will come across formulas as below.
This formula can be simplified if we make use of matrix notation. Again Bernard Brenyah, whom I mentioned at the beginning of the post, has provided a clear explanation of how the above formula can be expressed in matrix calculation in one of his blog posts.
With the above matrix calculation, we get the part inside the square root in the original formula. Now, all we need to do is put them inside the square root. Same as the annualised return, I took into account of 252 trading days (in this case, the square root of 252) to calculate the annualised standard deviation of a portfolio.
The second thing I would like to point out is the Sharpe ratio. In order to understand the Sharpe ratio, it is essential to understand the broader concept of risk-adjusted return. Risk-adjusted return refines an investment’s return by measuring how much risk is involved in producing that return, which is generally expressed as a number or rating. There could be a number of different methods of expressing risk-adjusted return, and the Sharpe ratio is one of them.
The Sharpe ratio was derived in 1966 by William Sharpe, another winner of a Nobel Memorial Prize in Economic Sciences.
The ratio describes how much excess return you are receiving for the extra volatility that you endure for holding a riskier asset. The Sharpe ratio can be expressed in below formula.
There are some criticisms on how the Sharpe ratio uses the standard deviation of returns as a denominator, which assumes the normal distribution of the returns. However, more often than not, the returns on financial assets tend to deviate from a normal distribution and may make interpretations of the Sharpe ratio misleading. It is for this reason that there are other methods which adjust or modify the original Sharpe ratio. But it is a more advanced topic, and I will stick to the traditional Sharpe ratio for this post.
Now let’s get the needed argument values for our functions. You can easily get daily returns by calling pct_change on the data frame with the price data. And the mean daily returns, the covariance matrix of returns are needed to calculate portfolio returns and volatility. We will generate 25,000 random portfolios. Finally, the risk-free rate has been taken from U.S. Department of The Treasury. The rate of 1.78% is the 52week treasury bill rates at the start of 2018. The rationale behind this is that the historical price data is from 2016~2017, and if I assume that I implement this analysis at the start of 2018, the most updated Treasury bill rate is from the start of 2018. And I also chose 52weeks treasury bill rates to match with the annualised return and risk I calculated.
returns = table.pct_change()mean_returns = returns.mean()cov_matrix = returns.cov()num_portfolios = 25000risk_free_rate = 0.0178
Let me briefly explain what below function is doing. First, it generates random portfolio and gets the results (portfolio returns, portfolio volatility, portfolio Sharpe ratio) and weights for the corresponding result. Then by locating the one with the highest Sharpe ratio portfolio, it displays maximum Sharpe ratio portfolio as red star sign. And does similar steps for minimum volatility portfolio, and displays it as a green star on the plot. All the randomly generated portfolios will be also plotted with colour map applied to them based on the Sharpe ratio. Bluer, higher the Sharpe ratio.
And for these two optimal portfolios, it will also show how it allocates the budget within the portfolio.
display_simulated_ef_with_random(mean_returns, cov_matrix, num_portfolios, risk_free_rate)
For minimum risk portfolio, we can see that more than half of our budget is allocated to Google. If you take another look at the daily return plot from earlier, you can see that Google is the least volatile stock of four, so allocating a large percentage to Google for minimum risk portfolio makes intuitive sense.
If we are willing to take higher risk for higher return, one that gives us the best risk-adjusted return is the one with maximum Sharpe ratio. In this scenario, we are allocating a significant portion to Amazon and Facebook, which are quite volatile stocks from the previous plot of daily returns. And Google which had more than 50% in the case of minimum risk portfolio, has less than 1% budget allocated to it.
From the plot of the randomly simulated portfolios, we can see it forms a shape of an arch line on the top of clustered blue dots. This line is called efficient frontier. Why is it efficient? Because points along the line will give you the lowest risk for a given target return. All the other dots right to the line will give you higher risk with same returns. If the expected returns are the same, why would you take an extra risk when there’s an option with lower risk?
The way we found the two kinds of optimal portfolio above was by simulating many possible random choices and pick the best ones (either minimum risk or maximum risk-adjusted return). We can also implement this by using Scipy’s optimize function.
If you are an advanced Excel user, you might be familiar with ‘solver’ function in excel. Scipy’s optimize function is doing the similar task when given what to optimize, and what are constraints and bounds.
Below functions are to get the maximum Sharpe ratio portfolio. In Scipy’s optimize function, there’s no ‘maximize’, so as an objective function you need to pass something that should be minimized. That is why the first “neg_sharpe_ratio” is computing the negative Sharpe ratio. Now we can use this as our objective function to minimize. In “max_sharpe_ratio” function, you first define arguments (this should not include the variables you would like to change for optimisation, in this case, “weights”). At first, the construction of constraints was a bit difficult for me to understand, due to the way it is stated.
constraints = ({‘type’: ‘eq’, ‘fun’: lambda x: np.sum(x) — 1})
The above constraint is saying that sum of x should be equal to 1. You can think of the ‘fun’ part construction as ‘1’ on the right side of equal sign has been moved to the left side of the equal sign.
np.sum(x) == 1 has become np.sum(x)-1
And what does this mean? It simply means that the sum of all the weights should be equal to 1. You cannot allocate more than 100% of your budget in total.
“bounds” is giving another limit to assign random weights, by saying any weight should be inclusively between 0 and 1. You cannot give minus budget allocation to a stock or more than 100% allocation to a stock.
We can also define an optimising function for calculating minimum volatility portfolio. This time we really do minimise objective function. What do we want to minimise? We want to minimise volatility by trying different weights. “constraints” and “bounds” are same as the above.
As I already mentioned above we can also draw a line which depicts where the efficient portfolios for a given risk rate should be. This is called “efficient frontier”. Below I define other functions to compute efficient frontier. The first function “efficient_return” is calculating the most efficient portfolio for a given target return, and the second function “efficient_frontier” will take a range of target returns and compute efficient portfolio for each return level.
Let’s try to plot the portfolio choices with maximum Sharpe ratio and minimum volatility also with all the randomly generated portfolios. But this time, we are not picking the optimal ones from the randomly generated portfolios, but we are actually calculating by using Scipy’s ‘minimize’ function. And the below function will also plot the efficient frontier line.
display_calculated_ef_with_random(mean_returns, cov_matrix, num_portfolios, risk_free_rate)
We have almost the same result as what we have simulated by picking from the randomly generated portfolios. The slight difference is that the Scipy’s “optimize” function has not allocated any budget at all for Google on maximum Sharpe ratio portfolio, while one we chose from the randomly generated samples has 0.45% of allocation for Google. There are some differences in the decimal places but more or less same.
Instead of plotting every randomly generated portfolio, we can plot each individual stocks on the plot with the corresponding values of each stock’s annual return and annual risk. This way we can see and compare how diversification is lowering the risk by optimising the allocation.
display_ef_with_selected(mean_returns, cov_matrix, risk_free_rate)
As you can see from the above plot, the stock with the least risk is Google at around 0.18. But with portfolio optimisation, we can achieve even lower risk at 0.16, and still with a higher return than Google. And if we are willing to take slightly more risk at around the similar level of risk of Google, we can achieve a much higher return of 0.30 with portfolio optimisation.
Considering how vast and the deep the finance field is, I’ve probably only scratched the surface. But I had fun going through coding and trying to understand the concept. And I’m learning every day. After finishing this implementation, I definitely know better than yesterday’s me. And if I keep on going and learning, in about a couple of year’s time, I will know a whole lot more than today’s me. If you have any comments or questions, feel free to leave a comment. Any feedback would be appreciated.
Thank you for reading. You can find the Jupyter Notebook from the below link.
|
[
{
"code": null,
"e": 754,
"s": 172,
"text": "My personal interest in finance has led me to take an online course on investment management in Coursera. It is a 5-course specialisation by the University of Geneva partnered with UBS. It is not specifically for financial modelling, but more for general introduction in investment strategies and the theories surrounding them. As someone who doesn’t have any experience in the industry, the course is really helpful to understand the big picture. I am currently on the 3rd course within the specialisation, and I learned something very interesting called “Modern Portfolio Theory”"
},
{
"code": null,
"e": 1036,
"s": 754,
"text": "While I was going through the course, I thought it would be a very good material to practice my Python skills. Even though the course did not provide any technical details of how to actually implement it, with some digging I found a couple of very useful blog posts I can refer to."
},
{
"code": null,
"e": 1082,
"s": 1036,
"text": "Series of Medium blog post by Bernard Brenyah"
},
{
"code": null,
"e": 1134,
"s": 1082,
"text": "Markowitz’s Efficient Frontier in Python [Part 1/2]"
},
{
"code": null,
"e": 1186,
"s": 1134,
"text": "Markowitz’s Efficient Frontier in Python [Part 2/2]"
},
{
"code": null,
"e": 1214,
"s": 1186,
"text": "Blog post by Bradford Lynch"
},
{
"code": null,
"e": 1248,
"s": 1214,
"text": "Investment Portfolio Optimization"
},
{
"code": null,
"e": 1416,
"s": 1248,
"text": "Based on what I have learned through the course, and also from the above blog posts, I have tried to replicate it in my own way, tweaking bit and pieces along the way."
},
{
"code": null,
"e": 1543,
"s": 1416,
"text": "*In addition to short code blocks I will attach, you can find the link for the whole Jupyter Notebook at the end of this post."
},
{
"code": null,
"e": 1758,
"s": 1543,
"text": "A good portfolio is more than a long list of good stocks and bonds. It is a balanced whole, providing the investor with protections and opportunities with respect to a wide range of contingencies. – Harry Markowitz"
},
{
"code": null,
"e": 1928,
"s": 1758,
"text": "Modern Portfolio Theory (MPT) is an investment theory developed by Harry Markowitz and published under the title “Portfolio Selection” in the Journal of Finance in 1952."
},
{
"code": null,
"e": 2225,
"s": 1928,
"text": "There are a few underlying concepts that can help you understand MPT. If you are familiar with finance, you might know what the acronym “TANSTAAFL” stands for. It is a famous acronym for “There Ain’t No Such Thing As A Free Lunch”. This concept is also closely related to ‘risk-return trade-off’."
},
{
"code": null,
"e": 2605,
"s": 2225,
"text": "Higher risk is associated with greater probability of higher return and lower risk with a greater probability of smaller return. MPT assumes that investors are risk-averse, meaning that given two portfolios that offer the same expected return, investors will prefer the less risky one. Thus, an investor will take on increased risk only if compensated by higher expected returns."
},
{
"code": null,
"e": 2939,
"s": 2605,
"text": "Another factor comes in to play in MPT is “diversification”. Modern portfolio theory says that it is not enough to look at the expected risk and return of one particular stock. By investing in more than one stock, an investor can reap the benefits of diversification — chief among them, a reduction in the riskiness of the portfolio."
},
{
"code": null,
"e": 3531,
"s": 2939,
"text": "What you need to understand is that “risk of a portfolio is not equal to average/weighted-average of individual stocks in the portfolio”. In terms of return, yes it is the average/weighted average of individual stock’s returns, but that’s not the case for risk. The risk is about how volatile the asset is, if you have more than one stock in your portfolio, then you have to take count of how these stocks movement correlates with each other. The beauty of diversification is that you can even get lower risk than a stock with the lowest risk in your portfolio, by optimising the allocation."
},
{
"code": null,
"e": 4122,
"s": 3531,
"text": "I will try to explain as I go along with the actual code. First, let’s start by importing some libraries we need. “Quandl” is a financial platform which also offers Python library. If you haven’t installed it before, of course, you first need to install the package in your command line “pip install quandl”, and before you can use it, you also need to get an API key on Quandl’s website. Sign-up and getting an API key is free but has some limits. As a logged-in free user, you will be able to call 2,000 calls per 10 minutes maximum (speed limit), and 50,000 calls per day (volume limit)."
},
{
"code": null,
"e": 4370,
"s": 4122,
"text": "import pandas as pd import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport quandlimport scipy.optimize as scoplt.style.use('fivethirtyeight')np.random.seed(777)%matplotlib inline%config InlineBackend.figure_format = 'retina'"
},
{
"code": null,
"e": 4632,
"s": 4370,
"text": "In order to run the below code block, you will need your own API key. The stocks selected for this post is Apple, Amazon, Google, Facebook. Below code block will get daily adjusted closing price of each stock from 01/01/2016 to 31/12/2017 (2 years’ price data)."
},
{
"code": null,
"e": 4950,
"s": 4632,
"text": "quandl.ApiConfig.api_key = 'your_api_key_here'stocks = ['AAPL','AMZN','GOOGL','FB']data = quandl.get_table('WIKI/PRICES', ticker = stocks, qopts = { 'columns': ['date', 'ticker', 'adj_close'] }, date = { 'gte': '2016-1-1', 'lte': '2017-12-31' }, paginate=True)data.head()"
},
{
"code": null,
"e": 4962,
"s": 4950,
"text": "data.info()"
},
{
"code": null,
"e": 5129,
"s": 4962,
"text": "By looking at the info() of data, it seems like the “date” column is already in datetime format. Let’s transform the data a little bit to make it easier to work with."
},
{
"code": null,
"e": 5359,
"s": 5129,
"text": "df = data.set_index('date')table = df.pivot(columns='ticker')# By specifying col[1] in below list comprehension# You can select the stock names under multi-level columntable.columns = [col[1] for col in table.columns]table.head()"
},
{
"code": null,
"e": 5474,
"s": 5359,
"text": "It looks much better now. Let’s first look at how the price of each stock has evolved within the given time frame."
},
{
"code": null,
"e": 5657,
"s": 5474,
"text": "plt.figure(figsize=(14, 7))for c in table.columns.values: plt.plot(table.index, table[c], lw=3, alpha=0.8,label=c)plt.legend(loc='upper left', fontsize=12)plt.ylabel('price in $')"
},
{
"code": null,
"e": 5873,
"s": 5657,
"text": "It looks like that Amazon and Google’s stock price is relatively more expensive than those of Facebook and Apple. But since Facebook and Apple are squashed at the bottom, it is hard to see the movement of these two."
},
{
"code": null,
"e": 6056,
"s": 5873,
"text": "Another way to plot this is plotting daily returns (percent change compared to the day before). By plotting daily returns instead of actual prices, we can see the stocks’ volatility."
},
{
"code": null,
"e": 6277,
"s": 6056,
"text": "returns = table.pct_change()plt.figure(figsize=(14, 7))for c in returns.columns.values: plt.plot(returns.index, returns[c], lw=3, alpha=0.8,label=c)plt.legend(loc='upper right', fontsize=12)plt.ylabel('daily returns')"
},
{
"code": null,
"e": 6587,
"s": 6277,
"text": "Amazon has two distinctive positive spikes and a couple of negative ones. Facebook has one highest positive spike. And Apple also has some spikes stand out from the plot. From the above plot, we can roughly see that Amazon looks like a quite risky stock, and Google seems to be the most stable one among them."
},
{
"code": null,
"e": 7020,
"s": 6587,
"text": "We have 4 stocks in our portfolio. One decision we have to make is how we should allocate our budget to each of stock in our portfolio. If our total budget is 1, then we can decide the weights for each stock, so that the sum of weights will be 1. And the value for weights will be the portion of budget we allocate to a specific stock. For example, if weight is 0.5 for Amazon, it means that we allocate 50% of our budget to Amazon."
},
{
"code": null,
"e": 7192,
"s": 7020,
"text": "Let’s define some functions to simulate random weights to each stock in the portfolio, then calculate the portfolio’s overall annualised returns and annualised volatility."
},
{
"code": null,
"e": 7591,
"s": 7192,
"text": "“portfolio_annualised_performance” function will calculate the returns and volatility, and to make it as an annualised calculation I take into account 252 as the number of trading days in one year. “random_portfolios” function will generate portfolios with random weights assigned to each stock, and by giving num_portfolios argument, you can decide how many random portfolios you want to generate."
},
{
"code": null,
"e": 7660,
"s": 7591,
"text": "From the above code block, there are two things I want to point out."
},
{
"code": null,
"e": 7859,
"s": 7660,
"text": "The first is the calculation for portfolio’s volatility in “portfolio_annualised_performance” function. If you look up “portfolio standard deviation formula”, you will come across formulas as below."
},
{
"code": null,
"e": 8118,
"s": 7859,
"text": "This formula can be simplified if we make use of matrix notation. Again Bernard Brenyah, whom I mentioned at the beginning of the post, has provided a clear explanation of how the above formula can be expressed in matrix calculation in one of his blog posts."
},
{
"code": null,
"e": 8449,
"s": 8118,
"text": "With the above matrix calculation, we get the part inside the square root in the original formula. Now, all we need to do is put them inside the square root. Same as the annualised return, I took into account of 252 trading days (in this case, the square root of 252) to calculate the annualised standard deviation of a portfolio."
},
{
"code": null,
"e": 8916,
"s": 8449,
"text": "The second thing I would like to point out is the Sharpe ratio. In order to understand the Sharpe ratio, it is essential to understand the broader concept of risk-adjusted return. Risk-adjusted return refines an investment’s return by measuring how much risk is involved in producing that return, which is generally expressed as a number or rating. There could be a number of different methods of expressing risk-adjusted return, and the Sharpe ratio is one of them."
},
{
"code": null,
"e": 9035,
"s": 8916,
"text": "The Sharpe ratio was derived in 1966 by William Sharpe, another winner of a Nobel Memorial Prize in Economic Sciences."
},
{
"code": null,
"e": 9218,
"s": 9035,
"text": "The ratio describes how much excess return you are receiving for the extra volatility that you endure for holding a riskier asset. The Sharpe ratio can be expressed in below formula."
},
{
"code": null,
"e": 9743,
"s": 9218,
"text": "There are some criticisms on how the Sharpe ratio uses the standard deviation of returns as a denominator, which assumes the normal distribution of the returns. However, more often than not, the returns on financial assets tend to deviate from a normal distribution and may make interpretations of the Sharpe ratio misleading. It is for this reason that there are other methods which adjust or modify the original Sharpe ratio. But it is a more advanced topic, and I will stick to the traditional Sharpe ratio for this post."
},
{
"code": null,
"e": 10529,
"s": 9743,
"text": "Now let’s get the needed argument values for our functions. You can easily get daily returns by calling pct_change on the data frame with the price data. And the mean daily returns, the covariance matrix of returns are needed to calculate portfolio returns and volatility. We will generate 25,000 random portfolios. Finally, the risk-free rate has been taken from U.S. Department of The Treasury. The rate of 1.78% is the 52week treasury bill rates at the start of 2018. The rationale behind this is that the historical price data is from 2016~2017, and if I assume that I implement this analysis at the start of 2018, the most updated Treasury bill rate is from the start of 2018. And I also chose 52weeks treasury bill rates to match with the annualised return and risk I calculated."
},
{
"code": null,
"e": 10658,
"s": 10529,
"text": "returns = table.pct_change()mean_returns = returns.mean()cov_matrix = returns.cov()num_portfolios = 25000risk_free_rate = 0.0178"
},
{
"code": null,
"e": 11256,
"s": 10658,
"text": "Let me briefly explain what below function is doing. First, it generates random portfolio and gets the results (portfolio returns, portfolio volatility, portfolio Sharpe ratio) and weights for the corresponding result. Then by locating the one with the highest Sharpe ratio portfolio, it displays maximum Sharpe ratio portfolio as red star sign. And does similar steps for minimum volatility portfolio, and displays it as a green star on the plot. All the randomly generated portfolios will be also plotted with colour map applied to them based on the Sharpe ratio. Bluer, higher the Sharpe ratio."
},
{
"code": null,
"e": 11362,
"s": 11256,
"text": "And for these two optimal portfolios, it will also show how it allocates the budget within the portfolio."
},
{
"code": null,
"e": 11453,
"s": 11362,
"text": "display_simulated_ef_with_random(mean_returns, cov_matrix, num_portfolios, risk_free_rate)"
},
{
"code": null,
"e": 11768,
"s": 11453,
"text": "For minimum risk portfolio, we can see that more than half of our budget is allocated to Google. If you take another look at the daily return plot from earlier, you can see that Google is the least volatile stock of four, so allocating a large percentage to Google for minimum risk portfolio makes intuitive sense."
},
{
"code": null,
"e": 12181,
"s": 11768,
"text": "If we are willing to take higher risk for higher return, one that gives us the best risk-adjusted return is the one with maximum Sharpe ratio. In this scenario, we are allocating a significant portion to Amazon and Facebook, which are quite volatile stocks from the previous plot of daily returns. And Google which had more than 50% in the case of minimum risk portfolio, has less than 1% budget allocated to it."
},
{
"code": null,
"e": 12653,
"s": 12181,
"text": "From the plot of the randomly simulated portfolios, we can see it forms a shape of an arch line on the top of clustered blue dots. This line is called efficient frontier. Why is it efficient? Because points along the line will give you the lowest risk for a given target return. All the other dots right to the line will give you higher risk with same returns. If the expected returns are the same, why would you take an extra risk when there’s an option with lower risk?"
},
{
"code": null,
"e": 12899,
"s": 12653,
"text": "The way we found the two kinds of optimal portfolio above was by simulating many possible random choices and pick the best ones (either minimum risk or maximum risk-adjusted return). We can also implement this by using Scipy’s optimize function."
},
{
"code": null,
"e": 13107,
"s": 12899,
"text": "If you are an advanced Excel user, you might be familiar with ‘solver’ function in excel. Scipy’s optimize function is doing the similar task when given what to optimize, and what are constraints and bounds."
},
{
"code": null,
"e": 13724,
"s": 13107,
"text": "Below functions are to get the maximum Sharpe ratio portfolio. In Scipy’s optimize function, there’s no ‘maximize’, so as an objective function you need to pass something that should be minimized. That is why the first “neg_sharpe_ratio” is computing the negative Sharpe ratio. Now we can use this as our objective function to minimize. In “max_sharpe_ratio” function, you first define arguments (this should not include the variables you would like to change for optimisation, in this case, “weights”). At first, the construction of constraints was a bit difficult for me to understand, due to the way it is stated."
},
{
"code": null,
"e": 13787,
"s": 13724,
"text": "constraints = ({‘type’: ‘eq’, ‘fun’: lambda x: np.sum(x) — 1})"
},
{
"code": null,
"e": 13989,
"s": 13787,
"text": "The above constraint is saying that sum of x should be equal to 1. You can think of the ‘fun’ part construction as ‘1’ on the right side of equal sign has been moved to the left side of the equal sign."
},
{
"code": null,
"e": 14027,
"s": 13989,
"text": "np.sum(x) == 1 has become np.sum(x)-1"
},
{
"code": null,
"e": 14182,
"s": 14027,
"text": "And what does this mean? It simply means that the sum of all the weights should be equal to 1. You cannot allocate more than 100% of your budget in total."
},
{
"code": null,
"e": 14393,
"s": 14182,
"text": "“bounds” is giving another limit to assign random weights, by saying any weight should be inclusively between 0 and 1. You cannot give minus budget allocation to a stock or more than 100% allocation to a stock."
},
{
"code": null,
"e": 14672,
"s": 14393,
"text": "We can also define an optimising function for calculating minimum volatility portfolio. This time we really do minimise objective function. What do we want to minimise? We want to minimise volatility by trying different weights. “constraints” and “bounds” are same as the above."
},
{
"code": null,
"e": 15147,
"s": 14672,
"text": "As I already mentioned above we can also draw a line which depicts where the efficient portfolios for a given risk rate should be. This is called “efficient frontier”. Below I define other functions to compute efficient frontier. The first function “efficient_return” is calculating the most efficient portfolio for a given target return, and the second function “efficient_frontier” will take a range of target returns and compute efficient portfolio for each return level."
},
{
"code": null,
"e": 15513,
"s": 15147,
"text": "Let’s try to plot the portfolio choices with maximum Sharpe ratio and minimum volatility also with all the randomly generated portfolios. But this time, we are not picking the optimal ones from the randomly generated portfolios, but we are actually calculating by using Scipy’s ‘minimize’ function. And the below function will also plot the efficient frontier line."
},
{
"code": null,
"e": 15605,
"s": 15513,
"text": "display_calculated_ef_with_random(mean_returns, cov_matrix, num_portfolios, risk_free_rate)"
},
{
"code": null,
"e": 16020,
"s": 15605,
"text": "We have almost the same result as what we have simulated by picking from the randomly generated portfolios. The slight difference is that the Scipy’s “optimize” function has not allocated any budget at all for Google on maximum Sharpe ratio portfolio, while one we chose from the randomly generated samples has 0.45% of allocation for Google. There are some differences in the decimal places but more or less same."
},
{
"code": null,
"e": 16303,
"s": 16020,
"text": "Instead of plotting every randomly generated portfolio, we can plot each individual stocks on the plot with the corresponding values of each stock’s annual return and annual risk. This way we can see and compare how diversification is lowering the risk by optimising the allocation."
},
{
"code": null,
"e": 16370,
"s": 16303,
"text": "display_ef_with_selected(mean_returns, cov_matrix, risk_free_rate)"
},
{
"code": null,
"e": 16748,
"s": 16370,
"text": "As you can see from the above plot, the stock with the least risk is Google at around 0.18. But with portfolio optimisation, we can achieve even lower risk at 0.16, and still with a higher return than Google. And if we are willing to take slightly more risk at around the similar level of risk of Google, we can achieve a much higher return of 0.30 with portfolio optimisation."
},
{
"code": null,
"e": 17251,
"s": 16748,
"text": "Considering how vast and the deep the finance field is, I’ve probably only scratched the surface. But I had fun going through coding and trying to understand the concept. And I’m learning every day. After finishing this implementation, I definitely know better than yesterday’s me. And if I keep on going and learning, in about a couple of year’s time, I will know a whole lot more than today’s me. If you have any comments or questions, feel free to leave a comment. Any feedback would be appreciated."
}
] |
Implementing K-Nearest Neighbors in scikit-learn | by Chaim Gluck | Towards Data Science
|
We’ll be using the iris data set, available here from the UCI Machine Learning. It’s a small data set with easily distinguishable clusters that’s very useful for demonstrations like this one. It contains 150 observations of iris plants of three species: setosa, versicolor, and virginica. The task is to identify the species of each plant based on their nearest neighbors.
K-Nearest Neighbors is a method that simply looks at the observation that are nearest to the one it’s trying to predict, and classifies the point of interest based on the majority of those around it.
I used the following code to load the data into a pandas DataFrame:
## load the iris data into a DataFrameimport pandas as pdurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' ## Specifying column names.col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']iris = pd.read_csv(url, header=None, names=col_names)
Here’s a look at the data:
Below, I’ve plotted the petal length and width divided by class so you can see how separable the classes are.
Now, in order to model the data I ran through a couple of preprocessing steps. First, I mapped the species names to a number, so I can run my Classifier against it. The code for that is as follows:
## map each iris species to a number with a dictionary and list comprehension.iris_class = {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}iris['species_num'] = [iris_class[i] for i in iris.species]
Split the data into our modeling and target variables, our X and y:
## Create an 'X' matrix by dropping the irrelevant columns.X = iris.drop(['species', 'species_num'], axis=1)y = iris.species_num
Train-test split:
from sklearn.model_selection import train_test_split## Split data into training and testing sets.X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
And we’re ready for the model. In the code below, we’ll import the Classifier, instantiate the model, fit it on the training data, and score it on the test data. Note that you can change the number of nearest neighbors it uses to classify each point.
## Import the Classifier.from sklearn.neighbors import KNeighborsClassifier## Instantiate the model with 5 neighbors. knn = KNeighborsClassifier(n_neighbors=5)## Fit the model on the training data.knn.fit(X_train, y_train)## See how the model performs on the test data.knn.score(X_test, y_test)
The model actually has a 100% accuracy score, since this is a very simplistic data set with distinctly separable classes. But there you have it. That’s how to implement K-Nearest Neighbors with scikit-learn. Load your favorite data set and give it a try!
|
[
{
"code": null,
"e": 544,
"s": 171,
"text": "We’ll be using the iris data set, available here from the UCI Machine Learning. It’s a small data set with easily distinguishable clusters that’s very useful for demonstrations like this one. It contains 150 observations of iris plants of three species: setosa, versicolor, and virginica. The task is to identify the species of each plant based on their nearest neighbors."
},
{
"code": null,
"e": 744,
"s": 544,
"text": "K-Nearest Neighbors is a method that simply looks at the observation that are nearest to the one it’s trying to predict, and classifies the point of interest based on the majority of those around it."
},
{
"code": null,
"e": 812,
"s": 744,
"text": "I used the following code to load the data into a pandas DataFrame:"
},
{
"code": null,
"e": 1115,
"s": 812,
"text": "## load the iris data into a DataFrameimport pandas as pdurl = 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' ## Specifying column names.col_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']iris = pd.read_csv(url, header=None, names=col_names)"
},
{
"code": null,
"e": 1142,
"s": 1115,
"text": "Here’s a look at the data:"
},
{
"code": null,
"e": 1252,
"s": 1142,
"text": "Below, I’ve plotted the petal length and width divided by class so you can see how separable the classes are."
},
{
"code": null,
"e": 1450,
"s": 1252,
"text": "Now, in order to model the data I ran through a couple of preprocessing steps. First, I mapped the species names to a number, so I can run my Classifier against it. The code for that is as follows:"
},
{
"code": null,
"e": 1659,
"s": 1450,
"text": "## map each iris species to a number with a dictionary and list comprehension.iris_class = {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}iris['species_num'] = [iris_class[i] for i in iris.species]"
},
{
"code": null,
"e": 1727,
"s": 1659,
"text": "Split the data into our modeling and target variables, our X and y:"
},
{
"code": null,
"e": 1856,
"s": 1727,
"text": "## Create an 'X' matrix by dropping the irrelevant columns.X = iris.drop(['species', 'species_num'], axis=1)y = iris.species_num"
},
{
"code": null,
"e": 1874,
"s": 1856,
"text": "Train-test split:"
},
{
"code": null,
"e": 2046,
"s": 1874,
"text": "from sklearn.model_selection import train_test_split## Split data into training and testing sets.X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)"
},
{
"code": null,
"e": 2297,
"s": 2046,
"text": "And we’re ready for the model. In the code below, we’ll import the Classifier, instantiate the model, fit it on the training data, and score it on the test data. Note that you can change the number of nearest neighbors it uses to classify each point."
},
{
"code": null,
"e": 2592,
"s": 2297,
"text": "## Import the Classifier.from sklearn.neighbors import KNeighborsClassifier## Instantiate the model with 5 neighbors. knn = KNeighborsClassifier(n_neighbors=5)## Fit the model on the training data.knn.fit(X_train, y_train)## See how the model performs on the test data.knn.score(X_test, y_test)"
}
] |
How to animate a straight line in linear motion using CSS ? - GeeksforGeeks
|
27 Apr, 2020
The linear motion of a straight line means the line will start from one point, goes to the second point, and then came back to the starting point. It is a kind of to and from motion. We will be doing it using CSS only.
Approach: The approach is to first create a straight line and then animate it using keyframes. It will be done in a two-step. First for forwarding movement and second for backward movement. The below code will follow the same approach.
HTML: In HTML, we have created a div element that is used to make a straight line.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title>GeeksforGeeks</title></head> <body> <div class="geeks"></div></body> </html>
CSS:
Create a straight line by providing minimum height and width of your preference.
Animate this straight line using before selector and provide it a linear animation with keyframes identifier named as animate.
The animation for keyframes is very simple. For the first half-frames make width 100%(forward movement) and then reduce it to 0%(backward movement) for the next half frames.
<style> body { margin: 0; padding: 0; background: green; } .geeks { width: 400px; height: 2px; background: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .geeks::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: green; animation: animate 5s linear infinite; } @keyframes animate { 0% { left: 0; } 50% { left: 100%; } 0% { left: 0; } }</style>
Complete Code: In this section, we will combine both HTML and CSS code to make a straight line animation effect.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content= "width=device-width, initial-scale=1.0" /> <title> How to animate a straight line in linear motion? </title> <style> body { margin: 0; padding: 0; background: green; } .geeks { width: 400px; height: 2px; background: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .geeks::before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: green; animation: animate 5s linear infinite; } @keyframes animate { 0% { left: 0; } 50% { left: 100%; } 0% { left: 0; } } </style></head> <body> <div class="geeks"></div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
HTML-Basics
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
Types of CSS (Cascading Style Sheet)
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 31370,
"s": 31342,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 31589,
"s": 31370,
"text": "The linear motion of a straight line means the line will start from one point, goes to the second point, and then came back to the starting point. It is a kind of to and from motion. We will be doing it using CSS only."
},
{
"code": null,
"e": 31825,
"s": 31589,
"text": "Approach: The approach is to first create a straight line and then animate it using keyframes. It will be done in a two-step. First for forwarding movement and second for backward movement. The below code will follow the same approach."
},
{
"code": null,
"e": 31908,
"s": 31825,
"text": "HTML: In HTML, we have created a div element that is used to make a straight line."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title>GeeksforGeeks</title></head> <body> <div class=\"geeks\"></div></body> </html>",
"e": 32152,
"s": 31908,
"text": null
},
{
"code": null,
"e": 32157,
"s": 32152,
"text": "CSS:"
},
{
"code": null,
"e": 32238,
"s": 32157,
"text": "Create a straight line by providing minimum height and width of your preference."
},
{
"code": null,
"e": 32365,
"s": 32238,
"text": "Animate this straight line using before selector and provide it a linear animation with keyframes identifier named as animate."
},
{
"code": null,
"e": 32539,
"s": 32365,
"text": "The animation for keyframes is very simple. For the first half-frames make width 100%(forward movement) and then reduce it to 0%(backward movement) for the next half frames."
},
{
"code": "<style> body { margin: 0; padding: 0; background: green; } .geeks { width: 400px; height: 2px; background: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .geeks::before { content: \"\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: green; animation: animate 5s linear infinite; } @keyframes animate { 0% { left: 0; } 50% { left: 100%; } 0% { left: 0; } }</style>",
"e": 33201,
"s": 32539,
"text": null
},
{
"code": null,
"e": 33314,
"s": 33201,
"text": "Complete Code: In this section, we will combine both HTML and CSS code to make a straight line animation effect."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\" /> <title> How to animate a straight line in linear motion? </title> <style> body { margin: 0; padding: 0; background: green; } .geeks { width: 400px; height: 2px; background: #fff; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .geeks::before { content: \"\"; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: green; animation: animate 5s linear infinite; } @keyframes animate { 0% { left: 0; } 50% { left: 100%; } 0% { left: 0; } } </style></head> <body> <div class=\"geeks\"></div></body> </html>",
"e": 34433,
"s": 33314,
"text": null
},
{
"code": null,
"e": 34441,
"s": 34433,
"text": "Output:"
},
{
"code": null,
"e": 34578,
"s": 34441,
"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": 34593,
"s": 34578,
"text": "CSS-Properties"
},
{
"code": null,
"e": 34605,
"s": 34593,
"text": "HTML-Basics"
},
{
"code": null,
"e": 34609,
"s": 34605,
"text": "CSS"
},
{
"code": null,
"e": 34614,
"s": 34609,
"text": "HTML"
},
{
"code": null,
"e": 34631,
"s": 34614,
"text": "Web Technologies"
},
{
"code": null,
"e": 34658,
"s": 34631,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34663,
"s": 34658,
"text": "HTML"
},
{
"code": null,
"e": 34761,
"s": 34663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34770,
"s": 34761,
"text": "Comments"
},
{
"code": null,
"e": 34783,
"s": 34770,
"text": "Old Comments"
},
{
"code": null,
"e": 34845,
"s": 34783,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34895,
"s": 34845,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34953,
"s": 34895,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 35001,
"s": 34953,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35038,
"s": 35001,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 35100,
"s": 35038,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35150,
"s": 35100,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35210,
"s": 35150,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 35258,
"s": 35210,
"text": "How to update Node.js and NPM to next version ?"
}
] |
Accolite Digital Interview Experience (SheCodes) | On-Campus - GeeksforGeeks
|
16 Sep, 2021
Accolite Digital started their drive at our college through SheCodes hiring on August 2021.
Role: Software Engineer
Drive: SheCodes
Offer-type: Internship+FTE
Round 1: Online MCQ Test
This was an MCQ round. It consisted of DSA, logical and numerical reasoning, quantitative aptitude, Networking, OS questions. This round mainly assessed our domain knowledge. There were 30 questions and 30 minutes were given to complete. The test was conducted on the Eduthrill platform, which is one of the products of Accolite Digital. The questions in this round were of easy to moderate difficulty.
Round 2: Online Coding Test
Those who performed well in Round 1 were shortlisted for Round 2. This was a coding round. There was one coding question allotted with one hour of time.
question: Give the minimum number of steps to convert an array of zeros to a given target array.
This question was given in a different way with a scenario and we had to provide the best solution in one hour’s time. The test was conducted on their platform catalyzer.
Round 3: Technical Interview 1
Shortlists from round 2 were taken to interview rounds. Only 3 girls from the college were selected for interviews.
The interviewer initially introduced himself and then asked my introduction. Then he asked me 3 coding questions and few questions on DSA concepts. For coding, I used GeeksforGeeks online editor.
Remove contiguous characters from a given string such that there are no duplicates. For eg: AAAABABBABB should be converted to ABABAB. I gave both O(n2) and O(n) solutions. Coded for O(n) as it is the optimized one. The interviewer was satisfied with the solution.
Later, he asked me to explain the approach for detecting cycles in a graph. I explained to him DFS but was not so sure of the correct approach and hence he asked me two more questions on a union-find algorithm and disjoint-set data structure as in dropping hint for me to answer the question. I explained a different approach, he wasn’t completely satisfied with it but then he mentioned that the answer was somewhat close.
He asked me to explain the tree traversals and code for preorder traversal. I explained it clearly and coded the same with a recursive approach. He was satisfied with the solution.
The next question was to find the minimum number of swaps to convert a given string to its given anagram. I coded for this question and we had a discussion on optimizing one of the functions.
The interviewer also asked me the reason for choosing C++ as my preferred coding language, he agreed with my justification and was also satisfied with my skills in Java as I had both my projects in Java.
The interviewer in the end asked for feedback and also asked if I had any questions for him. I gave the feedback and asked him to share his experience.
The interview lasted for about 1 hour 15 mins.
Round 2: Technical Interview 2
Only I was shortlisted from the previous round and in this round interviewer asked me in detail about my projects and asked me to explain my recent project and also asked few questions on the same. So prepare well with your projects and be ready with different possible questions as in why the idea was adopted? what is the use-case? why the language used?, which sector or domain in general, it’s useful for? and so on. We also had a discussion on how the application developed in the project aims on providing a good user experience.
After a discussion on project, she asked me a coding question. She shared a google docs sheet and I had to code my solution there. The question was to find out if a string element of an array combined with another string element is palindrome or not, i.e for a given list of unique words, return all the pairs of the distinct indices(i,j) in the given list so that the concatenation of the two words [i] + words[j] is a palindrome.
For eg:
Input: words=["abcd","dcba","lls","sssll"]
Output: [[0,1],[1,0],[2,3]]
At first, she clearly explained the question and then asked me to give my approach. I gave an O(n2) solution and tried optimizing it but she was satisfied with the working solution itself and asked me to code it. I coded the same and she was dropping the hints whenever I would do a mistake or miss something. Later I explained the code and she asked me to optimize a function in the code and she dropped a hint for the same. I optimized the function accordingly. She was satisfied with my explanation and optimization and then she asked me to rate myself in SQL and Databases and asked me to write a SQL query that involved the use of Equi-join, arithmetic operation on columns, and aggregate function-sum().
The query was to find the total order amount for the given customer, Order Id would be given as input. I wrote a query for the same and she was satisfied with it.
The interviewer tipped me to keep learning Java as its most widely used for projects and also agreed with my selection of C++ for basic coding.
This round lasted for about an hour.
Round 5: Hr
HR asked me the most commonly asked HR questions like
Introduce yourself.
Why Accolite Digital?
Where do I see myself in 5 years?
How much have I familiarized myself with technology in the past year?
What is my preferred work location? and so on.
later he gave me a brief about Accolite Digital and gave me the salary break up. Also, asked if I had any questions for him, I asked about the Internship and then asked him if he has any suggestions for me? He suggested I keep updating with technology.
Verdict:Selected.
Overall Experience :
The recruitment process was quite smooth and also the interviewers were very kind and helpful. They taught me something new, to handle my code when I was nervous, and debug accordingly. This was my first interview and was a very good experience.
Tips: Practice DSA, DBMS, OS, CNS concepts very well as these are the most commonly asked questions in an interview for CS / IS domain.
Accolite
Marketing
On-Campus
Internship
Interview Experiences
Accolite
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Zoho Interview Experience (Off-Campus ) 2022
Thoughtspot Interview Experience for SDE Intern
TurboHire Internship Interview Experience
Persistent Systems Interview Experience (Martian Program)
Amazon Interview Questions
Microsoft Interview Experience for Internship (Via Engage)
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
|
[
{
"code": null,
"e": 25109,
"s": 25081,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 25201,
"s": 25109,
"text": "Accolite Digital started their drive at our college through SheCodes hiring on August 2021."
},
{
"code": null,
"e": 25225,
"s": 25201,
"text": "Role: Software Engineer"
},
{
"code": null,
"e": 25241,
"s": 25225,
"text": "Drive: SheCodes"
},
{
"code": null,
"e": 25268,
"s": 25241,
"text": "Offer-type: Internship+FTE"
},
{
"code": null,
"e": 25293,
"s": 25268,
"text": "Round 1: Online MCQ Test"
},
{
"code": null,
"e": 25696,
"s": 25293,
"text": "This was an MCQ round. It consisted of DSA, logical and numerical reasoning, quantitative aptitude, Networking, OS questions. This round mainly assessed our domain knowledge. There were 30 questions and 30 minutes were given to complete. The test was conducted on the Eduthrill platform, which is one of the products of Accolite Digital. The questions in this round were of easy to moderate difficulty."
},
{
"code": null,
"e": 25724,
"s": 25696,
"text": "Round 2: Online Coding Test"
},
{
"code": null,
"e": 25879,
"s": 25724,
"text": "Those who performed well in Round 1 were shortlisted for Round 2. This was a coding round. There was one coding question allotted with one hour of time. "
},
{
"code": null,
"e": 25976,
"s": 25879,
"text": "question: Give the minimum number of steps to convert an array of zeros to a given target array."
},
{
"code": null,
"e": 26147,
"s": 25976,
"text": "This question was given in a different way with a scenario and we had to provide the best solution in one hour’s time. The test was conducted on their platform catalyzer."
},
{
"code": null,
"e": 26178,
"s": 26147,
"text": "Round 3: Technical Interview 1"
},
{
"code": null,
"e": 26294,
"s": 26178,
"text": "Shortlists from round 2 were taken to interview rounds. Only 3 girls from the college were selected for interviews."
},
{
"code": null,
"e": 26490,
"s": 26294,
"text": "The interviewer initially introduced himself and then asked my introduction. Then he asked me 3 coding questions and few questions on DSA concepts. For coding, I used GeeksforGeeks online editor."
},
{
"code": null,
"e": 26755,
"s": 26490,
"text": "Remove contiguous characters from a given string such that there are no duplicates. For eg: AAAABABBABB should be converted to ABABAB. I gave both O(n2) and O(n) solutions. Coded for O(n) as it is the optimized one. The interviewer was satisfied with the solution."
},
{
"code": null,
"e": 27179,
"s": 26755,
"text": "Later, he asked me to explain the approach for detecting cycles in a graph. I explained to him DFS but was not so sure of the correct approach and hence he asked me two more questions on a union-find algorithm and disjoint-set data structure as in dropping hint for me to answer the question. I explained a different approach, he wasn’t completely satisfied with it but then he mentioned that the answer was somewhat close."
},
{
"code": null,
"e": 27360,
"s": 27179,
"text": "He asked me to explain the tree traversals and code for preorder traversal. I explained it clearly and coded the same with a recursive approach. He was satisfied with the solution."
},
{
"code": null,
"e": 27552,
"s": 27360,
"text": "The next question was to find the minimum number of swaps to convert a given string to its given anagram. I coded for this question and we had a discussion on optimizing one of the functions."
},
{
"code": null,
"e": 27756,
"s": 27552,
"text": "The interviewer also asked me the reason for choosing C++ as my preferred coding language, he agreed with my justification and was also satisfied with my skills in Java as I had both my projects in Java."
},
{
"code": null,
"e": 27908,
"s": 27756,
"text": "The interviewer in the end asked for feedback and also asked if I had any questions for him. I gave the feedback and asked him to share his experience."
},
{
"code": null,
"e": 27955,
"s": 27908,
"text": "The interview lasted for about 1 hour 15 mins."
},
{
"code": null,
"e": 27986,
"s": 27955,
"text": "Round 2: Technical Interview 2"
},
{
"code": null,
"e": 28522,
"s": 27986,
"text": "Only I was shortlisted from the previous round and in this round interviewer asked me in detail about my projects and asked me to explain my recent project and also asked few questions on the same. So prepare well with your projects and be ready with different possible questions as in why the idea was adopted? what is the use-case? why the language used?, which sector or domain in general, it’s useful for? and so on. We also had a discussion on how the application developed in the project aims on providing a good user experience."
},
{
"code": null,
"e": 28954,
"s": 28522,
"text": "After a discussion on project, she asked me a coding question. She shared a google docs sheet and I had to code my solution there. The question was to find out if a string element of an array combined with another string element is palindrome or not, i.e for a given list of unique words, return all the pairs of the distinct indices(i,j) in the given list so that the concatenation of the two words [i] + words[j] is a palindrome."
},
{
"code": null,
"e": 29033,
"s": 28954,
"text": "For eg:\nInput: words=[\"abcd\",\"dcba\",\"lls\",\"sssll\"]\nOutput: [[0,1],[1,0],[2,3]]"
},
{
"code": null,
"e": 29743,
"s": 29033,
"text": "At first, she clearly explained the question and then asked me to give my approach. I gave an O(n2) solution and tried optimizing it but she was satisfied with the working solution itself and asked me to code it. I coded the same and she was dropping the hints whenever I would do a mistake or miss something. Later I explained the code and she asked me to optimize a function in the code and she dropped a hint for the same. I optimized the function accordingly. She was satisfied with my explanation and optimization and then she asked me to rate myself in SQL and Databases and asked me to write a SQL query that involved the use of Equi-join, arithmetic operation on columns, and aggregate function-sum()."
},
{
"code": null,
"e": 29906,
"s": 29743,
"text": "The query was to find the total order amount for the given customer, Order Id would be given as input. I wrote a query for the same and she was satisfied with it."
},
{
"code": null,
"e": 30050,
"s": 29906,
"text": "The interviewer tipped me to keep learning Java as its most widely used for projects and also agreed with my selection of C++ for basic coding."
},
{
"code": null,
"e": 30087,
"s": 30050,
"text": "This round lasted for about an hour."
},
{
"code": null,
"e": 30099,
"s": 30087,
"text": "Round 5: Hr"
},
{
"code": null,
"e": 30153,
"s": 30099,
"text": "HR asked me the most commonly asked HR questions like"
},
{
"code": null,
"e": 30173,
"s": 30153,
"text": "Introduce yourself."
},
{
"code": null,
"e": 30195,
"s": 30173,
"text": "Why Accolite Digital?"
},
{
"code": null,
"e": 30229,
"s": 30195,
"text": "Where do I see myself in 5 years?"
},
{
"code": null,
"e": 30299,
"s": 30229,
"text": "How much have I familiarized myself with technology in the past year?"
},
{
"code": null,
"e": 30346,
"s": 30299,
"text": "What is my preferred work location? and so on."
},
{
"code": null,
"e": 30599,
"s": 30346,
"text": "later he gave me a brief about Accolite Digital and gave me the salary break up. Also, asked if I had any questions for him, I asked about the Internship and then asked him if he has any suggestions for me? He suggested I keep updating with technology."
},
{
"code": null,
"e": 30617,
"s": 30599,
"text": "Verdict:Selected."
},
{
"code": null,
"e": 30638,
"s": 30617,
"text": "Overall Experience :"
},
{
"code": null,
"e": 30884,
"s": 30638,
"text": "The recruitment process was quite smooth and also the interviewers were very kind and helpful. They taught me something new, to handle my code when I was nervous, and debug accordingly. This was my first interview and was a very good experience."
},
{
"code": null,
"e": 31021,
"s": 30884,
"text": "Tips: Practice DSA, DBMS, OS, CNS concepts very well as these are the most commonly asked questions in an interview for CS / IS domain."
},
{
"code": null,
"e": 31030,
"s": 31021,
"text": "Accolite"
},
{
"code": null,
"e": 31040,
"s": 31030,
"text": "Marketing"
},
{
"code": null,
"e": 31050,
"s": 31040,
"text": "On-Campus"
},
{
"code": null,
"e": 31061,
"s": 31050,
"text": "Internship"
},
{
"code": null,
"e": 31083,
"s": 31061,
"text": "Interview Experiences"
},
{
"code": null,
"e": 31092,
"s": 31083,
"text": "Accolite"
},
{
"code": null,
"e": 31190,
"s": 31092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31199,
"s": 31190,
"text": "Comments"
},
{
"code": null,
"e": 31212,
"s": 31199,
"text": "Old Comments"
},
{
"code": null,
"e": 31271,
"s": 31212,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 31316,
"s": 31271,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 31364,
"s": 31316,
"text": "Thoughtspot Interview Experience for SDE Intern"
},
{
"code": null,
"e": 31406,
"s": 31364,
"text": "TurboHire Internship Interview Experience"
},
{
"code": null,
"e": 31464,
"s": 31406,
"text": "Persistent Systems Interview Experience (Martian Program)"
},
{
"code": null,
"e": 31491,
"s": 31464,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 31550,
"s": 31491,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 31610,
"s": 31550,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 31660,
"s": 31610,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
Checking for permutation of a palindrome in JavaScript
|
We are required to write a JavaScript function that takes in a string as the first and the only argument.
The task of our function is to check whether any rearrangement in the characters of the string results into a palindrome string or not. If yes, then our function should return true, false otherwise.
For example −
If the input string is −
const str = 'amadm';
Then the output should be −
const output = true;
because the string can be rearranged to form 'madam' which is a palindrome string.
The code for this will be −
Live Demo
const str = 'amadm';
const canFormPalindrome = (str = '') => {
const hash = {};
let count = 0;
for (let i = 0; i < str.length; i++) {
let c = str[i];
if(c === ' '){
continue;
};
if(hash[c]){
delete hash[c];
}else{
hash[c] = true;
};
count++;
};
if(count % 2 === 0){
return Object.keys(hash).length === 0;
}else{
return Object.keys(hash).length === 1;
};
};
console.log(canFormPalindrome(str));
And the output in the console will be −
true
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a string as the first and the only argument."
},
{
"code": null,
"e": 1367,
"s": 1168,
"text": "The task of our function is to check whether any rearrangement in the characters of the string results into a palindrome string or not. If yes, then our function should return true, false otherwise."
},
{
"code": null,
"e": 1381,
"s": 1367,
"text": "For example −"
},
{
"code": null,
"e": 1406,
"s": 1381,
"text": "If the input string is −"
},
{
"code": null,
"e": 1427,
"s": 1406,
"text": "const str = 'amadm';"
},
{
"code": null,
"e": 1455,
"s": 1427,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1476,
"s": 1455,
"text": "const output = true;"
},
{
"code": null,
"e": 1559,
"s": 1476,
"text": "because the string can be rearranged to form 'madam' which is a palindrome string."
},
{
"code": null,
"e": 1587,
"s": 1559,
"text": "The code for this will be −"
},
{
"code": null,
"e": 1598,
"s": 1587,
"text": " Live Demo"
},
{
"code": null,
"e": 2094,
"s": 1598,
"text": "const str = 'amadm';\nconst canFormPalindrome = (str = '') => {\n const hash = {};\n let count = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str[i];\n if(c === ' '){\n continue;\n };\n if(hash[c]){\n delete hash[c];\n }else{\n hash[c] = true;\n };\n count++;\n };\n if(count % 2 === 0){\n return Object.keys(hash).length === 0;\n }else{\n return Object.keys(hash).length === 1;\n };\n};\nconsole.log(canFormPalindrome(str));"
},
{
"code": null,
"e": 2134,
"s": 2094,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2139,
"s": 2134,
"text": "true"
}
] |
AWT Container Class
|
The class Container is the super class for the containers of AWT. Container object can contain other AWT components.
Following is the declaration for java.awt.Container class:
public class Container
extends Component
Container()
This creates a new Container.
Component add(Component comp)
Appends the specified component to the end of this container.
Component add(Component comp, int index)
Adds the specified component to this container at the given position.
void add(Component comp, Object constraints)
Adds the specified component to the end of this container.
void add(Component comp, Object constraints, int index)
Adds the specified component to this container with the specified constraints at the specified index.
Component add(String name, Component comp)
Adds the specified component to this container.
void addContainerListener(ContainerListener l)
Adds the specified container listener to receive container events from this container.
protected void addImpl(Component comp, Object constraints, int index)
Adds the specified component to this container at the specified index.
void addNotify()
Makes this Container displayable by connecting it to a native screen resource.
void addPropertyChangeListener(PropertyChangeListener listener)
Adds a PropertyChangeListener to the listener list.
void add Property Change Listener(String proper tyName, Property Change Listener listener)
Adds a PropertyChangeListener to the listener list for a specific property.
void applyComponentOrientation(ComponentOrientation o)
Sets the ComponentOrientation property of this container and all components contained within it.
boolean areFocusTraversalKeysSet(int id)
Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container.
int countComponents()
Deprecated. As of JDK version 1.1, replaced by getComponentCount().
void deliverEvent(Event e)
Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)
void doLayout()
Causes this container to lay out its components.
Component findComponentAt(int x, int y)
Locates the visible child component that contains the specified position.
Component findComponentAt(Point p)
Locates the visible child component that contains the specified point.
float getAlignmentX()
Returns the alignment along the x axis.
float getAlignmentY()
Returns the alignment along the y axis.
Component getComponent(int n)
Gets the nth component in this container.
Component getComponentAt(int x, int y)
Locates the component that contains the x,y position.
Component getComponentAt(Point p)
Gets the component that contains the specified point.
int getComponentCount()
Gets the number of components in this panel.
Component[] getComponents()
Gets all the components in this container.
int getComponentZOrder(Component comp)
Returns the z-order index of the component inside the container.
ContainerListener[] getContainerListeners()
Returns an array of all the container listeners registered on this container.
Set<AWTKeyStroke> getFocusTraversalKeys(int id)
Returns the Set of focus traversal keys for a given traversal operation for this Container.
FocusTraversalPolicy getFocusTraversalPolicy()
Returns the focus traversal policy that will manage keyboard traversal of this Container's children, or null if this Container is not a focus cycle root.
Insets getInsets()
Determines the insets of this container, which indicate the size of the container's border.
LayoutManager getLayout()
Gets the layout manager for this container.
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this Container.
Dimension getMaximumSize()
Returns the maximum size of this container.
Dimension getMinimumSize()
Returns the minimum size of this container.
Point getMousePosition(boolean allowChildren)
Returns the position of the mouse pointer in this Container's coordinate space if the Container is under the mouse pointer, otherwise returns null.
Dimension getPreferredSize()
Returns the preferred size of this container.
Insets insets()
Deprecated. As of JDK version 1.1, replaced by getInsets().
void invalidate()
Invalidates the container.
boolean isAncestorOf(Component c)
Checks if the component is contained in the component hierarchy of this container.
boolean isFocusCycleRoot()
Returns whether this Container is the root of a focus traversal cycle.
boolean isFocusCycleRoot(Container container)
Returns whether the specified Container is the focus cycle root of this Container's focus traversal cycle.
boolean isFocusTraversalPolicyProvider()
Returns whether this container provides focus traversal policy.
boolean isFocusTraversalPolicySet()
Returns whether the focus traversal policy has been explicitly set for this Container.
void layout()
Deprecated. As of JDK version 1.1, replaced by doLayout().
void list(PrintStream out, int indent)
Prints a listing of this container to the specified output stream.
void list(PrintWriter out, int indent)
Prints out a list, starting at the specified indentation, to the specified print writer.
Component locate(int x, int y)
Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).
Dimension minimumSize()
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
void paint(Graphics g)
Paints the container.
void paintComponents(Graphics g)
Paints each of the components in this container.
protected String paramString()
Returns a string representing the state of this Container.
Dimension preferredSize()
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().
void print(Graphics g)
Prints the container.
void printComponents(Graphics g)
Prints each of the components in this container.
protected void processContainerEvent(ContainerEvent e)
Processes container events occurring on this container by dispatching them to any registered ContainerListener objects.
protected void processEvent(AWTEvent e)
Processes events on this container.
void remove(Component comp)
Removes the specified component from this container.
void remove(int index)
Removes the component, specified by index, from this container.
void removeAll()
Removes all the components from this container.
void removeContainerListener(ContainerListener l)
Removes the specified container listener so it no longer receives container events from this container.
void removeNotify()
Makes this Container undisplayable by removing its connection to its native screen resource.
void setComponentZOrder(Component comp, int index)
Moves the specified component to the specified z-order index in the container.
void setFocusCycleRoot(boolean focusCycleRoot)
Sets whether this Container is the root of a focus traversal cycle.
void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)
Sets the focus traversal keys for a given traversal operation for this Container.
void setFocusTraversalPolicy(FocusTraversalPolicy policy)
Sets the focus traversal policy that will manage keyboard traversal of this Container's children, if this Container is a focus cycle root.
void setFocusTraversalPolicyProvider(boolean provider)
Sets whether this container will be used to provide focus traversal policy.
void setFont(Font f)
Sets the font of this container.
void setLayout(LayoutManager mgr)
Sets the layout manager for this container.
void transferFocusBackward()
Transfers the focus to the previous component, as though this Component were the focus owner.
void transferFocusDownCycle()
Transfers the focus down one focus traversal cycle.
void update(Graphics g)
Updates the container.
void validate()
Validates this container and all of its subcomponents.
protected void validateTree()
Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid).
This class inherits methods from the following classes:
java.awt.Component
java.awt.Component
java.lang.Object
java.lang.Object
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1864,
"s": 1747,
"text": "The class Container is the super class for the containers of AWT. Container object can contain other AWT components."
},
{
"code": null,
"e": 1923,
"s": 1864,
"text": "Following is the declaration for java.awt.Container class:"
},
{
"code": null,
"e": 1967,
"s": 1923,
"text": "public class Container\n extends Component"
},
{
"code": null,
"e": 1980,
"s": 1967,
"text": "Container() "
},
{
"code": null,
"e": 2010,
"s": 1980,
"text": "This creates a new Container."
},
{
"code": null,
"e": 2041,
"s": 2010,
"text": "Component add(Component comp) "
},
{
"code": null,
"e": 2103,
"s": 2041,
"text": "Appends the specified component to the end of this container."
},
{
"code": null,
"e": 2145,
"s": 2103,
"text": "Component add(Component comp, int index) "
},
{
"code": null,
"e": 2215,
"s": 2145,
"text": "Adds the specified component to this container at the given position."
},
{
"code": null,
"e": 2261,
"s": 2215,
"text": "void add(Component comp, Object constraints) "
},
{
"code": null,
"e": 2320,
"s": 2261,
"text": "Adds the specified component to the end of this container."
},
{
"code": null,
"e": 2377,
"s": 2320,
"text": "void add(Component comp, Object constraints, int index) "
},
{
"code": null,
"e": 2479,
"s": 2377,
"text": "Adds the specified component to this container with the specified constraints at the specified index."
},
{
"code": null,
"e": 2523,
"s": 2479,
"text": "Component add(String name, Component comp) "
},
{
"code": null,
"e": 2571,
"s": 2523,
"text": "Adds the specified component to this container."
},
{
"code": null,
"e": 2619,
"s": 2571,
"text": "void addContainerListener(ContainerListener l) "
},
{
"code": null,
"e": 2706,
"s": 2619,
"text": "Adds the specified container listener to receive container events from this container."
},
{
"code": null,
"e": 2777,
"s": 2706,
"text": "protected void addImpl(Component comp, Object constraints, int index) "
},
{
"code": null,
"e": 2848,
"s": 2777,
"text": "Adds the specified component to this container at the specified index."
},
{
"code": null,
"e": 2866,
"s": 2848,
"text": "void addNotify() "
},
{
"code": null,
"e": 2945,
"s": 2866,
"text": "Makes this Container displayable by connecting it to a native screen resource."
},
{
"code": null,
"e": 3010,
"s": 2945,
"text": "void addPropertyChangeListener(PropertyChangeListener listener) "
},
{
"code": null,
"e": 3062,
"s": 3010,
"text": "Adds a PropertyChangeListener to the listener list."
},
{
"code": null,
"e": 3154,
"s": 3062,
"text": "void add Property Change Listener(String proper tyName, Property Change Listener listener) "
},
{
"code": null,
"e": 3230,
"s": 3154,
"text": "Adds a PropertyChangeListener to the listener list for a specific property."
},
{
"code": null,
"e": 3286,
"s": 3230,
"text": "void applyComponentOrientation(ComponentOrientation o) "
},
{
"code": null,
"e": 3383,
"s": 3286,
"text": "Sets the ComponentOrientation property of this container and all components contained within it."
},
{
"code": null,
"e": 3425,
"s": 3383,
"text": "boolean areFocusTraversalKeysSet(int id) "
},
{
"code": null,
"e": 3561,
"s": 3425,
"text": "Returns whether the Set of focus traversal keys for the given focus traversal operation has been explicitly defined for this Container."
},
{
"code": null,
"e": 3584,
"s": 3561,
"text": "int countComponents() "
},
{
"code": null,
"e": 3652,
"s": 3584,
"text": "Deprecated. As of JDK version 1.1, replaced by getComponentCount()."
},
{
"code": null,
"e": 3680,
"s": 3652,
"text": "void deliverEvent(Event e) "
},
{
"code": null,
"e": 3753,
"s": 3680,
"text": "Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)"
},
{
"code": null,
"e": 3770,
"s": 3753,
"text": "void doLayout() "
},
{
"code": null,
"e": 3819,
"s": 3770,
"text": "Causes this container to lay out its components."
},
{
"code": null,
"e": 3860,
"s": 3819,
"text": "Component findComponentAt(int x, int y) "
},
{
"code": null,
"e": 3934,
"s": 3860,
"text": "Locates the visible child component that contains the specified position."
},
{
"code": null,
"e": 3970,
"s": 3934,
"text": "Component findComponentAt(Point p) "
},
{
"code": null,
"e": 4041,
"s": 3970,
"text": "Locates the visible child component that contains the specified point."
},
{
"code": null,
"e": 4064,
"s": 4041,
"text": "float getAlignmentX() "
},
{
"code": null,
"e": 4104,
"s": 4064,
"text": "Returns the alignment along the x axis."
},
{
"code": null,
"e": 4127,
"s": 4104,
"text": "float getAlignmentY() "
},
{
"code": null,
"e": 4167,
"s": 4127,
"text": "Returns the alignment along the y axis."
},
{
"code": null,
"e": 4198,
"s": 4167,
"text": "Component getComponent(int n) "
},
{
"code": null,
"e": 4240,
"s": 4198,
"text": "Gets the nth component in this container."
},
{
"code": null,
"e": 4280,
"s": 4240,
"text": "Component getComponentAt(int x, int y) "
},
{
"code": null,
"e": 4334,
"s": 4280,
"text": "Locates the component that contains the x,y position."
},
{
"code": null,
"e": 4369,
"s": 4334,
"text": "Component getComponentAt(Point p) "
},
{
"code": null,
"e": 4423,
"s": 4369,
"text": "Gets the component that contains the specified point."
},
{
"code": null,
"e": 4448,
"s": 4423,
"text": "int getComponentCount() "
},
{
"code": null,
"e": 4493,
"s": 4448,
"text": "Gets the number of components in this panel."
},
{
"code": null,
"e": 4522,
"s": 4493,
"text": "Component[] getComponents() "
},
{
"code": null,
"e": 4565,
"s": 4522,
"text": "Gets all the components in this container."
},
{
"code": null,
"e": 4605,
"s": 4565,
"text": "int getComponentZOrder(Component comp) "
},
{
"code": null,
"e": 4670,
"s": 4605,
"text": "Returns the z-order index of the component inside the container."
},
{
"code": null,
"e": 4715,
"s": 4670,
"text": "ContainerListener[] getContainerListeners() "
},
{
"code": null,
"e": 4793,
"s": 4715,
"text": "Returns an array of all the container listeners registered on this container."
},
{
"code": null,
"e": 4842,
"s": 4793,
"text": "Set<AWTKeyStroke> getFocusTraversalKeys(int id) "
},
{
"code": null,
"e": 4934,
"s": 4842,
"text": "Returns the Set of focus traversal keys for a given traversal operation for this Container."
},
{
"code": null,
"e": 4982,
"s": 4934,
"text": "FocusTraversalPolicy getFocusTraversalPolicy() "
},
{
"code": null,
"e": 5136,
"s": 4982,
"text": "Returns the focus traversal policy that will manage keyboard traversal of this Container's children, or null if this Container is not a focus cycle root."
},
{
"code": null,
"e": 5156,
"s": 5136,
"text": "Insets getInsets() "
},
{
"code": null,
"e": 5248,
"s": 5156,
"text": "Determines the insets of this container, which indicate the size of the container's border."
},
{
"code": null,
"e": 5275,
"s": 5248,
"text": "LayoutManager getLayout() "
},
{
"code": null,
"e": 5319,
"s": 5275,
"text": "Gets the layout manager for this container."
},
{
"code": null,
"e": 5386,
"s": 5319,
"text": "<T extends EventListener> T[] getListeners(Class<T> listenerType) "
},
{
"code": null,
"e": 5480,
"s": 5386,
"text": "Returns an array of all the objects currently registered as FooListeners upon this Container."
},
{
"code": null,
"e": 5508,
"s": 5480,
"text": "Dimension\tgetMaximumSize() "
},
{
"code": null,
"e": 5552,
"s": 5508,
"text": "Returns the maximum size of this container."
},
{
"code": null,
"e": 5580,
"s": 5552,
"text": "Dimension\tgetMinimumSize() "
},
{
"code": null,
"e": 5624,
"s": 5580,
"text": "Returns the minimum size of this container."
},
{
"code": null,
"e": 5671,
"s": 5624,
"text": "Point\tgetMousePosition(boolean allowChildren) "
},
{
"code": null,
"e": 5819,
"s": 5671,
"text": "Returns the position of the mouse pointer in this Container's coordinate space if the Container is under the mouse pointer, otherwise returns null."
},
{
"code": null,
"e": 5849,
"s": 5819,
"text": "Dimension\tgetPreferredSize() "
},
{
"code": null,
"e": 5895,
"s": 5849,
"text": "Returns the preferred size of this container."
},
{
"code": null,
"e": 5912,
"s": 5895,
"text": "Insets\tinsets() "
},
{
"code": null,
"e": 5972,
"s": 5912,
"text": "Deprecated. As of JDK version 1.1, replaced by getInsets()."
},
{
"code": null,
"e": 5991,
"s": 5972,
"text": "void invalidate() "
},
{
"code": null,
"e": 6018,
"s": 5991,
"text": "Invalidates the container."
},
{
"code": null,
"e": 6053,
"s": 6018,
"text": "boolean isAncestorOf(Component c) "
},
{
"code": null,
"e": 6136,
"s": 6053,
"text": "Checks if the component is contained in the component hierarchy of this container."
},
{
"code": null,
"e": 6164,
"s": 6136,
"text": "boolean isFocusCycleRoot() "
},
{
"code": null,
"e": 6235,
"s": 6164,
"text": "Returns whether this Container is the root of a focus traversal cycle."
},
{
"code": null,
"e": 6282,
"s": 6235,
"text": "boolean isFocusCycleRoot(Container container) "
},
{
"code": null,
"e": 6389,
"s": 6282,
"text": "Returns whether the specified Container is the focus cycle root of this Container's focus traversal cycle."
},
{
"code": null,
"e": 6431,
"s": 6389,
"text": "boolean isFocusTraversalPolicyProvider() "
},
{
"code": null,
"e": 6495,
"s": 6431,
"text": "Returns whether this container provides focus traversal policy."
},
{
"code": null,
"e": 6532,
"s": 6495,
"text": "boolean isFocusTraversalPolicySet() "
},
{
"code": null,
"e": 6619,
"s": 6532,
"text": "Returns whether the focus traversal policy has been explicitly set for this Container."
},
{
"code": null,
"e": 6634,
"s": 6619,
"text": "void layout() "
},
{
"code": null,
"e": 6693,
"s": 6634,
"text": "Deprecated. As of JDK version 1.1, replaced by doLayout()."
},
{
"code": null,
"e": 6733,
"s": 6693,
"text": "void list(PrintStream out, int indent) "
},
{
"code": null,
"e": 6800,
"s": 6733,
"text": "Prints a listing of this container to the specified output stream."
},
{
"code": null,
"e": 6840,
"s": 6800,
"text": "void list(PrintWriter out, int indent) "
},
{
"code": null,
"e": 6929,
"s": 6840,
"text": "Prints out a list, starting at the specified indentation, to the specified print writer."
},
{
"code": null,
"e": 6961,
"s": 6929,
"text": "Component locate(int x, int y) "
},
{
"code": null,
"e": 7034,
"s": 6961,
"text": "Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int)."
},
{
"code": null,
"e": 7059,
"s": 7034,
"text": "Dimension minimumSize() "
},
{
"code": null,
"e": 7124,
"s": 7059,
"text": "Deprecated. As of JDK version 1.1, replaced by getMinimumSize()."
},
{
"code": null,
"e": 7148,
"s": 7124,
"text": "void paint(Graphics g) "
},
{
"code": null,
"e": 7170,
"s": 7148,
"text": "Paints the container."
},
{
"code": null,
"e": 7204,
"s": 7170,
"text": "void paintComponents(Graphics g) "
},
{
"code": null,
"e": 7253,
"s": 7204,
"text": "Paints each of the components in this container."
},
{
"code": null,
"e": 7286,
"s": 7253,
"text": "protected String\tparamString() "
},
{
"code": null,
"e": 7346,
"s": 7286,
"text": " Returns a string representing the state of this Container."
},
{
"code": null,
"e": 7373,
"s": 7346,
"text": "Dimension\tpreferredSize() "
},
{
"code": null,
"e": 7440,
"s": 7373,
"text": "Deprecated. As of JDK version 1.1, replaced by getPreferredSize()."
},
{
"code": null,
"e": 7464,
"s": 7440,
"text": "void print(Graphics g) "
},
{
"code": null,
"e": 7486,
"s": 7464,
"text": "Prints the container."
},
{
"code": null,
"e": 7520,
"s": 7486,
"text": "void printComponents(Graphics g) "
},
{
"code": null,
"e": 7569,
"s": 7520,
"text": "Prints each of the components in this container."
},
{
"code": null,
"e": 7625,
"s": 7569,
"text": "protected void processContainerEvent(ContainerEvent e) "
},
{
"code": null,
"e": 7745,
"s": 7625,
"text": "Processes container events occurring on this container by dispatching them to any registered ContainerListener objects."
},
{
"code": null,
"e": 7786,
"s": 7745,
"text": "protected void processEvent(AWTEvent e) "
},
{
"code": null,
"e": 7822,
"s": 7786,
"text": "Processes events on this container."
},
{
"code": null,
"e": 7851,
"s": 7822,
"text": "void remove(Component comp) "
},
{
"code": null,
"e": 7904,
"s": 7851,
"text": "Removes the specified component from this container."
},
{
"code": null,
"e": 7928,
"s": 7904,
"text": "void remove(int index) "
},
{
"code": null,
"e": 7992,
"s": 7928,
"text": "Removes the component, specified by index, from this container."
},
{
"code": null,
"e": 8010,
"s": 7992,
"text": "void removeAll() "
},
{
"code": null,
"e": 8058,
"s": 8010,
"text": "Removes all the components from this container."
},
{
"code": null,
"e": 8109,
"s": 8058,
"text": "void removeContainerListener(ContainerListener l) "
},
{
"code": null,
"e": 8213,
"s": 8109,
"text": "Removes the specified container listener so it no longer receives container events from this container."
},
{
"code": null,
"e": 8234,
"s": 8213,
"text": "void removeNotify() "
},
{
"code": null,
"e": 8327,
"s": 8234,
"text": "Makes this Container undisplayable by removing its connection to its native screen resource."
},
{
"code": null,
"e": 8379,
"s": 8327,
"text": "void setComponentZOrder(Component comp, int index) "
},
{
"code": null,
"e": 8458,
"s": 8379,
"text": "Moves the specified component to the specified z-order index in the container."
},
{
"code": null,
"e": 8506,
"s": 8458,
"text": "void setFocusCycleRoot(boolean focusCycleRoot) "
},
{
"code": null,
"e": 8574,
"s": 8506,
"text": "Sets whether this Container is the root of a focus traversal cycle."
},
{
"code": null,
"e": 8650,
"s": 8574,
"text": "void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes) "
},
{
"code": null,
"e": 8732,
"s": 8650,
"text": "Sets the focus traversal keys for a given traversal operation for this Container."
},
{
"code": null,
"e": 8791,
"s": 8732,
"text": "void setFocusTraversalPolicy(FocusTraversalPolicy policy) "
},
{
"code": null,
"e": 8930,
"s": 8791,
"text": "Sets the focus traversal policy that will manage keyboard traversal of this Container's children, if this Container is a focus cycle root."
},
{
"code": null,
"e": 8986,
"s": 8930,
"text": "void setFocusTraversalPolicyProvider(boolean provider) "
},
{
"code": null,
"e": 9062,
"s": 8986,
"text": "Sets whether this container will be used to provide focus traversal policy."
},
{
"code": null,
"e": 9084,
"s": 9062,
"text": "void setFont(Font f) "
},
{
"code": null,
"e": 9117,
"s": 9084,
"text": "Sets the font of this container."
},
{
"code": null,
"e": 9152,
"s": 9117,
"text": "void setLayout(LayoutManager mgr) "
},
{
"code": null,
"e": 9196,
"s": 9152,
"text": "Sets the layout manager for this container."
},
{
"code": null,
"e": 9226,
"s": 9196,
"text": "void transferFocusBackward() "
},
{
"code": null,
"e": 9320,
"s": 9226,
"text": "Transfers the focus to the previous component, as though this Component were the focus owner."
},
{
"code": null,
"e": 9351,
"s": 9320,
"text": "void transferFocusDownCycle() "
},
{
"code": null,
"e": 9403,
"s": 9351,
"text": "Transfers the focus down one focus traversal cycle."
},
{
"code": null,
"e": 9428,
"s": 9403,
"text": "void update(Graphics g) "
},
{
"code": null,
"e": 9451,
"s": 9428,
"text": "Updates the container."
},
{
"code": null,
"e": 9468,
"s": 9451,
"text": "void validate() "
},
{
"code": null,
"e": 9523,
"s": 9468,
"text": "Validates this container and all of its subcomponents."
},
{
"code": null,
"e": 9554,
"s": 9523,
"text": "protected void validateTree() "
},
{
"code": null,
"e": 9685,
"s": 9554,
"text": "Recursively descends the container tree and recomputes the layout for any subtrees marked as needing it (those marked as invalid)."
},
{
"code": null,
"e": 9741,
"s": 9685,
"text": "This class inherits methods from the following classes:"
},
{
"code": null,
"e": 9760,
"s": 9741,
"text": "java.awt.Component"
},
{
"code": null,
"e": 9779,
"s": 9760,
"text": "java.awt.Component"
},
{
"code": null,
"e": 9796,
"s": 9779,
"text": "java.lang.Object"
},
{
"code": null,
"e": 9813,
"s": 9796,
"text": "java.lang.Object"
},
{
"code": null,
"e": 9846,
"s": 9813,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9854,
"s": 9846,
"text": " EduOLC"
},
{
"code": null,
"e": 9861,
"s": 9854,
"text": " Print"
},
{
"code": null,
"e": 9872,
"s": 9861,
"text": " Add Notes"
}
] |
How to Read a File Line by Line to String in Golang? - GeeksforGeeks
|
22 Jun, 2020
To read a file line by line the bufio package Scanner is used. Let the text file be named as sample.txt and the content inside the file is as follows:
GO Language is a statically compiled programming language, It is an open-source language. It was designed at Google by Rob Pike, Ken Thompson, and Robert Grieserner. It is also known as Golang. Go language is a general-purpose programming language mainly meant for building large scale complex software.
package main import ( "bufio" "fmt" "log" "os") func main() { // os.Open() opens specific file in // read-only mode and this return // a pointer of type os. file, err := os.Open("sample.txt") if err != nil { log.Fatalf("failed to open") } // The bufio.NewScanner() function is called in which the // object os.File passed as its parameter and this returns a // object bufio.Scanner which is further used on the // bufio.Scanner.Split() method. scanner := bufio.NewScanner(file) // The bufio.ScanLines is used as an // input to the method bufio.Scanner.Split() // and then the scanning forwards to each // new line using the bufio.Scanner.Scan() // method. scanner.Split(bufio.ScanLines) var text []string for scanner.Scan() { text = append(text, scanner.Text()) } // The method os.File.Close() is called // on the os.File object to close the file file.Close() // and then a loop iterates through // and prints each of the slice values. for _, each_ln := range text { fmt.Println(each_ln) }}
Output:
Golang-File-Handling
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Formatting in Golang
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to compare times in Golang?
Golang Maps
How to Trim a String in Golang?
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to convert a string in lower case in Golang?
|
[
{
"code": null,
"e": 24400,
"s": 24372,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 24551,
"s": 24400,
"text": "To read a file line by line the bufio package Scanner is used. Let the text file be named as sample.txt and the content inside the file is as follows:"
},
{
"code": null,
"e": 24855,
"s": 24551,
"text": "GO Language is a statically compiled programming language, It is an open-source language. It was designed at Google by Rob Pike, Ken Thompson, and Robert Grieserner. It is also known as Golang. Go language is a general-purpose programming language mainly meant for building large scale complex software."
},
{
"code": "package main import ( \"bufio\" \"fmt\" \"log\" \"os\") func main() { // os.Open() opens specific file in // read-only mode and this return // a pointer of type os. file, err := os.Open(\"sample.txt\") if err != nil { log.Fatalf(\"failed to open\") } // The bufio.NewScanner() function is called in which the // object os.File passed as its parameter and this returns a // object bufio.Scanner which is further used on the // bufio.Scanner.Split() method. scanner := bufio.NewScanner(file) // The bufio.ScanLines is used as an // input to the method bufio.Scanner.Split() // and then the scanning forwards to each // new line using the bufio.Scanner.Scan() // method. scanner.Split(bufio.ScanLines) var text []string for scanner.Scan() { text = append(text, scanner.Text()) } // The method os.File.Close() is called // on the os.File object to close the file file.Close() // and then a loop iterates through // and prints each of the slice values. for _, each_ln := range text { fmt.Println(each_ln) }}",
"e": 25982,
"s": 24855,
"text": null
},
{
"code": null,
"e": 25990,
"s": 25982,
"text": "Output:"
},
{
"code": null,
"e": 26011,
"s": 25990,
"text": "Golang-File-Handling"
},
{
"code": null,
"e": 26018,
"s": 26011,
"text": "Picked"
},
{
"code": null,
"e": 26030,
"s": 26018,
"text": "Go Language"
},
{
"code": null,
"e": 26128,
"s": 26030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26137,
"s": 26128,
"text": "Comments"
},
{
"code": null,
"e": 26150,
"s": 26137,
"text": "Old Comments"
},
{
"code": null,
"e": 26176,
"s": 26150,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 26227,
"s": 26176,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 26240,
"s": 26227,
"text": "Arrays in Go"
},
{
"code": null,
"e": 26287,
"s": 26240,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 26319,
"s": 26287,
"text": "How to compare times in Golang?"
},
{
"code": null,
"e": 26331,
"s": 26319,
"text": "Golang Maps"
},
{
"code": null,
"e": 26363,
"s": 26331,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 26380,
"s": 26363,
"text": "Slices in Golang"
},
{
"code": null,
"e": 26434,
"s": 26380,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
JavaScript String charAt() Method - GeeksforGeeks
|
05 Oct, 2021
Below is the example of the String charAt() Method.
Example:<script>function func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(0); var value1 = str.charAt(4); document.write(value); document.write(value1);}func();</script>
<script>function func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(0); var value1 = str.charAt(4); document.write(value); document.write(value1);}func();</script>
Output:JS
JS
str.charAT() Returns character at given index of string.
character = str.charAt(index)
Arguments:The only argument to this function is the index in the string from where the single character is to be extracted. The range of this index is between 0 and length – 1, including the limits. If no index is specified then the first character of the string is returned as 0 is the default index used for this function.
Return valueThis function returns a single character located at the index specified as the argument to the function. If the index is out of range, then this function returns an empty string.
Examples for the above function are provided below:
Example 1:
var str = 'JavaScript is object oriented language';
print(str.charAt(9));
Output:
t
In this example the function charAt() finds the character at index 9 and returns it.
Example 2:
var str = 'JavaScript is object oriented language';
print(str.charAt(50));
Output:
In this example the function charAt() finds the character at index 50. Since the index is out of bounds for the given string therefore the function returns “” an empty string.
Codes for the above function are provided below:
Program 1:
// JavaScript to illustrate charAt() function<script>function func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(9); document.write(value); }func();</script>
Output:
t
Program 2:
<script>// JavaScript to illustrate charAt() functionfunction func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(50); document.write(value); }func();</script>
Output:
Supported Browser:
Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 3 and above
Opera 3 and above
Safari 1
Akanksha_Rai
ysachin2314
javascript-string
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25003,
"s": 24975,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 25055,
"s": 25003,
"text": "Below is the example of the String charAt() Method."
},
{
"code": null,
"e": 25350,
"s": 25055,
"text": "Example:<script>function func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(0); var value1 = str.charAt(4); document.write(value); document.write(value1);}func();</script> "
},
{
"code": "<script>function func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(0); var value1 = str.charAt(4); document.write(value); document.write(value1);}func();</script> ",
"e": 25637,
"s": 25350,
"text": null
},
{
"code": null,
"e": 25648,
"s": 25637,
"text": "Output:JS\n"
},
{
"code": null,
"e": 25652,
"s": 25648,
"text": "JS\n"
},
{
"code": null,
"e": 25709,
"s": 25652,
"text": "str.charAT() Returns character at given index of string."
},
{
"code": null,
"e": 25740,
"s": 25709,
"text": "character = str.charAt(index)\n"
},
{
"code": null,
"e": 26065,
"s": 25740,
"text": "Arguments:The only argument to this function is the index in the string from where the single character is to be extracted. The range of this index is between 0 and length – 1, including the limits. If no index is specified then the first character of the string is returned as 0 is the default index used for this function."
},
{
"code": null,
"e": 26256,
"s": 26065,
"text": "Return valueThis function returns a single character located at the index specified as the argument to the function. If the index is out of range, then this function returns an empty string."
},
{
"code": null,
"e": 26308,
"s": 26256,
"text": "Examples for the above function are provided below:"
},
{
"code": null,
"e": 26319,
"s": 26308,
"text": "Example 1:"
},
{
"code": null,
"e": 26394,
"s": 26319,
"text": "var str = 'JavaScript is object oriented language';\nprint(str.charAt(9));\n"
},
{
"code": null,
"e": 26402,
"s": 26394,
"text": "Output:"
},
{
"code": null,
"e": 26405,
"s": 26402,
"text": "t\n"
},
{
"code": null,
"e": 26490,
"s": 26405,
"text": "In this example the function charAt() finds the character at index 9 and returns it."
},
{
"code": null,
"e": 26501,
"s": 26490,
"text": "Example 2:"
},
{
"code": null,
"e": 26577,
"s": 26501,
"text": "var str = 'JavaScript is object oriented language';\nprint(str.charAt(50));\n"
},
{
"code": null,
"e": 26585,
"s": 26577,
"text": "Output:"
},
{
"code": null,
"e": 26763,
"s": 26587,
"text": "In this example the function charAt() finds the character at index 50. Since the index is out of bounds for the given string therefore the function returns “” an empty string."
},
{
"code": null,
"e": 26812,
"s": 26763,
"text": "Codes for the above function are provided below:"
},
{
"code": null,
"e": 26823,
"s": 26812,
"text": "Program 1:"
},
{
"code": "// JavaScript to illustrate charAt() function<script>function func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(9); document.write(value); }func();</script> ",
"e": 27096,
"s": 26823,
"text": null
},
{
"code": null,
"e": 27104,
"s": 27096,
"text": "Output:"
},
{
"code": null,
"e": 27107,
"s": 27104,
"text": "t\n"
},
{
"code": null,
"e": 27118,
"s": 27107,
"text": "Program 2:"
},
{
"code": "<script>// JavaScript to illustrate charAt() functionfunction func() { // Original string var str = 'JavaScript is object oriented language'; // Finding the character at given index var value = str.charAt(50); document.write(value); }func();</script> ",
"e": 27394,
"s": 27118,
"text": null
},
{
"code": null,
"e": 27402,
"s": 27394,
"text": "Output:"
},
{
"code": null,
"e": 27423,
"s": 27404,
"text": "Supported Browser:"
},
{
"code": null,
"e": 27442,
"s": 27423,
"text": "Chrome 1 and above"
},
{
"code": null,
"e": 27460,
"s": 27442,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 27480,
"s": 27460,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 27510,
"s": 27480,
"text": "Internet Explorer 3 and above"
},
{
"code": null,
"e": 27528,
"s": 27510,
"text": "Opera 3 and above"
},
{
"code": null,
"e": 27537,
"s": 27528,
"text": "Safari 1"
},
{
"code": null,
"e": 27550,
"s": 27537,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 27562,
"s": 27550,
"text": "ysachin2314"
},
{
"code": null,
"e": 27580,
"s": 27562,
"text": "javascript-string"
},
{
"code": null,
"e": 27591,
"s": 27580,
"text": "JavaScript"
},
{
"code": null,
"e": 27608,
"s": 27591,
"text": "Web Technologies"
},
{
"code": null,
"e": 27706,
"s": 27608,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27715,
"s": 27706,
"text": "Comments"
},
{
"code": null,
"e": 27728,
"s": 27715,
"text": "Old Comments"
},
{
"code": null,
"e": 27789,
"s": 27728,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27834,
"s": 27789,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27906,
"s": 27834,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27958,
"s": 27906,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28004,
"s": 27958,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28060,
"s": 28004,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28093,
"s": 28060,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28155,
"s": 28093,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28198,
"s": 28155,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
geom_area plot with areas and outlines in ggplot2 in R - GeeksforGeeks
|
24 Oct, 2021
An Area Plot helps us to visualize the variation in quantitative quantity with respect to some other quantity. It is simply a line chart where the area under the plot is colored/shaded. It is best used to study the trends of variation over a period of time, where we want to analyze the value of one variable change over a period of time or respect to any other variable.
In this article, we will discuss how to draw an area plot in the R Programming Language using the ggplot2 package. To do so we use the geom_area() function that helps us create the area plot layer.
Syntax: geom_area(mapping, data , stat , position)
Argument:
mapping: determines the aesthetic mapping usually constructed with aes() function.
data: determines the data frame to be used for mapping.
stat: determines the statistical transformation.
position: determines the position adjustment for overlapping points.
Example:
Here is a basic area plot using the geom_area() function.
R
# create dataframeset.seed(1234)df <- data.frame(value =round(c(rnorm(2000, mean=100, sd=7)))) # import libraries ggplot2library(ggplot2) # create area plot ggplot(df, aes(x=value)) + geom_area(stat = "bin")
Output:
We can customize the color of the plot fill, outline as well as line type of outline using the color, fill, and linetype parameters of the geom_area() function.
Syntax: plot + geom_area( color, fill, linetype, alpha)
Parameters:
color: determines the color of the outline of the area plot.
fill: determines the color of background fill.
linetype: determines the type of outline in the plot.
alpha: determines the transparency of plot fill.
Example:
Here is an area plot with green color fill and a green outline with a dashed line and 50% transparency.
R
# create dataframeset.seed(1234)df <- data.frame(value =round(c(rnorm(2000, mean=100, sd=7)))) # import libraries ggplot2library(ggplot2) # create area plot# color, fill and linetype parameters# are used for color customization ggplot(df, aes(x=value)) + geom_area(stat = "bin", color = "#2bab53", fill = "#2bab53", linetype = "dashed", alpha = 0.5)
Output:
To create an outline plot using the geom_area() function, we create a basic area plot with transparency set to zero percent using the alpha parameter of the geom_area() function.
Syntax: geom_area( alpha=0 )
Example:
Here, is an outline plot with a green outline made using the geom_area() function.
R
# create dataframeset.seed(1234)df <- data.frame(value =round(c(rnorm(2000, mean=100, sd=7)))) # import libraries ggplot2library(ggplot2) # create area plot# alpha as zero is used for converting area plot to line plot ggplot(df, aes(x=value)) + geom_area(stat = "bin", color = "#2bab53", alpha = 0)
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n24 Oct, 2021"
},
{
"code": null,
"e": 25223,
"s": 24851,
"text": "An Area Plot helps us to visualize the variation in quantitative quantity with respect to some other quantity. It is simply a line chart where the area under the plot is colored/shaded. It is best used to study the trends of variation over a period of time, where we want to analyze the value of one variable change over a period of time or respect to any other variable."
},
{
"code": null,
"e": 25421,
"s": 25223,
"text": "In this article, we will discuss how to draw an area plot in the R Programming Language using the ggplot2 package. To do so we use the geom_area() function that helps us create the area plot layer."
},
{
"code": null,
"e": 25472,
"s": 25421,
"text": "Syntax: geom_area(mapping, data , stat , position)"
},
{
"code": null,
"e": 25482,
"s": 25472,
"text": "Argument:"
},
{
"code": null,
"e": 25565,
"s": 25482,
"text": "mapping: determines the aesthetic mapping usually constructed with aes() function."
},
{
"code": null,
"e": 25621,
"s": 25565,
"text": "data: determines the data frame to be used for mapping."
},
{
"code": null,
"e": 25670,
"s": 25621,
"text": "stat: determines the statistical transformation."
},
{
"code": null,
"e": 25739,
"s": 25670,
"text": "position: determines the position adjustment for overlapping points."
},
{
"code": null,
"e": 25748,
"s": 25739,
"text": "Example:"
},
{
"code": null,
"e": 25806,
"s": 25748,
"text": "Here is a basic area plot using the geom_area() function."
},
{
"code": null,
"e": 25808,
"s": 25806,
"text": "R"
},
{
"code": "# create dataframeset.seed(1234)df <- data.frame(value =round(c(rnorm(2000, mean=100, sd=7)))) # import libraries ggplot2library(ggplot2) # create area plot ggplot(df, aes(x=value)) + geom_area(stat = \"bin\")",
"e": 26094,
"s": 25808,
"text": null
},
{
"code": null,
"e": 26102,
"s": 26094,
"text": "Output:"
},
{
"code": null,
"e": 26263,
"s": 26102,
"text": "We can customize the color of the plot fill, outline as well as line type of outline using the color, fill, and linetype parameters of the geom_area() function."
},
{
"code": null,
"e": 26319,
"s": 26263,
"text": "Syntax: plot + geom_area( color, fill, linetype, alpha)"
},
{
"code": null,
"e": 26332,
"s": 26319,
"text": "Parameters: "
},
{
"code": null,
"e": 26393,
"s": 26332,
"text": "color: determines the color of the outline of the area plot."
},
{
"code": null,
"e": 26441,
"s": 26393,
"text": "fill: determines the color of background fill."
},
{
"code": null,
"e": 26495,
"s": 26441,
"text": "linetype: determines the type of outline in the plot."
},
{
"code": null,
"e": 26544,
"s": 26495,
"text": "alpha: determines the transparency of plot fill."
},
{
"code": null,
"e": 26553,
"s": 26544,
"text": "Example:"
},
{
"code": null,
"e": 26657,
"s": 26553,
"text": "Here is an area plot with green color fill and a green outline with a dashed line and 50% transparency."
},
{
"code": null,
"e": 26659,
"s": 26657,
"text": "R"
},
{
"code": "# create dataframeset.seed(1234)df <- data.frame(value =round(c(rnorm(2000, mean=100, sd=7)))) # import libraries ggplot2library(ggplot2) # create area plot# color, fill and linetype parameters# are used for color customization ggplot(df, aes(x=value)) + geom_area(stat = \"bin\", color = \"#2bab53\", fill = \"#2bab53\", linetype = \"dashed\", alpha = 0.5)",
"e": 27143,
"s": 26659,
"text": null
},
{
"code": null,
"e": 27151,
"s": 27143,
"text": "Output:"
},
{
"code": null,
"e": 27330,
"s": 27151,
"text": "To create an outline plot using the geom_area() function, we create a basic area plot with transparency set to zero percent using the alpha parameter of the geom_area() function."
},
{
"code": null,
"e": 27359,
"s": 27330,
"text": "Syntax: geom_area( alpha=0 )"
},
{
"code": null,
"e": 27368,
"s": 27359,
"text": "Example:"
},
{
"code": null,
"e": 27451,
"s": 27368,
"text": "Here, is an outline plot with a green outline made using the geom_area() function."
},
{
"code": null,
"e": 27453,
"s": 27451,
"text": "R"
},
{
"code": "# create dataframeset.seed(1234)df <- data.frame(value =round(c(rnorm(2000, mean=100, sd=7)))) # import libraries ggplot2library(ggplot2) # create area plot# alpha as zero is used for converting area plot to line plot ggplot(df, aes(x=value)) + geom_area(stat = \"bin\", color = \"#2bab53\", alpha = 0)",
"e": 27863,
"s": 27453,
"text": null
},
{
"code": null,
"e": 27871,
"s": 27863,
"text": "Output:"
},
{
"code": null,
"e": 27878,
"s": 27871,
"text": "Picked"
},
{
"code": null,
"e": 27887,
"s": 27878,
"text": "R-ggplot"
},
{
"code": null,
"e": 27898,
"s": 27887,
"text": "R Language"
},
{
"code": null,
"e": 27996,
"s": 27898,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28005,
"s": 27996,
"text": "Comments"
},
{
"code": null,
"e": 28018,
"s": 28005,
"text": "Old Comments"
},
{
"code": null,
"e": 28070,
"s": 28018,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28108,
"s": 28070,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28143,
"s": 28108,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28201,
"s": 28143,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28250,
"s": 28201,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28293,
"s": 28250,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28343,
"s": 28293,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 28360,
"s": 28343,
"text": "R - if statement"
},
{
"code": null,
"e": 28397,
"s": 28360,
"text": "How to import an Excel File into R ?"
}
] |
C# | Check if an array object is equal to another array object - GeeksforGeeks
|
06 Jan, 2022
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Equals(Object) method which is inherited by Array class from object class is used to check whether an array is equal to another array or not.
Syntax:
public virtual bool Equals (object obj);
Here, obj is the object which is to be compared with the current object.Return Value: This method return true if the specified object is equal to the current object otherwise it returns false.
Below programs illustrate the use of above-discussed method:
Example 1:
C#
// C# code to check if a Array is// equal to other Array or notusing System; namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Two-dimensional array int[, ] intarray = new int[, ] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // check if intarray is // equal to itself or not Console.WriteLine(intarray.Equals(intarray)); }}}
True
Example 2:
C#
// C# code to check if an Array is// equal to other Array or notusing System; namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Creating and initializing new the String String[] arr1 = new String[4] { "Sun", "Mon", "Tue", "Thu" }; // taking anotther array String[] arr2 = new String[4] { "Sun", "Mon", "Tue", "Thu" }; // check if arr1 is // equal to arr2 or not Console.WriteLine(arr1.Equals(arr2)); // assigning arr1 reference to arr3 String[] arr3 = new String[4]; arr3 = arr1; // check if arr2 is // equal to arr3 or not Console.WriteLine(arr2.Equals(arr3)); // check if arr1 is // equal to arr3 or not // it will return true as both // array object refer to same Console.WriteLine(arr1.Equals(arr3)); }}}
False
False
True
Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality.
sweetyty
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
Common Language Runtime (CLR) in C#
C# | Encapsulation
|
[
{
"code": null,
"e": 24137,
"s": 24109,
"text": "\n06 Jan, 2022"
},
{
"code": null,
"e": 24416,
"s": 24137,
"text": "An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Equals(Object) method which is inherited by Array class from object class is used to check whether an array is equal to another array or not."
},
{
"code": null,
"e": 24425,
"s": 24416,
"text": "Syntax: "
},
{
"code": null,
"e": 24466,
"s": 24425,
"text": "public virtual bool Equals (object obj);"
},
{
"code": null,
"e": 24659,
"s": 24466,
"text": "Here, obj is the object which is to be compared with the current object.Return Value: This method return true if the specified object is equal to the current object otherwise it returns false."
},
{
"code": null,
"e": 24720,
"s": 24659,
"text": "Below programs illustrate the use of above-discussed method:"
},
{
"code": null,
"e": 24732,
"s": 24720,
"text": "Example 1: "
},
{
"code": null,
"e": 24735,
"s": 24732,
"text": "C#"
},
{
"code": "// C# code to check if a Array is// equal to other Array or notusing System; namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Two-dimensional array int[, ] intarray = new int[, ] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } }; // check if intarray is // equal to itself or not Console.WriteLine(intarray.Equals(intarray)); }}}",
"e": 25263,
"s": 24735,
"text": null
},
{
"code": null,
"e": 25268,
"s": 25263,
"text": "True"
},
{
"code": null,
"e": 25281,
"s": 25270,
"text": "Example 2:"
},
{
"code": null,
"e": 25284,
"s": 25281,
"text": "C#"
},
{
"code": "// C# code to check if an Array is// equal to other Array or notusing System; namespace geeksforgeeks { class GFG { // Main Method public static void Main() { // Creating and initializing new the String String[] arr1 = new String[4] { \"Sun\", \"Mon\", \"Tue\", \"Thu\" }; // taking anotther array String[] arr2 = new String[4] { \"Sun\", \"Mon\", \"Tue\", \"Thu\" }; // check if arr1 is // equal to arr2 or not Console.WriteLine(arr1.Equals(arr2)); // assigning arr1 reference to arr3 String[] arr3 = new String[4]; arr3 = arr1; // check if arr2 is // equal to arr3 or not Console.WriteLine(arr2.Equals(arr3)); // check if arr1 is // equal to arr3 or not // it will return true as both // array object refer to same Console.WriteLine(arr1.Equals(arr3)); }}}",
"e": 26236,
"s": 25284,
"text": null
},
{
"code": null,
"e": 26253,
"s": 26236,
"text": "False\nFalse\nTrue"
},
{
"code": null,
"e": 26364,
"s": 26255,
"text": "Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality. "
},
{
"code": null,
"e": 26373,
"s": 26364,
"text": "sweetyty"
},
{
"code": null,
"e": 26387,
"s": 26373,
"text": "CSharp-Arrays"
},
{
"code": null,
"e": 26401,
"s": 26387,
"text": "CSharp-method"
},
{
"code": null,
"e": 26404,
"s": 26401,
"text": "C#"
},
{
"code": null,
"e": 26502,
"s": 26404,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26511,
"s": 26502,
"text": "Comments"
},
{
"code": null,
"e": 26524,
"s": 26511,
"text": "Old Comments"
},
{
"code": null,
"e": 26570,
"s": 26524,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 26585,
"s": 26570,
"text": "C# | Delegates"
},
{
"code": null,
"e": 26625,
"s": 26585,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 26643,
"s": 26625,
"text": "C# | Constructors"
},
{
"code": null,
"e": 26674,
"s": 26643,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 26697,
"s": 26674,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 26719,
"s": 26697,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 26741,
"s": 26719,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 26777,
"s": 26741,
"text": "Common Language Runtime (CLR) in C#"
}
] |
How to get the Width and Height of the screen in JavaScript?
|
Javascript has provided window.screen object that contains information regarding the user's screen. The information includes height and width, and also many other features. To find the height and width of the screen the methods provided by javascript are screen.height and screen.width respectively.
scree.height;
scree.width;
In the following example, the width of the screen is displayed using the screen.width method.
Live Demo
<html>
<body>
<p id="width"> </p>
<script>
document.getElementById("width").innerHTML =
"Screen width is " + screen.width;
</script>
</body>
</html>
1366
In the following example, the height of the screen is displayed using the screen.height method.
Live Demo
<html>
<body>
<p id="height"> </p>
<script>
document.getElementById("height").innerHTML =
"Screen heigth is " + screen.height;
</script>
</body>
</html>
768
|
[
{
"code": null,
"e": 1362,
"s": 1062,
"text": "Javascript has provided window.screen object that contains information regarding the user's screen. The information includes height and width, and also many other features. To find the height and width of the screen the methods provided by javascript are screen.height and screen.width respectively."
},
{
"code": null,
"e": 1376,
"s": 1362,
"text": "scree.height;"
},
{
"code": null,
"e": 1389,
"s": 1376,
"text": "scree.width;"
},
{
"code": null,
"e": 1483,
"s": 1389,
"text": "In the following example, the width of the screen is displayed using the screen.width method."
},
{
"code": null,
"e": 1493,
"s": 1483,
"text": "Live Demo"
},
{
"code": null,
"e": 1660,
"s": 1493,
"text": "<html>\n<body>\n<p id=\"width\"> </p>\n <script>\n document.getElementById(\"width\").innerHTML =\n \"Screen width is \" + screen.width;\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1665,
"s": 1660,
"text": "1366"
},
{
"code": null,
"e": 1761,
"s": 1665,
"text": "In the following example, the height of the screen is displayed using the screen.height method."
},
{
"code": null,
"e": 1771,
"s": 1761,
"text": "Live Demo"
},
{
"code": null,
"e": 1945,
"s": 1771,
"text": "<html>\n<body>\n <p id=\"height\"> </p>\n <script>\n document.getElementById(\"height\").innerHTML =\n \"Screen heigth is \" + screen.height;\n </script>\n</body>\n</html>"
},
{
"code": null,
"e": 1949,
"s": 1945,
"text": "768"
}
] |
Gradle - Testing
|
The test task automatically detects and executes all the unit tests in the test source set., Once the test execution is complete, it also generates a report. JUnit and TestNG are the supported APIs.
The test task provides a Test.getDebug() method that can be set to launch to make the JVM wait for a debugger. Before proceeding to the execution, it sets the debugger post to 5005.
The Test Task detects which classes are test classes by inspecting the compiled test classes. By default, it scans all .class files. You can set custom includes / excludes and only those classes will be scanned.
Depending on the test framework used (JUnit / TestNG), the test class detection uses the different criteria. When using JUnit, we scan for both JUnit 3 and 4 test classes.
If any of the following criteria match, the class is considered to be a JUnit test class −
Class or a super class extends TestCase or GroovyTestCase
Class or a super class is annotated with @RunWith
Class or a super class contain a method annotated with @Test
When using TestNG, we scan for methods annotated with @Test
Note − The abstract classes are not executed. Gradle also scans the inheritance tree into jar files on the test classpath.
If you don't want to use test class detection, you can disable it by setting scanForTestClasses to false.
JUnit and TestNG allows sophisticated grouping of test methods. For grouping, JUnit test classes and methods JUnit 4.8 introduces the concept of categories. The test task allows the specification of the JUnit categories, which you want to include and exclude.
You can use the following code snippet in build.gradle file to group test methods −
test {
useJUnit {
includeCategories 'org.gradle.junit.CategoryA'
excludeCategories 'org.gradle.junit.CategoryB'
}
}
The Test class has an include and exclude method. These methods can be used to specify, which tests should actually be run.
Use the below mentioned code to run only the included tests −
test {
include '**my.package.name/*'
}
Use the code given below to skip the excluded tests −
test {
exclude '**my.package.name/*'
}
The sample build.gradle file as shown below it shows different configuration options.
apply plugin: 'java' // adds 'test' task
test {
// enable TestNG support (default is JUnit)
useTestNG()
// set a system property for the test JVM(s)
systemProperty 'some.prop', 'value'
// explicitly include or exclude tests
include 'org/foo/**'
exclude 'org/boo/**'
// show standard out and standard error of the test JVM(s) on the console
testLogging.showStandardStreams = true
// set heap size for the test JVM(s)
minHeapSize = "128m"
maxHeapSize = "512m"
// set JVM arguments for the test JVM(s)
jvmArgs '-XX:MaxPermSize=256m'
// listen to events in the test execution lifecycle
beforeTest {
descriptor → logger.lifecycle("Running test: " + descriptor)
}
// listen to standard out and standard error of the test JVM(s)
onOutput {
descriptor, event → logger.lifecycle
("Test: " + descriptor + " produced standard out/err: "
+ event.message )
}
}
You can use the following command syntax to execute some test task.
gradle <someTestTask> --debug-jvm
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2081,
"s": 1882,
"text": "The test task automatically detects and executes all the unit tests in the test source set., Once the test execution is complete, it also generates a report. JUnit and TestNG are the supported APIs."
},
{
"code": null,
"e": 2263,
"s": 2081,
"text": "The test task provides a Test.getDebug() method that can be set to launch to make the JVM wait for a debugger. Before proceeding to the execution, it sets the debugger post to 5005."
},
{
"code": null,
"e": 2475,
"s": 2263,
"text": "The Test Task detects which classes are test classes by inspecting the compiled test classes. By default, it scans all .class files. You can set custom includes / excludes and only those classes will be scanned."
},
{
"code": null,
"e": 2647,
"s": 2475,
"text": "Depending on the test framework used (JUnit / TestNG), the test class detection uses the different criteria. When using JUnit, we scan for both JUnit 3 and 4 test classes."
},
{
"code": null,
"e": 2738,
"s": 2647,
"text": "If any of the following criteria match, the class is considered to be a JUnit test class −"
},
{
"code": null,
"e": 2796,
"s": 2738,
"text": "Class or a super class extends TestCase or GroovyTestCase"
},
{
"code": null,
"e": 2846,
"s": 2796,
"text": "Class or a super class is annotated with @RunWith"
},
{
"code": null,
"e": 2907,
"s": 2846,
"text": "Class or a super class contain a method annotated with @Test"
},
{
"code": null,
"e": 2967,
"s": 2907,
"text": "When using TestNG, we scan for methods annotated with @Test"
},
{
"code": null,
"e": 3090,
"s": 2967,
"text": "Note − The abstract classes are not executed. Gradle also scans the inheritance tree into jar files on the test classpath."
},
{
"code": null,
"e": 3196,
"s": 3090,
"text": "If you don't want to use test class detection, you can disable it by setting scanForTestClasses to false."
},
{
"code": null,
"e": 3456,
"s": 3196,
"text": "JUnit and TestNG allows sophisticated grouping of test methods. For grouping, JUnit test classes and methods JUnit 4.8 introduces the concept of categories. The test task allows the specification of the JUnit categories, which you want to include and exclude."
},
{
"code": null,
"e": 3540,
"s": 3456,
"text": "You can use the following code snippet in build.gradle file to group test methods −"
},
{
"code": null,
"e": 3674,
"s": 3540,
"text": "test {\n useJUnit {\n includeCategories 'org.gradle.junit.CategoryA'\n excludeCategories 'org.gradle.junit.CategoryB'\n }\n}"
},
{
"code": null,
"e": 3798,
"s": 3674,
"text": "The Test class has an include and exclude method. These methods can be used to specify, which tests should actually be run."
},
{
"code": null,
"e": 3860,
"s": 3798,
"text": "Use the below mentioned code to run only the included tests −"
},
{
"code": null,
"e": 3903,
"s": 3860,
"text": "test {\n include '**my.package.name/*'\n}\n"
},
{
"code": null,
"e": 3957,
"s": 3903,
"text": "Use the code given below to skip the excluded tests −"
},
{
"code": null,
"e": 4000,
"s": 3957,
"text": "test {\n exclude '**my.package.name/*'\n}\n"
},
{
"code": null,
"e": 4086,
"s": 4000,
"text": "The sample build.gradle file as shown below it shows different configuration options."
},
{
"code": null,
"e": 5038,
"s": 4086,
"text": "apply plugin: 'java' // adds 'test' task\n\ntest {\n // enable TestNG support (default is JUnit)\n useTestNG()\n\n // set a system property for the test JVM(s)\n systemProperty 'some.prop', 'value'\n\n // explicitly include or exclude tests\n include 'org/foo/**'\n exclude 'org/boo/**'\n\n // show standard out and standard error of the test JVM(s) on the console\n testLogging.showStandardStreams = true\n\n // set heap size for the test JVM(s)\n minHeapSize = \"128m\"\n maxHeapSize = \"512m\"\n\n // set JVM arguments for the test JVM(s)\n jvmArgs '-XX:MaxPermSize=256m'\n \n // listen to events in the test execution lifecycle\n beforeTest { \n descriptor → logger.lifecycle(\"Running test: \" + descriptor)\n }\n\n // listen to standard out and standard error of the test JVM(s)\n onOutput { \n descriptor, event → logger.lifecycle\n (\"Test: \" + descriptor + \" produced standard out/err: \" \n + event.message )\n }\n}"
},
{
"code": null,
"e": 5106,
"s": 5038,
"text": "You can use the following command syntax to execute some test task."
},
{
"code": null,
"e": 5141,
"s": 5106,
"text": "gradle <someTestTask> --debug-jvm\n"
},
{
"code": null,
"e": 5148,
"s": 5141,
"text": " Print"
},
{
"code": null,
"e": 5159,
"s": 5148,
"text": " Add Notes"
}
] |
An introduction to Generalized Estimating Equations | by Robert Greener | Towards Data Science
|
A key assumption underpinning generalized linear models (which linear regression is a type of) is the independence of observations. In longitudinal data this will simply not hold. Observations within an individual (between time points) are likely to be more similar than those between individuals.
So, how do you deal with this? One option is to fit a generalized linear mixed model in which there are random intercept and slope terms for each individual. This will tell you for a specific individual (i.e. conditional on the random intercept and slope) what is the effect of a variable on an outcome. However, this isn’t very useful if you are concerned with the marginal effect, i.e. what is the effect of a variable on an outcome on average in the population.
If you want to answer these population questions you need to fit a generalized linear model using generalized estimating equations (GEE). This is an approach that obtains the population average effect accounting for the fact that observations within individuals are likely to be more similar than those between individuals.
Suppose we have our outcome — all-cause mortality. Now suppose we record this every month for 10 months for every person. Now suppose our exposure, which is just time. We can now define a logistic regression model, with the sole independent variable being time (in months) and the dependent variable being death at that time. “Okay, great” I hear you say “but these observations are obviously not independent!”. Spot on, but we’ll come to that.
To use GEE we must first define how time points are related. However, by using Huber-White standard errors our results will be consistent even if we misspecify this relationship! So we have some choices.
This working correlation structure assumes that time points are independent of each other. This is probably an unreasonable assumption in practice.
This is where the correlation between observations at two time points is equal for any two time points. This is commonly used as it requires just one additional parameter α to be estimated.
This is where the correlation between observations follows an autoregressive structure. Suppose we were using an AR-1 correlation matrix. This would mean that the correlation between month 1 and 2 of a person would be expected to be α and the correlation between month 1 and 3 of a person would be expected to be α2, between month 1 and 4 would be α3 and so on.
This is most appropriate when you think closer together time points are more similar than further apart time points.
This is where we estimate a separate α for each possible combination of time points. This is the most general case. Though you need a lot of data to be able to estimate all of the α used.
There do exist some other choices, but these aren’t widely used.
It’s simple. Either choose the most general one your data can support (depending on sample size) or you can choose one you think suits the data best. Either way, don’t sweat it! This approach is consistent even if you misspecify this.
Fitting the model is simple. We just fit a GLM using GEE with our specified working correlation matrix:
Where:
Yij is 1 if participant i died at time j
pij is the probability of death for participant i at time j
β0 is the population average log odds of death at time 0. This can be exponentiated to obtain the odds of death at time 0.
β1 is the population average difference in log odds of death associated with a one-month increase in time. This can be exponentiated to obtain the odds ratio associated with a one-month increase in time.
Tij is the time of the j’th measurement for participant i in months.
That’s it. Our population average effect of a one-month increase on time increases the odds of death by an odds ratio of exp(β1).
We can do this in R using geepack. Suppose our dataframe already existed with three columns death time and person.id all we have to do is:
library(geepack)mod <- geeglm(death ~ time, id = person.id, waves = time, family=binomial, corstr="exchangeable")
You can then just call summary(mod) as normal and get your results!
And of course, you could add covariates to the model by just adding them to the formula. They can be time-varying or constant — either is fine!
Hopefully you’ve come away from reading this with a basic idea of GEE. They should be a tool in the toolbox of any data scientist working with longitudinal data.
|
[
{
"code": null,
"e": 469,
"s": 171,
"text": "A key assumption underpinning generalized linear models (which linear regression is a type of) is the independence of observations. In longitudinal data this will simply not hold. Observations within an individual (between time points) are likely to be more similar than those between individuals."
},
{
"code": null,
"e": 934,
"s": 469,
"text": "So, how do you deal with this? One option is to fit a generalized linear mixed model in which there are random intercept and slope terms for each individual. This will tell you for a specific individual (i.e. conditional on the random intercept and slope) what is the effect of a variable on an outcome. However, this isn’t very useful if you are concerned with the marginal effect, i.e. what is the effect of a variable on an outcome on average in the population."
},
{
"code": null,
"e": 1258,
"s": 934,
"text": "If you want to answer these population questions you need to fit a generalized linear model using generalized estimating equations (GEE). This is an approach that obtains the population average effect accounting for the fact that observations within individuals are likely to be more similar than those between individuals."
},
{
"code": null,
"e": 1703,
"s": 1258,
"text": "Suppose we have our outcome — all-cause mortality. Now suppose we record this every month for 10 months for every person. Now suppose our exposure, which is just time. We can now define a logistic regression model, with the sole independent variable being time (in months) and the dependent variable being death at that time. “Okay, great” I hear you say “but these observations are obviously not independent!”. Spot on, but we’ll come to that."
},
{
"code": null,
"e": 1907,
"s": 1703,
"text": "To use GEE we must first define how time points are related. However, by using Huber-White standard errors our results will be consistent even if we misspecify this relationship! So we have some choices."
},
{
"code": null,
"e": 2055,
"s": 1907,
"text": "This working correlation structure assumes that time points are independent of each other. This is probably an unreasonable assumption in practice."
},
{
"code": null,
"e": 2245,
"s": 2055,
"text": "This is where the correlation between observations at two time points is equal for any two time points. This is commonly used as it requires just one additional parameter α to be estimated."
},
{
"code": null,
"e": 2607,
"s": 2245,
"text": "This is where the correlation between observations follows an autoregressive structure. Suppose we were using an AR-1 correlation matrix. This would mean that the correlation between month 1 and 2 of a person would be expected to be α and the correlation between month 1 and 3 of a person would be expected to be α2, between month 1 and 4 would be α3 and so on."
},
{
"code": null,
"e": 2724,
"s": 2607,
"text": "This is most appropriate when you think closer together time points are more similar than further apart time points."
},
{
"code": null,
"e": 2912,
"s": 2724,
"text": "This is where we estimate a separate α for each possible combination of time points. This is the most general case. Though you need a lot of data to be able to estimate all of the α used."
},
{
"code": null,
"e": 2977,
"s": 2912,
"text": "There do exist some other choices, but these aren’t widely used."
},
{
"code": null,
"e": 3212,
"s": 2977,
"text": "It’s simple. Either choose the most general one your data can support (depending on sample size) or you can choose one you think suits the data best. Either way, don’t sweat it! This approach is consistent even if you misspecify this."
},
{
"code": null,
"e": 3316,
"s": 3212,
"text": "Fitting the model is simple. We just fit a GLM using GEE with our specified working correlation matrix:"
},
{
"code": null,
"e": 3323,
"s": 3316,
"text": "Where:"
},
{
"code": null,
"e": 3364,
"s": 3323,
"text": "Yij is 1 if participant i died at time j"
},
{
"code": null,
"e": 3424,
"s": 3364,
"text": "pij is the probability of death for participant i at time j"
},
{
"code": null,
"e": 3547,
"s": 3424,
"text": "β0 is the population average log odds of death at time 0. This can be exponentiated to obtain the odds of death at time 0."
},
{
"code": null,
"e": 3751,
"s": 3547,
"text": "β1 is the population average difference in log odds of death associated with a one-month increase in time. This can be exponentiated to obtain the odds ratio associated with a one-month increase in time."
},
{
"code": null,
"e": 3820,
"s": 3751,
"text": "Tij is the time of the j’th measurement for participant i in months."
},
{
"code": null,
"e": 3950,
"s": 3820,
"text": "That’s it. Our population average effect of a one-month increase on time increases the odds of death by an odds ratio of exp(β1)."
},
{
"code": null,
"e": 4089,
"s": 3950,
"text": "We can do this in R using geepack. Suppose our dataframe already existed with three columns death time and person.id all we have to do is:"
},
{
"code": null,
"e": 4203,
"s": 4089,
"text": "library(geepack)mod <- geeglm(death ~ time, id = person.id, waves = time, family=binomial, corstr=\"exchangeable\")"
},
{
"code": null,
"e": 4271,
"s": 4203,
"text": "You can then just call summary(mod) as normal and get your results!"
},
{
"code": null,
"e": 4415,
"s": 4271,
"text": "And of course, you could add covariates to the model by just adding them to the formula. They can be time-varying or constant — either is fine!"
}
] |
DoubleStream sorted() in Java - GeeksforGeeks
|
06 Dec, 2018
DoubleStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream.
Syntax :
DoubleStream sorted()
Where, DoubleStream is a sequence of primitive double-valued
elements. This is the double primitive specialization of Stream.
Return Value : DoubleStream sorted() method returns the new stream having the elements in sorted order.
Example 1 : Using DoubleStream sorted() to sort the numbers in given DoubleStream.
// Java code to sort DoubleStream// using DoubleStream.sorted()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of(10.2, 9.3, 8.4, 7.5, 6.6); // displaying the stream with sorted elements // using DoubleStream.sorted() function stream.sorted().forEach(System.out::println); }}
6.6
7.5
8.4
9.3
10.2
Example 2 : Using DoubleStream sorted() to sort the random numbers generated by DoubleStream generator().
// Java code to sort DoubleStream// using DoubleStream.sorted()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream by generating // random elements using DoubleStream.generate() DoubleStream stream = DoubleStream.generate(() -> (double)(Math.random() * 10000)).limit(5); // displaying the stream with sorted elements // using DoubleStream.sorted() function stream.sorted().forEach(System.out::println); }}
1279.6146863795122
6927.016817313592
7037.390703089559
8374.314582282514
9112.609381925824
Java - util package
java-DoubleStream
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Generics in Java
Comparator Interface in Java with Examples
Strings in Java
How to remove an element from ArrayList in Java?
Difference between Abstract Class and Interface in Java
|
[
{
"code": null,
"e": 23557,
"s": 23529,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 23995,
"s": 23557,
"text": "DoubleStream sorted() returns a stream consisting of the elements of this stream in sorted order. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Stateful intermediate operations may need to process the entire input before producing a result. For example, one cannot produce any results from sorting a stream until one has seen all elements of the stream."
},
{
"code": null,
"e": 24004,
"s": 23995,
"text": "Syntax :"
},
{
"code": null,
"e": 24155,
"s": 24004,
"text": "DoubleStream sorted()\n\nWhere, DoubleStream is a sequence of primitive double-valued \nelements. This is the double primitive specialization of Stream.\n"
},
{
"code": null,
"e": 24259,
"s": 24155,
"text": "Return Value : DoubleStream sorted() method returns the new stream having the elements in sorted order."
},
{
"code": null,
"e": 24342,
"s": 24259,
"text": "Example 1 : Using DoubleStream sorted() to sort the numbers in given DoubleStream."
},
{
"code": "// Java code to sort DoubleStream// using DoubleStream.sorted()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream DoubleStream stream = DoubleStream.of(10.2, 9.3, 8.4, 7.5, 6.6); // displaying the stream with sorted elements // using DoubleStream.sorted() function stream.sorted().forEach(System.out::println); }}",
"e": 24855,
"s": 24342,
"text": null
},
{
"code": null,
"e": 24877,
"s": 24855,
"text": "6.6\n7.5\n8.4\n9.3\n10.2\n"
},
{
"code": null,
"e": 24983,
"s": 24877,
"text": "Example 2 : Using DoubleStream sorted() to sort the random numbers generated by DoubleStream generator()."
},
{
"code": "// Java code to sort DoubleStream// using DoubleStream.sorted()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // Creating an DoubleStream by generating // random elements using DoubleStream.generate() DoubleStream stream = DoubleStream.generate(() -> (double)(Math.random() * 10000)).limit(5); // displaying the stream with sorted elements // using DoubleStream.sorted() function stream.sorted().forEach(System.out::println); }}",
"e": 25558,
"s": 24983,
"text": null
},
{
"code": null,
"e": 25650,
"s": 25558,
"text": "1279.6146863795122\n6927.016817313592\n7037.390703089559\n8374.314582282514\n9112.609381925824\n"
},
{
"code": null,
"e": 25670,
"s": 25650,
"text": "Java - util package"
},
{
"code": null,
"e": 25688,
"s": 25670,
"text": "java-DoubleStream"
},
{
"code": null,
"e": 25703,
"s": 25688,
"text": "Java-Functions"
},
{
"code": null,
"e": 25715,
"s": 25703,
"text": "java-stream"
},
{
"code": null,
"e": 25720,
"s": 25715,
"text": "Java"
},
{
"code": null,
"e": 25725,
"s": 25720,
"text": "Java"
},
{
"code": null,
"e": 25823,
"s": 25725,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25832,
"s": 25823,
"text": "Comments"
},
{
"code": null,
"e": 25845,
"s": 25832,
"text": "Old Comments"
},
{
"code": null,
"e": 25875,
"s": 25845,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25890,
"s": 25875,
"text": "Stream In Java"
},
{
"code": null,
"e": 25911,
"s": 25890,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25957,
"s": 25911,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25976,
"s": 25957,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25993,
"s": 25976,
"text": "Generics in Java"
},
{
"code": null,
"e": 26036,
"s": 25993,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 26052,
"s": 26036,
"text": "Strings in Java"
},
{
"code": null,
"e": 26101,
"s": 26052,
"text": "How to remove an element from ArrayList in Java?"
}
] |
Difference between <article> tag and <section> tag - GeeksforGeeks
|
28 Jan, 2020
Both the tags are semantics tag in HTML 5. In this article, we will discuss the behavior of the <article> and <section> tag. Both the <article> and <section> tags are represented in a similar way but used for some meaning, that meaning is for the browsers and the developers. Both tags can replace each other as there will be no changes to the outputs, but it will be difficult to understand by the developers and the browsers to act on those content.
<article> Tag: This tag contains independent content that doesn’t require any other context. So the <article> tag can be placed inside the main content. But each of the articles will contain independent content within it. Like YouTube use to contain different kinds of videos on a single page, each video is independent or you can see the course page of GeeksforGeeks each course is independent, each course can have its own page.Feature:
An article can have nested articles and that should refer to parent article.
Article tags are perfect for Microdata information.
<section> Tag: This tag is used to split a page into sections like Introduction, Contact Information, Details, etc and each of these sections can be in a different <section> tag. The <section> tag is introduced to wrap-up the things in a particular section. The <section> tag divides the content into sections and subsections. The section tag is used when requirements of two headers or footers or any other section of documents needed. Section tag grouped the generic block of related content.Feature:
A section can have nested sections
Note: Placing <article> tag inside of <section> tag is good practice, like section basically defines the types and the articles will contain the specific contents in that type of section.
Example: In this example we will use both the tags depending on its behavior like articles that contain a list of independent content and the section tag will contain specific sections on a webpage.
<!DOCTYPE html><!DOCTYPE html><html> <head> <title> article tag over section tag </title> <style> .container { width: 650px; height: auto; } .section { float: right; } .article { float: left; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal</p> <div class="container"> <div class="article"> <article> <h2>This is article tag</h2> <p> Above header(h2) placed in article tag </p> </article> <h2>This is non-article tag</h2> <p> The header is larger compare to above header </p> </div> <div class="section"> <section> <h2>This is section tag</h2> <p> Above header(h2) placed in section tag </p> </section> <h2>This is non-section tag</h2> <p> The header is larger compare to above header </p> </div> </div> </center></body> </html>
Output:
Choose one over another:
<section> tag: When you just want to decorate any content in your page i.e. you want to add some functions then you can use <section> tag, also that can be replaced by the <div> tag. The section tag will be good when the content of any web page is appropriate for the contents outline and browsers does not give any attention to the outlines.
<article> tag: The <article> tag is a self-completed tag, this can be used for any of those reasons, where <section> tag is required plus the <article> tag place the content independently. Article tag can be used to place any social post, magazine article, blogs, list of related contents, any independent content.
Tags for:
If your content material contains the date, price, author, description, etc then go for the article tag. Basically use an article tag to contain content that could be shared and obviously for actual articles. Wrap your blog posts in them.
If your content contains any kind of procedure to make or create something that will depend on something then go for the section tag like a div, when it describes what your document outline would include.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Misc
HTML-Tags
Difference Between
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference between Process and Thread
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Difference between Clustered and Non-clustered index
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 23697,
"s": 23669,
"text": "\n28 Jan, 2020"
},
{
"code": null,
"e": 24149,
"s": 23697,
"text": "Both the tags are semantics tag in HTML 5. In this article, we will discuss the behavior of the <article> and <section> tag. Both the <article> and <section> tags are represented in a similar way but used for some meaning, that meaning is for the browsers and the developers. Both tags can replace each other as there will be no changes to the outputs, but it will be difficult to understand by the developers and the browsers to act on those content."
},
{
"code": null,
"e": 24588,
"s": 24149,
"text": "<article> Tag: This tag contains independent content that doesn’t require any other context. So the <article> tag can be placed inside the main content. But each of the articles will contain independent content within it. Like YouTube use to contain different kinds of videos on a single page, each video is independent or you can see the course page of GeeksforGeeks each course is independent, each course can have its own page.Feature:"
},
{
"code": null,
"e": 24665,
"s": 24588,
"text": "An article can have nested articles and that should refer to parent article."
},
{
"code": null,
"e": 24717,
"s": 24665,
"text": "Article tags are perfect for Microdata information."
},
{
"code": null,
"e": 25220,
"s": 24717,
"text": "<section> Tag: This tag is used to split a page into sections like Introduction, Contact Information, Details, etc and each of these sections can be in a different <section> tag. The <section> tag is introduced to wrap-up the things in a particular section. The <section> tag divides the content into sections and subsections. The section tag is used when requirements of two headers or footers or any other section of documents needed. Section tag grouped the generic block of related content.Feature:"
},
{
"code": null,
"e": 25255,
"s": 25220,
"text": "A section can have nested sections"
},
{
"code": null,
"e": 25443,
"s": 25255,
"text": "Note: Placing <article> tag inside of <section> tag is good practice, like section basically defines the types and the articles will contain the specific contents in that type of section."
},
{
"code": null,
"e": 25642,
"s": 25443,
"text": "Example: In this example we will use both the tags depending on its behavior like articles that contain a list of independent content and the section tag will contain specific sections on a webpage."
},
{
"code": "<!DOCTYPE html><!DOCTYPE html><html> <head> <title> article tag over section tag </title> <style> .container { width: 650px; height: auto; } .section { float: right; } .article { float: left; } h1 { color: green; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <p>A Computer Science Portal</p> <div class=\"container\"> <div class=\"article\"> <article> <h2>This is article tag</h2> <p> Above header(h2) placed in article tag </p> </article> <h2>This is non-article tag</h2> <p> The header is larger compare to above header </p> </div> <div class=\"section\"> <section> <h2>This is section tag</h2> <p> Above header(h2) placed in section tag </p> </section> <h2>This is non-section tag</h2> <p> The header is larger compare to above header </p> </div> </div> </center></body> </html>",
"e": 27088,
"s": 25642,
"text": null
},
{
"code": null,
"e": 27096,
"s": 27088,
"text": "Output:"
},
{
"code": null,
"e": 27121,
"s": 27096,
"text": "Choose one over another:"
},
{
"code": null,
"e": 27464,
"s": 27121,
"text": "<section> tag: When you just want to decorate any content in your page i.e. you want to add some functions then you can use <section> tag, also that can be replaced by the <div> tag. The section tag will be good when the content of any web page is appropriate for the contents outline and browsers does not give any attention to the outlines."
},
{
"code": null,
"e": 27779,
"s": 27464,
"text": "<article> tag: The <article> tag is a self-completed tag, this can be used for any of those reasons, where <section> tag is required plus the <article> tag place the content independently. Article tag can be used to place any social post, magazine article, blogs, list of related contents, any independent content."
},
{
"code": null,
"e": 27789,
"s": 27779,
"text": "Tags for:"
},
{
"code": null,
"e": 28028,
"s": 27789,
"text": "If your content material contains the date, price, author, description, etc then go for the article tag. Basically use an article tag to contain content that could be shared and obviously for actual articles. Wrap your blog posts in them."
},
{
"code": null,
"e": 28233,
"s": 28028,
"text": "If your content contains any kind of procedure to make or create something that will depend on something then go for the section tag like a div, when it describes what your document outline would include."
},
{
"code": null,
"e": 28370,
"s": 28233,
"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": 28380,
"s": 28370,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28390,
"s": 28380,
"text": "HTML-Tags"
},
{
"code": null,
"e": 28409,
"s": 28390,
"text": "Difference Between"
},
{
"code": null,
"e": 28414,
"s": 28409,
"text": "HTML"
},
{
"code": null,
"e": 28431,
"s": 28414,
"text": "Web Technologies"
},
{
"code": null,
"e": 28458,
"s": 28431,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28463,
"s": 28458,
"text": "HTML"
},
{
"code": null,
"e": 28561,
"s": 28463,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28570,
"s": 28561,
"text": "Comments"
},
{
"code": null,
"e": 28583,
"s": 28570,
"text": "Old Comments"
},
{
"code": null,
"e": 28644,
"s": 28583,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28682,
"s": 28644,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 28750,
"s": 28682,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 28787,
"s": 28750,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 28840,
"s": 28787,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 28902,
"s": 28840,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28952,
"s": 28902,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29012,
"s": 28952,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29060,
"s": 29012,
"text": "How to update Node.js and NPM to next version ?"
}
] |
React CSS
|
There are many ways to style React with CSS, this tutorial will
take a closer look at inline styling, and CSS
stylesheet.
To style an element with the inline style attribute, the value must be a
JavaScript object:
Insert an object with the styling information:
class MyHeader extends React.Component {
render() {
return (
<div>
<h1 style={{color: "red"}}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
Run
Example »
Note: In JSX, JavaScript expressions are written inside curly braces,
and since JavaScript objects also use curly braces,
the styling in the example above is written inside two sets of curly braces {{}}.
Since the inline CSS is written in a JavaScript object, properties with two names, like background-color,
must be written with camel case syntax:
Use backgroundColor instead of
background-color:
class MyHeader extends React.Component {
render() {
return (
<div>
<h1 style={{backgroundColor: "lightblue"}}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
Run
Example »
You can also create an object with styling information, and refer to it in the style attribute:
Create a style object named mystyle:
class MyHeader extends React.Component {
render() {
const mystyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Arial"
};
return (
<div>
<h1 style={mystyle}>Hello Style!</h1>
<p>Add a little style!</p>
</div>
);
}
}
Run
Example »
You can write your CSS styling in a separate file, just save the file with the
.css file extension, and import it in your
application.
Create a new file called "App.css" and insert some CSS code in it:
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Arial;
text-align: center;
}
Note: You can call the file whatever you like, just remember the correct file extension.
Import the stylesheet in your application:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './App.css';
class MyHeader extends React.Component {
render() {
return (
<div>
<h1>Hello Style!</h1>
<p>Add a little style!.</p>
</div>
);
}
}
ReactDOM.render(<MyHeader />, document.getElementById('root'));
Run
Example »
Another way of adding styles to your application is to use CSS Modules.
CSS Modules are convenient for components that are placed in separate files.
The CSS inside a module is available only for the component that imported it,
and you do not have to worry about name conflicts.
Create the CSS module with the .module.css
extension, example: mystyle.module.css.
Create a new file called "mystyle.module.css" and insert some CSS code in it:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Arial;
text-align: center;
}
Import the stylesheet in your component:
import React from 'react';
import ReactDOM from 'react-dom/client';
import styles from './mystyle.module.css';
class Car extends React.Component {
render() {
return <h1 className={styles.bigblue}>Hello Car!</h1>;
}
}
export default Car;
Import the component in your application:
import React from 'react';
import ReactDOM from 'react-dom/client';
import Car from './App.js';
ReactDOM.render(<Car />, document.getElementById('root'));
Run
Example »
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:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 124,
"s": 0,
"text": "There are many ways to style React with CSS, this tutorial will \ntake a closer look at inline styling, and CSS \nstylesheet."
},
{
"code": null,
"e": 217,
"s": 124,
"text": "To style an element with the inline style attribute, the value must be a \nJavaScript object:"
},
{
"code": null,
"e": 264,
"s": 217,
"text": "Insert an object with the styling information:"
},
{
"code": null,
"e": 456,
"s": 264,
"text": "class MyHeader extends React.Component {\n render() {\n return (\n <div>\n <h1 style={{color: \"red\"}}>Hello Style!</h1>\n <p>Add a little style!</p>\n </div>\n );\n }\n}\n \n"
},
{
"code": null,
"e": 473,
"s": 456,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 677,
"s": 473,
"text": "Note: In JSX, JavaScript expressions are written inside curly braces,\nand since JavaScript objects also use curly braces,\nthe styling in the example above is written inside two sets of curly braces {{}}."
},
{
"code": null,
"e": 824,
"s": 677,
"text": "Since the inline CSS is written in a JavaScript object, properties with two names, like background-color, \nmust be written with camel case syntax:"
},
{
"code": null,
"e": 876,
"s": 824,
"text": "Use backgroundColor instead of \n background-color:"
},
{
"code": null,
"e": 1084,
"s": 876,
"text": "class MyHeader extends React.Component {\n render() {\n return (\n <div>\n <h1 style={{backgroundColor: \"lightblue\"}}>Hello Style!</h1>\n <p>Add a little style!</p>\n </div>\n );\n }\n}\n \n"
},
{
"code": null,
"e": 1101,
"s": 1084,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1197,
"s": 1101,
"text": "You can also create an object with styling information, and refer to it in the style attribute:"
},
{
"code": null,
"e": 1234,
"s": 1197,
"text": "Create a style object named mystyle:"
},
{
"code": null,
"e": 1568,
"s": 1234,
"text": "class MyHeader extends React.Component {\n render() {\n const mystyle = {\n color: \"white\",\n backgroundColor: \"DodgerBlue\",\n padding: \"10px\",\n fontFamily: \"Arial\"\n };\n return (\n <div>\n <h1 style={mystyle}>Hello Style!</h1>\n <p>Add a little style!</p>\n </div>\n );\n }\n}\n \n \n \n \n \n \n \n"
},
{
"code": null,
"e": 1585,
"s": 1568,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 1722,
"s": 1585,
"text": "You can write your CSS styling in a separate file, just save the file with the \n.css file extension, and import it in your \napplication."
},
{
"code": null,
"e": 1789,
"s": 1722,
"text": "Create a new file called \"App.css\" and insert some CSS code in it:"
},
{
"code": null,
"e": 1905,
"s": 1789,
"text": "body {\n background-color: #282c34;\n color: white;\n padding: 40px;\n font-family: Arial;\n text-align: center;\n}\n"
},
{
"code": null,
"e": 1994,
"s": 1905,
"text": "Note: You can call the file whatever you like, just remember the correct file extension."
},
{
"code": null,
"e": 2037,
"s": 1994,
"text": "Import the stylesheet in your application:"
},
{
"code": null,
"e": 2361,
"s": 2037,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './App.css';\n\nclass MyHeader extends React.Component {\n render() {\n return (\n <div>\n <h1>Hello Style!</h1>\n <p>Add a little style!.</p>\n </div>\n );\n \n}\n}\n\nReactDOM.render(<MyHeader />, document.getElementById('root'));\n"
},
{
"code": null,
"e": 2378,
"s": 2361,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 2450,
"s": 2378,
"text": "Another way of adding styles to your application is to use CSS Modules."
},
{
"code": null,
"e": 2527,
"s": 2450,
"text": "CSS Modules are convenient for components that are placed in separate files."
},
{
"code": null,
"e": 2657,
"s": 2527,
"text": "The CSS inside a module is available only for the component that imported it, \nand you do not have to worry about name conflicts."
},
{
"code": null,
"e": 2741,
"s": 2657,
"text": "Create the CSS module with the .module.css \nextension, example: mystyle.module.css."
},
{
"code": null,
"e": 2819,
"s": 2741,
"text": "Create a new file called \"mystyle.module.css\" and insert some CSS code in it:"
},
{
"code": null,
"e": 2915,
"s": 2819,
"text": ".bigblue {\n color: DodgerBlue;\n padding: 40px;\n font-family: Arial;\n text-align: center;\n}\n"
},
{
"code": null,
"e": 2956,
"s": 2915,
"text": "Import the stylesheet in your component:"
},
{
"code": null,
"e": 3209,
"s": 2956,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport styles from './mystyle.module.css'; \n\nclass Car extends React.Component {\n render() {\n return <h1 className={styles.bigblue}>Hello Car!</h1>;\n }\n}\n\nexport default Car;\n \n \n"
},
{
"code": null,
"e": 3251,
"s": 3209,
"text": "Import the component in your application:"
},
{
"code": null,
"e": 3410,
"s": 3251,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport Car from './App.js';\n\nReactDOM.render(<Car />, document.getElementById('root'));\n \n"
},
{
"code": null,
"e": 3427,
"s": 3410,
"text": "\nRun \nExample »\n"
},
{
"code": null,
"e": 3460,
"s": 3427,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3502,
"s": 3460,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3609,
"s": 3502,
"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": 3628,
"s": 3609,
"text": "help@w3schools.com"
}
] |
How to Add Outline or Edge Color to Histogram in Seaborn?
|
02 Dec, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.Seaborn aims to make visualization of the central part of exploring and understanding data. It provides dataset-oriented APIs, so that we can switch between different visual representations for the same variables for a better understanding of the dataset.
In this article, we are going to add an outline or edge color to a histogram. The task can be done using the seaborn.distplot() method.
Syntax: seaborn.distplot(aSeries)
Parameters
aSeries, 1d-array, or list: Observed data. If this is a Series object with a name attribute, the name will be used to label the data axis.
binsargument for matplotlib hist(), or None, optional: Specification of hist bins. If unspecified, as reference rule is used that tries to find a useful default.
colormatplotlib color, optional: Color to plot everything but the fitted curve in.
labelstring, optional: Legend label for the relevant component of the plot.
axmatplotlib axis, optional: If provided, plot on this axis.
Returns
axmatplotlib Axes: Returns the Axes object with the plot for further tweaking.
We are mainly going to use the hist_kws parameters of this method like edgecolor, color, linewidth, etc, as it deals with the outline and edges of the histogram, it takes a dictionary value.
Example 1:
Below is the dataset through which the histogram is to be illustrated:
Python3
# import required modulesimport seabornfrom vega_datasets import data # assign datasetdataset = data.co2_concentration() # display datasetdataset.sample(n=5)
Output:
Now illustrating a histogram and also adding an outline to it.
Python3
# depict illustrationseaborn.distplot(dataset['CO2'])
Output:
Also, illustrating a histogram and adding an edge color to it.
Python3
# depict illustrationsns.distplot(dataset['CO2'], hist_kws=dict(edgecolor="green", linewidth=5))
Output:
Example 2:
Here is another dataset through which a histogram is to be depicted:
Python3
# import required modulesimport seabornfrom vega_datasets import data # assign datasetdataset = data.la_riots() # display datasetdataset.sample(n=5)
Now below is the illustration:
Python3
# depict illustrationsns.distplot(dataset['age'], hist_kws={'color':'green', 'edgecolor':'black', 'linewidth':2, 'linestyle':'--'})
Output:
Example 3:
Here is another example to add an outline or edge color to Histogram.
Python3
# import required modulesimport seabornfrom vega_datasets import data # assign datasetdataset = data.seattle_weather() # display datasetdataset.sample(n=5) # depict illustrationsns.distplot(dataset['temp_min'], hist_kws={'color': 'black', 'edgecolor': 'green', 'linewidth': 5})
Output:
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Dec, 2020"
},
{
"code": null,
"e": 606,
"s": 52,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.Seaborn aims to make visualization of the central part of exploring and understanding data. It provides dataset-oriented APIs, so that we can switch between different visual representations for the same variables for a better understanding of the dataset."
},
{
"code": null,
"e": 742,
"s": 606,
"text": "In this article, we are going to add an outline or edge color to a histogram. The task can be done using the seaborn.distplot() method."
},
{
"code": null,
"e": 776,
"s": 742,
"text": "Syntax: seaborn.distplot(aSeries)"
},
{
"code": null,
"e": 787,
"s": 776,
"text": "Parameters"
},
{
"code": null,
"e": 926,
"s": 787,
"text": "aSeries, 1d-array, or list: Observed data. If this is a Series object with a name attribute, the name will be used to label the data axis."
},
{
"code": null,
"e": 1088,
"s": 926,
"text": "binsargument for matplotlib hist(), or None, optional: Specification of hist bins. If unspecified, as reference rule is used that tries to find a useful default."
},
{
"code": null,
"e": 1171,
"s": 1088,
"text": "colormatplotlib color, optional: Color to plot everything but the fitted curve in."
},
{
"code": null,
"e": 1247,
"s": 1171,
"text": "labelstring, optional: Legend label for the relevant component of the plot."
},
{
"code": null,
"e": 1308,
"s": 1247,
"text": "axmatplotlib axis, optional: If provided, plot on this axis."
},
{
"code": null,
"e": 1316,
"s": 1308,
"text": "Returns"
},
{
"code": null,
"e": 1395,
"s": 1316,
"text": "axmatplotlib Axes: Returns the Axes object with the plot for further tweaking."
},
{
"code": null,
"e": 1586,
"s": 1395,
"text": "We are mainly going to use the hist_kws parameters of this method like edgecolor, color, linewidth, etc, as it deals with the outline and edges of the histogram, it takes a dictionary value."
},
{
"code": null,
"e": 1597,
"s": 1586,
"text": "Example 1:"
},
{
"code": null,
"e": 1668,
"s": 1597,
"text": "Below is the dataset through which the histogram is to be illustrated:"
},
{
"code": null,
"e": 1676,
"s": 1668,
"text": "Python3"
},
{
"code": "# import required modulesimport seabornfrom vega_datasets import data # assign datasetdataset = data.co2_concentration() # display datasetdataset.sample(n=5)",
"e": 1836,
"s": 1676,
"text": null
},
{
"code": null,
"e": 1844,
"s": 1836,
"text": "Output:"
},
{
"code": null,
"e": 1907,
"s": 1844,
"text": "Now illustrating a histogram and also adding an outline to it."
},
{
"code": null,
"e": 1915,
"s": 1907,
"text": "Python3"
},
{
"code": "# depict illustrationseaborn.distplot(dataset['CO2'])",
"e": 1969,
"s": 1915,
"text": null
},
{
"code": null,
"e": 1977,
"s": 1969,
"text": "Output:"
},
{
"code": null,
"e": 2040,
"s": 1977,
"text": "Also, illustrating a histogram and adding an edge color to it."
},
{
"code": null,
"e": 2048,
"s": 2040,
"text": "Python3"
},
{
"code": "# depict illustrationsns.distplot(dataset['CO2'], hist_kws=dict(edgecolor=\"green\", linewidth=5))",
"e": 2157,
"s": 2048,
"text": null
},
{
"code": null,
"e": 2165,
"s": 2157,
"text": "Output:"
},
{
"code": null,
"e": 2176,
"s": 2165,
"text": "Example 2:"
},
{
"code": null,
"e": 2245,
"s": 2176,
"text": "Here is another dataset through which a histogram is to be depicted:"
},
{
"code": null,
"e": 2253,
"s": 2245,
"text": "Python3"
},
{
"code": "# import required modulesimport seabornfrom vega_datasets import data # assign datasetdataset = data.la_riots() # display datasetdataset.sample(n=5)",
"e": 2404,
"s": 2253,
"text": null
},
{
"code": null,
"e": 2435,
"s": 2404,
"text": "Now below is the illustration:"
},
{
"code": null,
"e": 2443,
"s": 2435,
"text": "Python3"
},
{
"code": "# depict illustrationsns.distplot(dataset['age'], hist_kws={'color':'green', 'edgecolor':'black', 'linewidth':2, 'linestyle':'--'})",
"e": 2609,
"s": 2443,
"text": null
},
{
"code": null,
"e": 2617,
"s": 2609,
"text": "Output:"
},
{
"code": null,
"e": 2628,
"s": 2617,
"text": "Example 3:"
},
{
"code": null,
"e": 2698,
"s": 2628,
"text": "Here is another example to add an outline or edge color to Histogram."
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "Python3"
},
{
"code": "# import required modulesimport seabornfrom vega_datasets import data # assign datasetdataset = data.seattle_weather() # display datasetdataset.sample(n=5) # depict illustrationsns.distplot(dataset['temp_min'], hist_kws={'color': 'black', 'edgecolor': 'green', 'linewidth': 5})",
"e": 3021,
"s": 2706,
"text": null
},
{
"code": null,
"e": 3029,
"s": 3021,
"text": "Output:"
},
{
"code": null,
"e": 3044,
"s": 3029,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 3068,
"s": 3044,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3075,
"s": 3068,
"text": "Python"
},
{
"code": null,
"e": 3094,
"s": 3075,
"text": "Technical Scripter"
}
] |
file parameter of Python’s print() Function
|
23 Oct, 2020
print() function in Python3 supports a ‘file‘ argument, which specifies where the function should write a given object(s) to. If not specified explicitly, it is sys.stdout by default.
It serves two essential purposes:
Print to STDERR
Print to external file
Note : The ‘file’ parameter is found only in Python 3.x or later. Printing to STDERR :
Specify the file parameter as sys.stderr instead of the default value. This is very useful when debugging a small program (It would be better to use a debugger in other cases).
# Code for printing to STDERRimport sys print('GeeksForGeeks', file = sys.stderr)
Output :
GeeksForGeeks
Printing to a specific file :
Instead of the default value, specify the file parameter with the name of the required file. If the file does not exist, a new file by that name is created and written to.
# Code for printing to a filesample = open('samplefile.txt', 'w') print('GeeksForGeeks', file = sample)sample.close()
Output (in “samplefile.txt”) :
GeeksForGeeks
Note : Try this in interpreter on your system, since such file can’t be accessed on Online IDE.
python-io
Python
Technical Scripter
python-io
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Oct, 2020"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "print() function in Python3 supports a ‘file‘ argument, which specifies where the function should write a given object(s) to. If not specified explicitly, it is sys.stdout by default."
},
{
"code": null,
"e": 246,
"s": 212,
"text": "It serves two essential purposes:"
},
{
"code": null,
"e": 285,
"s": 246,
"text": "Print to STDERR\nPrint to external file"
},
{
"code": null,
"e": 372,
"s": 285,
"text": "Note : The ‘file’ parameter is found only in Python 3.x or later. Printing to STDERR :"
},
{
"code": null,
"e": 549,
"s": 372,
"text": "Specify the file parameter as sys.stderr instead of the default value. This is very useful when debugging a small program (It would be better to use a debugger in other cases)."
},
{
"code": "# Code for printing to STDERRimport sys print('GeeksForGeeks', file = sys.stderr)",
"e": 632,
"s": 549,
"text": null
},
{
"code": null,
"e": 641,
"s": 632,
"text": "Output :"
},
{
"code": null,
"e": 656,
"s": 641,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 687,
"s": 656,
"text": " Printing to a specific file :"
},
{
"code": null,
"e": 859,
"s": 687,
"text": "Instead of the default value, specify the file parameter with the name of the required file. If the file does not exist, a new file by that name is created and written to."
},
{
"code": "# Code for printing to a filesample = open('samplefile.txt', 'w') print('GeeksForGeeks', file = sample)sample.close()",
"e": 978,
"s": 859,
"text": null
},
{
"code": null,
"e": 1009,
"s": 978,
"text": "Output (in “samplefile.txt”) :"
},
{
"code": null,
"e": 1024,
"s": 1009,
"text": "GeeksForGeeks\n"
},
{
"code": null,
"e": 1120,
"s": 1024,
"text": "Note : Try this in interpreter on your system, since such file can’t be accessed on Online IDE."
},
{
"code": null,
"e": 1130,
"s": 1120,
"text": "python-io"
},
{
"code": null,
"e": 1137,
"s": 1130,
"text": "Python"
},
{
"code": null,
"e": 1156,
"s": 1137,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1166,
"s": 1156,
"text": "python-io"
}
] |
Queries to print all divisors of number
|
23 Dec, 2017
Given a positive integer ‘n’ and query ‘q’. Print all the divisors of number ‘n’.
Input: 6
Output: 1 2 3 6
Explanation
Divisors of 6 are: 1, 2, 3, 6
Input: 10
Output: 1 2 5 10
Naive approach is to iterate through 1 to sqrt(n) for every query ‘q’ and print the divisors accordingly. See this to understand more. Time complexity of this approach is q*sqrt(n) which is not sufficient for large number of queries.
Efficient approach is to use factorization by using sieve base approach.
Create a list of consecutive integers from 1 to ‘n’.
For any number ‘d’, iterate through all the multiples of ‘d’ i.e., d, 2d, 3d, ... etc. Meanwhile push the divisor ‘d’ for every multiples.
// C++ program to print divisors of// number for multiple query#include <iostream>#include <vector>using namespace std; const int MAX = 1e5; // Initialize global divisor vector// array of sequence containervector<int> divisor[MAX + 1]; // Sieve based approach to pre-// calculate all divisors of numbervoid sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].push_back(i); }} // Utility function to print divisors// of given numberinline void printDivisor(int& n){ for (auto& div : divisor[n]) cout << div << " ";} // Driver codeint main(){ sieve(); int n = 10; cout << "Divisors of " << n << " = "; printDivisor(n); n = 30; cout << "\nDivisors of " << n << " = "; printDivisor(n); return 0;}
Output
Divisors of 10 = 1 2 5 10
Divisors of 30 = 1 2 3 5 6 10 15 303
Time complexity: O(len) for each query, where len is equal to total divisors of number ‘n’.Auxiliary space: O(MAX)
divisors
number-theory
Mathematical
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Dec, 2017"
},
{
"code": null,
"e": 136,
"s": 54,
"text": "Given a positive integer ‘n’ and query ‘q’. Print all the divisors of number ‘n’."
},
{
"code": null,
"e": 232,
"s": 136,
"text": "Input: 6\nOutput: 1 2 3 6\nExplanation\nDivisors of 6 are: 1, 2, 3, 6\n\nInput: 10\nOutput: 1 2 5 10\n"
},
{
"code": null,
"e": 466,
"s": 232,
"text": "Naive approach is to iterate through 1 to sqrt(n) for every query ‘q’ and print the divisors accordingly. See this to understand more. Time complexity of this approach is q*sqrt(n) which is not sufficient for large number of queries."
},
{
"code": null,
"e": 539,
"s": 466,
"text": "Efficient approach is to use factorization by using sieve base approach."
},
{
"code": null,
"e": 592,
"s": 539,
"text": "Create a list of consecutive integers from 1 to ‘n’."
},
{
"code": null,
"e": 731,
"s": 592,
"text": "For any number ‘d’, iterate through all the multiples of ‘d’ i.e., d, 2d, 3d, ... etc. Meanwhile push the divisor ‘d’ for every multiples."
},
{
"code": "// C++ program to print divisors of// number for multiple query#include <iostream>#include <vector>using namespace std; const int MAX = 1e5; // Initialize global divisor vector// array of sequence containervector<int> divisor[MAX + 1]; // Sieve based approach to pre-// calculate all divisors of numbervoid sieve(){ for (int i = 1; i <= MAX; ++i) { for (int j = i; j <= MAX; j += i) divisor[j].push_back(i); }} // Utility function to print divisors// of given numberinline void printDivisor(int& n){ for (auto& div : divisor[n]) cout << div << \" \";} // Driver codeint main(){ sieve(); int n = 10; cout << \"Divisors of \" << n << \" = \"; printDivisor(n); n = 30; cout << \"\\nDivisors of \" << n << \" = \"; printDivisor(n); return 0;}",
"e": 1526,
"s": 731,
"text": null
},
{
"code": null,
"e": 1599,
"s": 1526,
"text": "Output \nDivisors of 10 = 1 2 5 10 \nDivisors of 30 = 1 2 3 5 6 10 15 303\n"
},
{
"code": null,
"e": 1714,
"s": 1599,
"text": "Time complexity: O(len) for each query, where len is equal to total divisors of number ‘n’.Auxiliary space: O(MAX)"
},
{
"code": null,
"e": 1723,
"s": 1714,
"text": "divisors"
},
{
"code": null,
"e": 1737,
"s": 1723,
"text": "number-theory"
},
{
"code": null,
"e": 1750,
"s": 1737,
"text": "Mathematical"
},
{
"code": null,
"e": 1764,
"s": 1750,
"text": "number-theory"
},
{
"code": null,
"e": 1777,
"s": 1764,
"text": "Mathematical"
}
] |
Google Interview Experience | Set 2 (Placement Questions)
|
28 Apr, 2017
MCQ Questions: 20 (+4, -1)Subjective Question: 1
1) Given four matricesP = 20×10Q = 10×5R = 5×10S = 10×10Find minimum no. of multiplication required for PxQxRxS?a) 4000b) 2500c) 3000d) None Of These
2) Two n-size arays are given . n1 in decreasing order and n2 in increasing order. If c1 is time complexity for n1 using quicksort and c2 is time complexity for n2 using quicksort. Then –a) c1 > c2b) c1 < c2
c) c1 = c2
d) None of these
3) If there is a N sorted array then what is time complexity of finding 2 no.s having sum less than 1000.a) O(1)b) O(n^2)c) O(n)d) O(logn)
4) There are some process . In which of the scheduling algo CPU utilization is minimum. If I/O burst time is 90ms and CPU burst time is 10ms.(question is very long to remember)
5)
int func(int x, int *y, int **z)
{
int p, q;
x += 2;
p = *y++;
q = **z++;
q = **z++; //Not a repeated line.
}
void main()
{
int a = 5, *b, **c;
b = &a;
c = &b;
printf(“%d”,a);
}
6) Find the least significant digit of 2^3*google where google=10^100.a) 2b) 4c) 6d) 8
7) Let w(n) and A(n) denote respectively, the worst case and average case running time of an algorithm executed on an input of size n. which of the following is ALWAYS TRUE?a) A(n) = Omega(W(n))b) A(n) = Theta(W(n))c) A(n) = O(W(n))d) A(n) = o(W(n))
8) Consider a complete undirected graph with vertex set {0, 1, 2, 3, 4}. Entry Wij in the matrix W below is the weight of the edge {i, j}.
0 1 8 1 4
1 0 12 4 9
W = 8 12 0 7 3
1 4 7 0 2
4 9 3 2 0
What is the minimum possible weight of a spanning tree T in this graph such that vertex 0 is a leaf node in the tree T?a) 7b) 8c) 9d) 10
9) In the graph given in question 8, what is the minimum possible weight of a path P from vertex 1 to vertex 2 in this graph such that P contains at most 3 edges?a) 7b) 8c) 9d) 10
10) A hash table of length 10 uses open addressing with hash function h(k)=k mod 10, and linear probing. After inserting 6 values into an empty hash table, the table is as shown below.
|0| |
|1| |
|2| 42|
|3| 23|
|4| 34|
|5| 52|
|6| 46|
|7| 33|
|8| |
|9| |
Which one of the following choices gives a possible order in which the key values could have been inserted in the table?a) 46, 42, 34, 52, 23, 33b) 34, 42, 23, 52, 33, 46c) 46, 34, 42, 23, 52, 33d) 42, 46, 33, 23, 34, 52
11) How many different insertion sequences of the key values using the same hash function of question 10 and linear probing will result in the hash table shown above?a) 10b) 20c) 30d) 40
12) The recurrence relation capturing the optimal time of the Tower of Hanoi problem with n discs isa) T(n) = 2T(n – 2) + 2b) T(n) = 2T(n – 1) + nc) T(n) = 2T(n/2) + 1d) T(n) = 2T(n – 1) + 1
13) Given three semaphores, S0, S1 and S2 initialized as S0=1, S1=0, S2=0 and processes P0, P1 and P2.
P0 : while(true)
P0, P1 and P2.
P0 : while(true)
{
wait(S0);
printf(“ 0 “);
Release(S1);
Release(S2);
}
P1: while(true)
{
Wait(S1);
Release(S2);
}
P2: while(true)
{
Wait(S2);
Release(S0);
}
Find out how many times the process P0 executes printf statement.a) At least twiceb) Exactly oncec) Exactly twiced) Exactly thrice
14) Given the following program construct
{
if ( a == b ) { S1; exit(); }
else if ( c==d ) { S2; }
else { S3; exit(); }
S4;
}
Given 4 test cases, find out which one among the following covers all the 4 statementsT1: a, b, c and d are same.T2: a, b, c and d are all distinct.T3: a == b and c != d.T4: a != b and c==d.a) T1, T2 & T3;b) T1, T4.c) T2, T4.d) T1, T2 & T4.
15) Which of the following statements are true?I. Shortest remaining time first scheduling may cause starvationII. Preemptive scheduling may cause starvationIII. Round robin is better than FCFS in terms of response timea) I onlyb) I and III onlyc) II and III onlyd) I, II and III
16) Sequences of logical pages access :1 2 3 2 4 1 3 2 4 1Implemented Optimal,LRU,FIFO Page replacement techniques.Then no. of page faults in :a) Optimal < LRU < FIFO
b) Optimal < FIFO < LRU
c) Optimal = FIFO
d) None
17) Find the no. of page faults for Optimal Page replacement technique in the given sequence of question no. 16.a) 5b) 6c) 7d) 8
18) Given a simple graph of 6 nodes (note- it’s a simple graph) then tell which of the following is a set of valid graph degrees.a) 4,4,1,1,1,1b) 4,4,2,1,1,1c) 4,4,2,2,1,1d) None
19)
gcd(n,m)
{
if (n%m == 0)
return n;
n = n%m;
return gcd ( m, n);
}
What is the complexity of calculating gcd(n, m) in worst case?a) O(lgn)b) O(lgm)c) O(lg(lgn))d) O(lg(lgm))
20)
void f(char * x)
{
x++;
*x = 'a';
}
int main()
{
char * str = "hello";
f(str);
cout << str;
system("pause");
return 0;
}
a) hellob) halloc) allod) empty string
SECTION B – Subjective QuestionA knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square exactly once. Find all the distinct tours of a knight placed on (x,y) of a NxN chessboard.X,Y Knight can go to 8 positions.(default rule). Write a running code.
These questions are contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Google
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Apr, 2017"
},
{
"code": null,
"e": 103,
"s": 54,
"text": "MCQ Questions: 20 (+4, -1)Subjective Question: 1"
},
{
"code": null,
"e": 253,
"s": 103,
"text": "1) Given four matricesP = 20×10Q = 10×5R = 5×10S = 10×10Find minimum no. of multiplication required for PxQxRxS?a) 4000b) 2500c) 3000d) None Of These"
},
{
"code": null,
"e": 628,
"s": 253,
"text": "2) Two n-size arays are given . n1 in decreasing order and n2 in increasing order. If c1 is time complexity for n1 using quicksort and c2 is time complexity for n2 using quicksort. Then –a) c1 > c2b) c1 < c2\nc) c1 = c2\nd) None of these\n3) If there is a N sorted array then what is time complexity of finding 2 no.s having sum less than 1000.a) O(1)b) O(n^2)c) O(n)d) O(logn)"
},
{
"code": null,
"e": 805,
"s": 628,
"text": "4) There are some process . In which of the scheduling algo CPU utilization is minimum. If I/O burst time is 90ms and CPU burst time is 10ms.(question is very long to remember)"
},
{
"code": null,
"e": 808,
"s": 805,
"text": "5)"
},
{
"code": null,
"e": 1004,
"s": 808,
"text": "int func(int x, int *y, int **z)\n{\n int p, q;\n x += 2;\n p = *y++;\n q = **z++;\n q = **z++; //Not a repeated line.\n}\nvoid main()\n{\n int a = 5, *b, **c;\n b = &a;\n c = &b;\n printf(“%d”,a);\n}"
},
{
"code": null,
"e": 1091,
"s": 1004,
"text": "6) Find the least significant digit of 2^3*google where google=10^100.a) 2b) 4c) 6d) 8"
},
{
"code": null,
"e": 1341,
"s": 1091,
"text": "7) Let w(n) and A(n) denote respectively, the worst case and average case running time of an algorithm executed on an input of size n. which of the following is ALWAYS TRUE?a) A(n) = Omega(W(n))b) A(n) = Theta(W(n))c) A(n) = O(W(n))d) A(n) = o(W(n))"
},
{
"code": null,
"e": 1480,
"s": 1341,
"text": "8) Consider a complete undirected graph with vertex set {0, 1, 2, 3, 4}. Entry Wij in the matrix W below is the weight of the edge {i, j}."
},
{
"code": null,
"e": 1552,
"s": 1480,
"text": " 0 1 8 1 4\n 1 0 12 4 9\nW = 8 12 0 7 3\n 1 4 7 0 2\n 4 9 3 2 0"
},
{
"code": null,
"e": 1689,
"s": 1552,
"text": "What is the minimum possible weight of a spanning tree T in this graph such that vertex 0 is a leaf node in the tree T?a) 7b) 8c) 9d) 10"
},
{
"code": null,
"e": 1869,
"s": 1689,
"text": "9) In the graph given in question 8, what is the minimum possible weight of a path P from vertex 1 to vertex 2 in this graph such that P contains at most 3 edges?a) 7b) 8c) 9d) 10"
},
{
"code": null,
"e": 2054,
"s": 1869,
"text": "10) A hash table of length 10 uses open addressing with hash function h(k)=k mod 10, and linear probing. After inserting 6 values into an empty hash table, the table is as shown below."
},
{
"code": null,
"e": 2135,
"s": 2054,
"text": "|0| | \n|1| |\n|2| 42|\n|3| 23|\n|4| 34|\n|5| 52|\n|6| 46|\n|7| 33|\n|8| |\n|9| |"
},
{
"code": null,
"e": 2356,
"s": 2135,
"text": "Which one of the following choices gives a possible order in which the key values could have been inserted in the table?a) 46, 42, 34, 52, 23, 33b) 34, 42, 23, 52, 33, 46c) 46, 34, 42, 23, 52, 33d) 42, 46, 33, 23, 34, 52"
},
{
"code": null,
"e": 2543,
"s": 2356,
"text": "11) How many different insertion sequences of the key values using the same hash function of question 10 and linear probing will result in the hash table shown above?a) 10b) 20c) 30d) 40"
},
{
"code": null,
"e": 2734,
"s": 2543,
"text": "12) The recurrence relation capturing the optimal time of the Tower of Hanoi problem with n discs isa) T(n) = 2T(n – 2) + 2b) T(n) = 2T(n – 1) + nc) T(n) = 2T(n/2) + 1d) T(n) = 2T(n – 1) + 1"
},
{
"code": null,
"e": 2837,
"s": 2734,
"text": "13) Given three semaphores, S0, S1 and S2 initialized as S0=1, S1=0, S2=0 and processes P0, P1 and P2."
},
{
"code": null,
"e": 3044,
"s": 2837,
"text": "P0 : while(true)\nP0, P1 and P2.\nP0 : while(true)\n{\n wait(S0);\n printf(“ 0 “);\n Release(S1);\n Release(S2);\n}\nP1: while(true)\n{\n Wait(S1);\n Release(S2);\n}\nP2: while(true)\n{\n Wait(S2);\n Release(S0);\n} "
},
{
"code": null,
"e": 3175,
"s": 3044,
"text": "Find out how many times the process P0 executes printf statement.a) At least twiceb) Exactly oncec) Exactly twiced) Exactly thrice"
},
{
"code": null,
"e": 3217,
"s": 3175,
"text": "14) Given the following program construct"
},
{
"code": null,
"e": 3306,
"s": 3217,
"text": "{\n if ( a == b ) { S1; exit(); }\n else if ( c==d ) { S2; }\n else { S3; exit(); }\n S4;\n} "
},
{
"code": null,
"e": 3547,
"s": 3306,
"text": "Given 4 test cases, find out which one among the following covers all the 4 statementsT1: a, b, c and d are same.T2: a, b, c and d are all distinct.T3: a == b and c != d.T4: a != b and c==d.a) T1, T2 & T3;b) T1, T4.c) T2, T4.d) T1, T2 & T4."
},
{
"code": null,
"e": 3827,
"s": 3547,
"text": "15) Which of the following statements are true?I. Shortest remaining time first scheduling may cause starvationII. Preemptive scheduling may cause starvationIII. Round robin is better than FCFS in terms of response timea) I onlyb) I and III onlyc) II and III onlyd) I, II and III"
},
{
"code": null,
"e": 4173,
"s": 3827,
"text": "16) Sequences of logical pages access :1 2 3 2 4 1 3 2 4 1Implemented Optimal,LRU,FIFO Page replacement techniques.Then no. of page faults in :a) Optimal < LRU < FIFO\nb) Optimal < FIFO < LRU\nc) Optimal = FIFO\nd) None\n17) Find the no. of page faults for Optimal Page replacement technique in the given sequence of question no. 16.a) 5b) 6c) 7d) 8"
},
{
"code": null,
"e": 4352,
"s": 4173,
"text": "18) Given a simple graph of 6 nodes (note- it’s a simple graph) then tell which of the following is a set of valid graph degrees.a) 4,4,1,1,1,1b) 4,4,2,1,1,1c) 4,4,2,2,1,1d) None"
},
{
"code": null,
"e": 4356,
"s": 4352,
"text": "19)"
},
{
"code": null,
"e": 4433,
"s": 4356,
"text": "gcd(n,m)\n{\n if (n%m == 0)\n return n;\n n = n%m;\n return gcd ( m, n);\n} "
},
{
"code": null,
"e": 4540,
"s": 4433,
"text": "What is the complexity of calculating gcd(n, m) in worst case?a) O(lgn)b) O(lgm)c) O(lg(lgn))d) O(lg(lgm))"
},
{
"code": null,
"e": 4544,
"s": 4540,
"text": "20)"
},
{
"code": null,
"e": 4680,
"s": 4544,
"text": "void f(char * x)\n{\n x++;\n *x = 'a';\n}\nint main()\n{\n char * str = \"hello\";\n f(str);\n cout << str;\n system(\"pause\");\n return 0;\n} "
},
{
"code": null,
"e": 4719,
"s": 4680,
"text": "a) hellob) halloc) allod) empty string"
},
{
"code": null,
"e": 5019,
"s": 4719,
"text": "SECTION B – Subjective QuestionA knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square exactly once. Find all the distinct tours of a knight placed on (x,y) of a NxN chessboard.X,Y Knight can go to 8 positions.(default rule). Write a running code."
},
{
"code": null,
"e": 5290,
"s": 5019,
"text": "These questions are contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5297,
"s": 5290,
"text": "Google"
},
{
"code": null,
"e": 5319,
"s": 5297,
"text": "Interview Experiences"
},
{
"code": null,
"e": 5326,
"s": 5319,
"text": "Google"
}
] |
Extracting each word from a String using Regex in Java
|
11 Dec, 2018
Given a string, extract words from it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z.
Examples:
Input : Funny?? are not you?
Output : Funny
are
not
you
Input : Geeks for geeks??
Output : Geeks
for
geeks
We have discussed a solution for C++ in this post : Program to extract words from a given String
We have also discussed basic approach for java in these posts : Counting number of lines, words, characters and paragraphs in a text file using Java and Print first letter in word using Regex.
In this post, we will discuss Regular Expression approach for doing the same. This approach is best in terms of Time Complexity and is also used for large input files. Below is the regular expression for any word.
[a-zA-Z]+
// Java program to demonstrate extracting words// from string using Regex import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s1 = "Geeks for Geeks"; String s2 = "A Computer Science Portal for Geeks"; Pattern p = Pattern.compile("[a-zA-Z]+"); Matcher m1 = p.matcher(s1); Matcher m2 = p.matcher(s2); System.out.println("Words from string \"" + s1 + "\" : "); while (m1.find()) { System.out.println(m1.group()); } System.out.println("Words from string \"" + s2 + "\" : "); while (m2.find()) { System.out.println(m2.group()); } }}
Output:
Words from string "Geeks for Geeks" :
Geeks
for
Geeks
Words from string "A Computer Science Portal for Geeks" :
A
Computer
Science
Portal
for
Geeks
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
java-regular-expression
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "Given a string, extract words from it. “Words” are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z."
},
{
"code": null,
"e": 196,
"s": 186,
"text": "Examples:"
},
{
"code": null,
"e": 351,
"s": 196,
"text": "Input : Funny?? are not you?\nOutput : Funny\n are\n not\n you\n\nInput : Geeks for geeks?? \nOutput : Geeks\n for\n geeks\n"
},
{
"code": null,
"e": 448,
"s": 351,
"text": "We have discussed a solution for C++ in this post : Program to extract words from a given String"
},
{
"code": null,
"e": 641,
"s": 448,
"text": "We have also discussed basic approach for java in these posts : Counting number of lines, words, characters and paragraphs in a text file using Java and Print first letter in word using Regex."
},
{
"code": null,
"e": 855,
"s": 641,
"text": "In this post, we will discuss Regular Expression approach for doing the same. This approach is best in terms of Time Complexity and is also used for large input files. Below is the regular expression for any word."
},
{
"code": null,
"e": 866,
"s": 855,
"text": "[a-zA-Z]+\n"
},
{
"code": "// Java program to demonstrate extracting words// from string using Regex import java.util.regex.Matcher;import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s1 = \"Geeks for Geeks\"; String s2 = \"A Computer Science Portal for Geeks\"; Pattern p = Pattern.compile(\"[a-zA-Z]+\"); Matcher m1 = p.matcher(s1); Matcher m2 = p.matcher(s2); System.out.println(\"Words from string \\\"\" + s1 + \"\\\" : \"); while (m1.find()) { System.out.println(m1.group()); } System.out.println(\"Words from string \\\"\" + s2 + \"\\\" : \"); while (m2.find()) { System.out.println(m2.group()); } }}",
"e": 1634,
"s": 866,
"text": null
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Output:"
},
{
"code": null,
"e": 1793,
"s": 1642,
"text": "Words from string \"Geeks for Geeks\" : \nGeeks\nfor\nGeeks\nWords from string \"A Computer Science Portal for Geeks\" : \nA\nComputer\nScience\nPortal\nfor\nGeeks\n"
},
{
"code": null,
"e": 2095,
"s": 1793,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2220,
"s": 2095,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2244,
"s": 2220,
"text": "java-regular-expression"
},
{
"code": null,
"e": 2265,
"s": 2244,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2278,
"s": 2265,
"text": "Java-Strings"
},
{
"code": null,
"e": 2283,
"s": 2278,
"text": "Java"
},
{
"code": null,
"e": 2296,
"s": 2283,
"text": "Java-Strings"
},
{
"code": null,
"e": 2301,
"s": 2296,
"text": "Java"
}
] |
Programmatically Check the Network Speed in Android
|
17 Oct, 2020
Network speed can be defined as the total number of packets being exchanged by the client and the server per second, usually calculated in Megabits per second(Mbps). A bit is either a 0 or 1. 1 Megabit implies 1 Million bits. Usually, packet size depends on the protocol and various other factors and usually ranges on a vast scale. In this article, a program is implemented that fetches us Upload and Download speeds with the server. Note that the program is successful when the device is connected to a network.
This program could be used for research as well as for optimization:
Research: one could derive the content and the available speeds to correlate the network dependency.
Optimization: one could continuously monitor the speed and context, to avoid the connection when not required or reduce the quality of a video being broadcasted depending upon the current speeds.
Approach:
Step 1: Create an Empty activity in Android Studio. To create one, follow this article- https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Check if the primary language selected is Kotlin.
Step 2: Go to the AndroidManifest.xml file and add the uses-permission ACCESS_NETWORK_STATE.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.geeksforgeeks.networkspeed"> <!--Add this permission--> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!-----------------------> <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>
Step 3: In the activity_main.xml, add a button. Bellow is the code for the same.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Create a Button--> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show Speed" android:layout_centerInParent="true" /> </RelativeLayout>
Step 4: In the MainActivity.kt, add the below code. setOnClickListener is added with the button, which when clicked shows the upload speed and download speed as a toast on the screen.
Kotlin
package org.geeksforgeeks.networkspeed import android.content.Contextimport android.net.ConnectivityManagerimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.annotation.RequiresApi class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring Button from the layout file val btn = findViewById<Button>(R.id.btn) // Action when the button id clicked btn.setOnClickListener { // Connectivity Manager val cm = applicationContext.getSystemService (Context.CONNECTIVITY_SERVICE) as ConnectivityManager // Network Capabilities of Active Network val nc = cm.getNetworkCapabilities(cm.activeNetwork) // DownSpeed in MBPS val downSpeed = (nc.linkDownstreamBandwidthKbps)/1000 // UpSpeed in MBPS val upSpeed = (nc.linkUpstreamBandwidthKbps)/1000 // Toast to Display DownSpeed and UpSpeed Toast.makeText(applicationContext, "Up Speed: $upSpeed Mbps \nDown Speed: $downSpeed Mbps", Toast.LENGTH_LONG).show() } }}
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Oct, 2020"
},
{
"code": null,
"e": 542,
"s": 28,
"text": "Network speed can be defined as the total number of packets being exchanged by the client and the server per second, usually calculated in Megabits per second(Mbps). A bit is either a 0 or 1. 1 Megabit implies 1 Million bits. Usually, packet size depends on the protocol and various other factors and usually ranges on a vast scale. In this article, a program is implemented that fetches us Upload and Download speeds with the server. Note that the program is successful when the device is connected to a network."
},
{
"code": null,
"e": 611,
"s": 542,
"text": "This program could be used for research as well as for optimization:"
},
{
"code": null,
"e": 712,
"s": 611,
"text": "Research: one could derive the content and the available speeds to correlate the network dependency."
},
{
"code": null,
"e": 908,
"s": 712,
"text": "Optimization: one could continuously monitor the speed and context, to avoid the connection when not required or reduce the quality of a video being broadcasted depending upon the current speeds."
},
{
"code": null,
"e": 918,
"s": 908,
"text": "Approach:"
},
{
"code": null,
"e": 1148,
"s": 918,
"text": "Step 1: Create an Empty activity in Android Studio. To create one, follow this article- https://www.geeksforgeeks.org/android-how-to-create-start-a-new-project-in-android-studio/. Check if the primary language selected is Kotlin."
},
{
"code": null,
"e": 1241,
"s": 1148,
"text": "Step 2: Go to the AndroidManifest.xml file and add the uses-permission ACCESS_NETWORK_STATE."
},
{
"code": null,
"e": 1245,
"s": 1241,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"org.geeksforgeeks.networkspeed\"> <!--Add this permission--> <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /> <!-----------------------> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 2092,
"s": 1245,
"text": null
},
{
"code": null,
"e": 2173,
"s": 2092,
"text": "Step 3: In the activity_main.xml, add a button. Bellow is the code for the same."
},
{
"code": null,
"e": 2177,
"s": 2173,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Create a Button--> <Button android:id=\"@+id/btn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Show Speed\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 2769,
"s": 2177,
"text": null
},
{
"code": null,
"e": 2953,
"s": 2769,
"text": "Step 4: In the MainActivity.kt, add the below code. setOnClickListener is added with the button, which when clicked shows the upload speed and download speed as a toast on the screen."
},
{
"code": null,
"e": 2960,
"s": 2953,
"text": "Kotlin"
},
{
"code": "package org.geeksforgeeks.networkspeed import android.content.Contextimport android.net.ConnectivityManagerimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toastimport androidx.annotation.RequiresApi class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.M) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring Button from the layout file val btn = findViewById<Button>(R.id.btn) // Action when the button id clicked btn.setOnClickListener { // Connectivity Manager val cm = applicationContext.getSystemService (Context.CONNECTIVITY_SERVICE) as ConnectivityManager // Network Capabilities of Active Network val nc = cm.getNetworkCapabilities(cm.activeNetwork) // DownSpeed in MBPS val downSpeed = (nc.linkDownstreamBandwidthKbps)/1000 // UpSpeed in MBPS val upSpeed = (nc.linkUpstreamBandwidthKbps)/1000 // Toast to Display DownSpeed and UpSpeed Toast.makeText(applicationContext, \"Up Speed: $upSpeed Mbps \\nDown Speed: $downSpeed Mbps\", Toast.LENGTH_LONG).show() } }}",
"e": 4378,
"s": 2960,
"text": null
},
{
"code": null,
"e": 4386,
"s": 4378,
"text": "Android"
},
{
"code": null,
"e": 4393,
"s": 4386,
"text": "Kotlin"
},
{
"code": null,
"e": 4401,
"s": 4393,
"text": "Android"
}
] |
Python winsound module
|
01 Jul, 2022
Maybe you have just begun coding in Python. Maybe the entire outset seems inconclusive since you have been working with regular IDEs and would like to obtain a bit more out of what your code does on the respective console and maybe a little music or tune might just liven it up. This article serves the purpose of introducing to you the winsound module, an object or file with a set of attributes or functions, specific to the task of generating or playing sound or a sound file. Note: The winsound module is defined only for execution on a Windows Platform, hence the name WINsound. Since, the winsound module is a builtin, there is no need for you to install it prior to executing it. The basic action would be to
import winsound
and then based upon the kind of output you would like, type out the following functions:
winsound.Beep( ) The functionality devoted to this method is to generate a ‘Beep’ sound. However, the user is required to input the frequency value and the duration of the sound (these are parameters that shall be passed while calling the function). Note: The frequency must be in the range 37 through 32,767 hertz.
Python3
import winsound # frequency is set to 500Hzfreq = 500 # duration is set to 100 milliseconds dur = 100 winsound.Beep(freq, dur)
Output:
Windows system will produce a ‘Beep’ sound with the given frequency for the given duration of time.
Building further on the code above, things can be taken to another level by implementing a ‘for’ loop to increment the frequency and duration. This has been done in the code below:
Python3
import winsound freq = 100dur = 50 # loop iterates 5 times i.e, 5 beeps will be produced.for i in range(0, 5): winsound.Beep(freq, dur) freq+= 100 dur+= 50
Output:
Consecutive notes with frequency differences of 100Hz and time duration 50 milliseconds greaterthan the previous time duration are produced.
winsound.PlaySound( ) With the PlaySound function, things can get slightly advanced, not to mention interesting. Keep in mind that this function is only compatible with .wav files. Two parameters are passed in the function: ‘filename’ and the flag – winsound.SND_FILENAME, which is required for the Platform API to refer to the output file. The flags are as defined below:
Example:
Python3
import winsound print("Playing the file 'Welcome.wav'") # winsound.PlaySound('filename', flag)winsound.PlaySound('Welcome.wav', winsound.SND_FILENAME)
Output:
The respective audio file named 'Welcome.wav' is executed.
SND_ALIAS The sound parameter should be interpreted as a control panel sound association name. The Windows registry keys are associated with sound names. If the registry contains no such name, play the system default sound unless SND_NODEFAULT. All Win32 systems support the following:
Example:
Python3
import winsound # Play Windows question soundwinsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
Output:
Play Windows question sound
There are various other winsound functions, most of which are particular to specific tasks, some of which deal with runtime parameters. Nonetheless, the functions mentioned above should suffice as long as the idea is to play around to get an idea of what can be accomplished using this module.
simmytarika5
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 770,
"s": 54,
"text": "Maybe you have just begun coding in Python. Maybe the entire outset seems inconclusive since you have been working with regular IDEs and would like to obtain a bit more out of what your code does on the respective console and maybe a little music or tune might just liven it up. This article serves the purpose of introducing to you the winsound module, an object or file with a set of attributes or functions, specific to the task of generating or playing sound or a sound file. Note: The winsound module is defined only for execution on a Windows Platform, hence the name WINsound. Since, the winsound module is a builtin, there is no need for you to install it prior to executing it. The basic action would be to"
},
{
"code": null,
"e": 786,
"s": 770,
"text": "import winsound"
},
{
"code": null,
"e": 875,
"s": 786,
"text": "and then based upon the kind of output you would like, type out the following functions:"
},
{
"code": null,
"e": 1192,
"s": 875,
"text": "winsound.Beep( ) The functionality devoted to this method is to generate a ‘Beep’ sound. However, the user is required to input the frequency value and the duration of the sound (these are parameters that shall be passed while calling the function). Note: The frequency must be in the range 37 through 32,767 hertz. "
},
{
"code": null,
"e": 1200,
"s": 1192,
"text": "Python3"
},
{
"code": "import winsound # frequency is set to 500Hzfreq = 500 # duration is set to 100 milliseconds dur = 100 winsound.Beep(freq, dur)",
"e": 1351,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1359,
"s": 1351,
"text": "Output:"
},
{
"code": null,
"e": 1459,
"s": 1359,
"text": "Windows system will produce a ‘Beep’ sound with the given frequency for the given duration of time."
},
{
"code": null,
"e": 1641,
"s": 1459,
"text": "Building further on the code above, things can be taken to another level by implementing a ‘for’ loop to increment the frequency and duration. This has been done in the code below: "
},
{
"code": null,
"e": 1649,
"s": 1641,
"text": "Python3"
},
{
"code": "import winsound freq = 100dur = 50 # loop iterates 5 times i.e, 5 beeps will be produced.for i in range(0, 5): winsound.Beep(freq, dur) freq+= 100 dur+= 50",
"e": 1820,
"s": 1649,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1820,
"text": "Output: "
},
{
"code": null,
"e": 1971,
"s": 1829,
"text": "Consecutive notes with frequency differences of 100Hz and time duration 50 milliseconds greaterthan the previous time duration are produced."
},
{
"code": null,
"e": 2344,
"s": 1971,
"text": "winsound.PlaySound( ) With the PlaySound function, things can get slightly advanced, not to mention interesting. Keep in mind that this function is only compatible with .wav files. Two parameters are passed in the function: ‘filename’ and the flag – winsound.SND_FILENAME, which is required for the Platform API to refer to the output file. The flags are as defined below:"
},
{
"code": null,
"e": 2354,
"s": 2344,
"text": "Example: "
},
{
"code": null,
"e": 2362,
"s": 2354,
"text": "Python3"
},
{
"code": "import winsound print(\"Playing the file 'Welcome.wav'\") # winsound.PlaySound('filename', flag)winsound.PlaySound('Welcome.wav', winsound.SND_FILENAME) ",
"e": 2519,
"s": 2362,
"text": null
},
{
"code": null,
"e": 2527,
"s": 2519,
"text": "Output:"
},
{
"code": null,
"e": 2586,
"s": 2527,
"text": "The respective audio file named 'Welcome.wav' is executed."
},
{
"code": null,
"e": 2872,
"s": 2586,
"text": "SND_ALIAS The sound parameter should be interpreted as a control panel sound association name. The Windows registry keys are associated with sound names. If the registry contains no such name, play the system default sound unless SND_NODEFAULT. All Win32 systems support the following:"
},
{
"code": null,
"e": 2882,
"s": 2872,
"text": "Example: "
},
{
"code": null,
"e": 2890,
"s": 2882,
"text": "Python3"
},
{
"code": "import winsound # Play Windows question soundwinsound.PlaySound(\"SystemQuestion\", winsound.SND_ALIAS)",
"e": 2993,
"s": 2890,
"text": null
},
{
"code": null,
"e": 3001,
"s": 2993,
"text": "Output:"
},
{
"code": null,
"e": 3029,
"s": 3001,
"text": "Play Windows question sound"
},
{
"code": null,
"e": 3323,
"s": 3029,
"text": "There are various other winsound functions, most of which are particular to specific tasks, some of which deal with runtime parameters. Nonetheless, the functions mentioned above should suffice as long as the idea is to play around to get an idea of what can be accomplished using this module."
},
{
"code": null,
"e": 3336,
"s": 3323,
"text": "simmytarika5"
},
{
"code": null,
"e": 3351,
"s": 3336,
"text": "python-utility"
},
{
"code": null,
"e": 3358,
"s": 3351,
"text": "Python"
}
] |
Node.js split() function
|
14 Oct, 2021
The split() function is a string function of Node.js which is used to split string into sub-strings. This function returns the output in array form.Syntax:
string.split( separator )
Parameters: This function accepts single parameter separator which holds the character to split the string.Return Value: The function returns the splitted string and generates array as result.Below programs demonstrate the working of split() function:Program 1:
javascript
function splitStr(str) { // Function to split string var string = str.split("*"); console.log(string);} // Initialize stringvar str = "Welcome*to*GeeksforGeeks"; // Function callsplitStr(str);
Output:
[ 'Welcome', 'to', 'GeeksforGeeks' ]
Program 2:
javascript
function splitStr(str, separator) { // Function to split string var string = str.split(separator); console.log(string);} // Initialize stringvar str = "GeeksforGeeks/A/computer/science/portal"; var separator = "/"; // Function callsplitStr(str, separator);
Output:
[ 'GeeksforGeeks', 'A', 'computer', 'science', 'portal' ]
anikakapoor
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Oct, 2021"
},
{
"code": null,
"e": 211,
"s": 53,
"text": "The split() function is a string function of Node.js which is used to split string into sub-strings. This function returns the output in array form.Syntax: "
},
{
"code": null,
"e": 237,
"s": 211,
"text": "string.split( separator )"
},
{
"code": null,
"e": 501,
"s": 237,
"text": "Parameters: This function accepts single parameter separator which holds the character to split the string.Return Value: The function returns the splitted string and generates array as result.Below programs demonstrate the working of split() function:Program 1: "
},
{
"code": null,
"e": 512,
"s": 501,
"text": "javascript"
},
{
"code": "function splitStr(str) { // Function to split string var string = str.split(\"*\"); console.log(string);} // Initialize stringvar str = \"Welcome*to*GeeksforGeeks\"; // Function callsplitStr(str); ",
"e": 732,
"s": 512,
"text": null
},
{
"code": null,
"e": 742,
"s": 732,
"text": "Output: "
},
{
"code": null,
"e": 779,
"s": 742,
"text": "[ 'Welcome', 'to', 'GeeksforGeeks' ]"
},
{
"code": null,
"e": 792,
"s": 779,
"text": "Program 2: "
},
{
"code": null,
"e": 803,
"s": 792,
"text": "javascript"
},
{
"code": "function splitStr(str, separator) { // Function to split string var string = str.split(separator); console.log(string);} // Initialize stringvar str = \"GeeksforGeeks/A/computer/science/portal\"; var separator = \"/\"; // Function callsplitStr(str, separator);",
"e": 1084,
"s": 803,
"text": null
},
{
"code": null,
"e": 1094,
"s": 1084,
"text": "Output: "
},
{
"code": null,
"e": 1152,
"s": 1094,
"text": "[ 'GeeksforGeeks', 'A', 'computer', 'science', 'portal' ]"
},
{
"code": null,
"e": 1166,
"s": 1154,
"text": "anikakapoor"
},
{
"code": null,
"e": 1182,
"s": 1166,
"text": "NodeJS-function"
},
{
"code": null,
"e": 1190,
"s": 1182,
"text": "Node.js"
},
{
"code": null,
"e": 1207,
"s": 1190,
"text": "Web Technologies"
}
] |
Database Design(Normal Forms) - GeeksforGeeks
|
09 Oct, 2019
BCNF is a stronger version 3NF. So every relation in BCNF will also be in 3NF.
1. Registration_Num: Unique registration number
of each registered student
2. UID: Unique identity number, unique at the
national level for each citizen
3. BankAccount_Num: Unique account number at
the bank. A student can have multiple accounts
or join accounts. This attribute stores the
primary account number.
4. Name: Name of the student
5. Hostel_Room: Room number of the hostel
Suppliers(sid:integer, sname:string, city:string, street:string)
Parts(pid:integer, pname:string, color:string)
Catalog(sid:integer, pid:integer, cost:real)
X → Y is a trivial functional dependency (Y ⊆ X)
X is a superkey for schema R
I. Title Author --> Catalog_no
II. Catalog_no --> Title, Author, Publisher, Year
III. Publisher Title Year --> Price
Book (Title, Author, Catalog_no, Publisher, Year, Price)
Collection (Title, Author, Catalog_no)
I. Title, Author --> Catalog_no
II. Catalog_no --> Title, Author, Publisher, Year
III. Publisher, Title, Year --> Price
Assume {Author, Title} is the key for both schemes
The table "Collection" is in BCNF as there is only one functional dependency “Title Author –> Catalog_no” and {Author, Title} is key for collection.
Book is not in BCNF because Catalog_no is not a key and there is a functional dependency “Catalog_no –> Title Author Publisher Year”.
Book is not in 3NF because non-prime attributes (Publisher Year) are transitively dependent on key [Title, Author].
Book is in 2NF because every non-prime attribute of the table is either dependent on the whole of a candidate key [Title, Author], or on another non prime attribute.
In table book, candidate keys are {Title, Author} and {Catalog_no}. In table Book, non-prime attributes (attributes that do not occur in any candidate key) are Publisher, Year and Prince
A) {EF}+ = {EFGIJ} ≠ R(The given relation)
B) {EFH}+ = {EFGHIJKLMN} = R (Correct since each member of the
given relation is determined)
C) {EFHKL}+ = {EFGHIJKLMN} = R (Not correct although each member
of the given relation can be determined
but it is not minimal, since by the definition
of Candidate key it should be minimal Super Key)
D) {E}+ = {E} ≠ R
Since, {EFGHIJKLMN}+ = {EFGHIJKLMN}
{EFGHIJKLM}+ = {EFGHIJKLMN} ( Since L -> {N}, hence can replace N by L)
In a similar way K -> {M} hence replace M by K
{EFGHIJKL}+ = {EFGHIJKLMN}
Again {EFGHIJ}+ = {EFGHIJKLMN} (Since {E, H} -> {K, L}, hence replace KL by EH)
{EFGH}+ = {EFGHIJKLMN} (Since {F} -> {I, J} )
{EFH}+ = {EFGHIJKLMN} (Since {E, F} -> {G} )
S1: Every table with two single-valued
attributes is in 1NF, 2NF, 3NF and BCNF.
S2: AB->C, D->E, E->C is a minimal cover for
the set of functional dependencies
AB->C, D->E, AB->E, E->C.
S1: Every table with two single-valued
attributes is in 1NF, 2NF, 3NF and BCNF.
If {A->B} exists then BCNF since {A}+ = AB = RIf {B->A} exists then BCNF since {B}+ = AB = RIf {A->B,B->A} exists then BCNF since A and B both are Super Key now.If {No non trivial Functional Dependency} then default BCNF.
If {A->B} exists then BCNF since {A}+ = AB = R
If {B->A} exists then BCNF since {B}+ = AB = R
If {A->B,B->A} exists then BCNF since A and B both are Super Key now.
If {No non trivial Functional Dependency} then default BCNF.
S2: AB->C, D->E, E->C is a minimal cover for
the set of functional dependencies
AB->C, D->E, AB->E, E->C.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
50 Common Ports You Should Know
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
How to Find Length of String in Bash Script?
Top 10 Programming Languages to Learn in 2022
Spring Boot - Thymeleaf with Example
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
Converting an image to a Torch Tensor in Python
|
[
{
"code": null,
"e": 31564,
"s": 31536,
"text": "\n09 Oct, 2019"
},
{
"code": null,
"e": 31643,
"s": 31564,
"text": "BCNF is a stronger version 3NF. So every relation in BCNF will also be in 3NF."
},
{
"code": null,
"e": 32045,
"s": 31643,
"text": "1. Registration_Num: Unique registration number\n of each registered student\n2. UID: Unique identity number, unique at the \n national level for each citizen\n3. BankAccount_Num: Unique account number at\n the bank. A student can have multiple accounts\n or join accounts. This attribute stores the \n primary account number.\n4. Name: Name of the student\n5. Hostel_Room: Room number of the hostel "
},
{
"code": null,
"e": 32202,
"s": 32045,
"text": "Suppliers(sid:integer, sname:string, city:string, street:string)\nParts(pid:integer, pname:string, color:string)\nCatalog(sid:integer, pid:integer, cost:real)"
},
{
"code": null,
"e": 32289,
"s": 32202,
"text": " X → Y is a trivial functional dependency (Y ⊆ X)\n X is a superkey for schema R "
},
{
"code": null,
"e": 32407,
"s": 32289,
"text": "I. Title Author --> Catalog_no\nII. Catalog_no --> Title, Author, Publisher, Year\nIII. Publisher Title Year --> Price "
},
{
"code": null,
"e": 32504,
"s": 32407,
"text": "Book (Title, Author, Catalog_no, Publisher, Year, Price)\nCollection (Title, Author, Catalog_no) "
},
{
"code": null,
"e": 32679,
"s": 32504,
"text": "I. Title, Author --> Catalog_no\nII. Catalog_no --> Title, Author, Publisher, Year\nIII. Publisher, Title, Year --> Price \n\nAssume {Author, Title} is the key for both schemes "
},
{
"code": null,
"e": 32828,
"s": 32679,
"text": "The table \"Collection\" is in BCNF as there is only one functional dependency “Title Author –> Catalog_no” and {Author, Title} is key for collection."
},
{
"code": null,
"e": 32962,
"s": 32828,
"text": "Book is not in BCNF because Catalog_no is not a key and there is a functional dependency “Catalog_no –> Title Author Publisher Year”."
},
{
"code": null,
"e": 33078,
"s": 32962,
"text": "Book is not in 3NF because non-prime attributes (Publisher Year) are transitively dependent on key [Title, Author]."
},
{
"code": null,
"e": 33431,
"s": 33078,
"text": "Book is in 2NF because every non-prime attribute of the table is either dependent on the whole of a candidate key [Title, Author], or on another non prime attribute.\nIn table book, candidate keys are {Title, Author} and {Catalog_no}. In table Book, non-prime attributes (attributes that do not occur in any candidate key) are Publisher, Year and Prince"
},
{
"code": null,
"e": 33930,
"s": 33431,
"text": "\nA) {EF}+ = {EFGIJ} ≠ R(The given relation)\n\nB) {EFH}+ = {EFGHIJKLMN} = R (Correct since each member of the \n given relation is determined)\n\nC) {EFHKL}+ = {EFGHIJKLMN} = R (Not correct although each member \n of the given relation can be determined \n but it is not minimal, since by the definition\n of Candidate key it should be minimal Super Key)\n\n D) {E}+ = {E} ≠ R\n\n"
},
{
"code": null,
"e": 34299,
"s": 33930,
"text": "Since, {EFGHIJKLMN}+ = {EFGHIJKLMN}\n\n{EFGHIJKLM}+ = {EFGHIJKLMN} ( Since L -> {N}, hence can replace N by L)\n\nIn a similar way K -> {M} hence replace M by K\n\n{EFGHIJKL}+ = {EFGHIJKLMN} \n\nAgain {EFGHIJ}+ = {EFGHIJKLMN} (Since {E, H} -> {K, L}, hence replace KL by EH)\n\n{EFGH}+ = {EFGHIJKLMN} (Since {F} -> {I, J} )\n\n{EFH}+ = {EFGHIJKLMN} (Since {E, F} -> {G} )\n\n"
},
{
"code": null,
"e": 34512,
"s": 34299,
"text": " S1: Every table with two single-valued \n attributes is in 1NF, 2NF, 3NF and BCNF.\n\n S2: AB->C, D->E, E->C is a minimal cover for \n the set of functional dependencies \n AB->C, D->E, AB->E, E->C. "
},
{
"code": null,
"e": 34602,
"s": 34512,
"text": " \nS1: Every table with two single-valued \n attributes is in 1NF, 2NF, 3NF and BCNF.\n"
},
{
"code": null,
"e": 34824,
"s": 34602,
"text": "If {A->B} exists then BCNF since {A}+ = AB = RIf {B->A} exists then BCNF since {B}+ = AB = RIf {A->B,B->A} exists then BCNF since A and B both are Super Key now.If {No non trivial Functional Dependency} then default BCNF."
},
{
"code": null,
"e": 34871,
"s": 34824,
"text": "If {A->B} exists then BCNF since {A}+ = AB = R"
},
{
"code": null,
"e": 34918,
"s": 34871,
"text": "If {B->A} exists then BCNF since {B}+ = AB = R"
},
{
"code": null,
"e": 34988,
"s": 34918,
"text": "If {A->B,B->A} exists then BCNF since A and B both are Super Key now."
},
{
"code": null,
"e": 35049,
"s": 34988,
"text": "If {No non trivial Functional Dependency} then default BCNF."
},
{
"code": null,
"e": 35170,
"s": 35049,
"text": "S2: AB->C, D->E, E->C is a minimal cover for \n the set of functional dependencies \n AB->C, D->E, AB->E, E->C.\n"
},
{
"code": null,
"e": 35268,
"s": 35170,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 35342,
"s": 35268,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 35395,
"s": 35342,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 35427,
"s": 35395,
"text": "50 Common Ports You Should Know"
},
{
"code": null,
"e": 35493,
"s": 35427,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 35538,
"s": 35493,
"text": "How to Find Length of String in Bash Script?"
},
{
"code": null,
"e": 35584,
"s": 35538,
"text": "Top 10 Programming Languages to Learn in 2022"
},
{
"code": null,
"e": 35621,
"s": 35584,
"text": "Spring Boot - Thymeleaf with Example"
},
{
"code": null,
"e": 35646,
"s": 35621,
"text": "Naming Convention in C++"
},
{
"code": null,
"e": 35678,
"s": 35646,
"text": "Floyd’s Cycle Finding Algorithm"
}
] |
Jagged Array or Array of Arrays in C with Examples
|
14 Feb, 2020
Prerequisite: Arrays in C
Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays.
Example:
arr[][] = { {0, 1, 2},
{6, 4},
{1, 7, 6, 8, 9},
{5}
};
Below are the methods to implement the jagged array in C:
Using array and a pointer (Static Jagged Array)First declare 1-D arrays with the number of rows you will need,The size of each array (array for the elements in the row) will be the number of columns (or elements) in the row,Then declare a 1-D array of pointers that will hold the addresses of the rows,The size of the 1-D array is the number of rows you want in the jagged array.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ int row0[4] = { 1, 2, 3, 4 }; int row1[2] = { 5, 6 }; int* jagged[2] = { row0, row1 }; // Array to hold the size of each row int Size[2] = { 4, 2 }, k = 0; // To display elements of Jagged array for (int i = 0; i < 2; i++) { // pointer to hold the address of the row int* ptr = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf("%d ", *ptr); // move the pointer to the // next element in the row ptr++; } printf("\n"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:1 2 3 4
5 6
Using an array of pointer (Dynamic Jagged Array)Declare an array of pointers (jagged array),The size of this array will be the number of rows required in the Jagged arrayThen for each pointer in the array allocate memory for the number of elements you want in this row.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ // 2 Rows int* jagged[2]; // Allocate memory for elements in row 0 jagged[0] = malloc(sizeof(int) * 1); // Allocate memory for elements in row 1 jagged[1] = malloc(sizeof(int) * 3); // Array to hold the size of each row int Size[2] = { 1, 3 }, k = 0, number = 100; // User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; // move the pointer p++; } k++; } k = 0; // Display elements in Jagged array for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf("%d ", *p); // move the pointer to the next element p++; } printf("\n"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:100
101 102 103
Using array and a pointer (Static Jagged Array)First declare 1-D arrays with the number of rows you will need,The size of each array (array for the elements in the row) will be the number of columns (or elements) in the row,Then declare a 1-D array of pointers that will hold the addresses of the rows,The size of the 1-D array is the number of rows you want in the jagged array.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ int row0[4] = { 1, 2, 3, 4 }; int row1[2] = { 5, 6 }; int* jagged[2] = { row0, row1 }; // Array to hold the size of each row int Size[2] = { 4, 2 }, k = 0; // To display elements of Jagged array for (int i = 0; i < 2; i++) { // pointer to hold the address of the row int* ptr = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf("%d ", *ptr); // move the pointer to the // next element in the row ptr++; } printf("\n"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:1 2 3 4
5 6
First declare 1-D arrays with the number of rows you will need,
The size of each array (array for the elements in the row) will be the number of columns (or elements) in the row,
Then declare a 1-D array of pointers that will hold the addresses of the rows,
The size of the 1-D array is the number of rows you want in the jagged array.
Below is the implementation of the above approach:Example:
// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ int row0[4] = { 1, 2, 3, 4 }; int row1[2] = { 5, 6 }; int* jagged[2] = { row0, row1 }; // Array to hold the size of each row int Size[2] = { 4, 2 }, k = 0; // To display elements of Jagged array for (int i = 0; i < 2; i++) { // pointer to hold the address of the row int* ptr = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf("%d ", *ptr); // move the pointer to the // next element in the row ptr++; } printf("\n"); k++; // move the pointer to the next row jagged[i]++; } return 0;}
1 2 3 4
5 6
Using an array of pointer (Dynamic Jagged Array)Declare an array of pointers (jagged array),The size of this array will be the number of rows required in the Jagged arrayThen for each pointer in the array allocate memory for the number of elements you want in this row.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ // 2 Rows int* jagged[2]; // Allocate memory for elements in row 0 jagged[0] = malloc(sizeof(int) * 1); // Allocate memory for elements in row 1 jagged[1] = malloc(sizeof(int) * 3); // Array to hold the size of each row int Size[2] = { 1, 3 }, k = 0, number = 100; // User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; // move the pointer p++; } k++; } k = 0; // Display elements in Jagged array for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf("%d ", *p); // move the pointer to the next element p++; } printf("\n"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:100
101 102 103
Declare an array of pointers (jagged array),
The size of this array will be the number of rows required in the Jagged array
Then for each pointer in the array allocate memory for the number of elements you want in this row.
Below is the implementation of the above approach:Example:
// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ // 2 Rows int* jagged[2]; // Allocate memory for elements in row 0 jagged[0] = malloc(sizeof(int) * 1); // Allocate memory for elements in row 1 jagged[1] = malloc(sizeof(int) * 3); // Array to hold the size of each row int Size[2] = { 1, 3 }, k = 0, number = 100; // User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; // move the pointer p++; } k++; } k = 0; // Display elements in Jagged array for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf("%d ", *p); // move the pointer to the next element p++; } printf("\n"); k++; // move the pointer to the next row jagged[i]++; } return 0;}
100
101 102 103
Technical Scripter 2019
Arrays
C Language
Technical Scripter
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Feb, 2020"
},
{
"code": null,
"e": 78,
"s": 52,
"text": "Prerequisite: Arrays in C"
},
{
"code": null,
"e": 298,
"s": 78,
"text": "Jagged array is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. These type of arrays are also known as Jagged arrays."
},
{
"code": null,
"e": 307,
"s": 298,
"text": "Example:"
},
{
"code": null,
"e": 410,
"s": 307,
"text": "arr[][] = { {0, 1, 2},\n {6, 4},\n {1, 7, 6, 8, 9},\n {5} \n };\n"
},
{
"code": null,
"e": 468,
"s": 410,
"text": "Below are the methods to implement the jagged array in C:"
},
{
"code": null,
"e": 3052,
"s": 468,
"text": "Using array and a pointer (Static Jagged Array)First declare 1-D arrays with the number of rows you will need,The size of each array (array for the elements in the row) will be the number of columns (or elements) in the row,Then declare a 1-D array of pointers that will hold the addresses of the rows,The size of the 1-D array is the number of rows you want in the jagged array.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ int row0[4] = { 1, 2, 3, 4 }; int row1[2] = { 5, 6 }; int* jagged[2] = { row0, row1 }; // Array to hold the size of each row int Size[2] = { 4, 2 }, k = 0; // To display elements of Jagged array for (int i = 0; i < 2; i++) { // pointer to hold the address of the row int* ptr = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf(\"%d \", *ptr); // move the pointer to the // next element in the row ptr++; } printf(\"\\n\"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:1 2 3 4 \n5 6\nUsing an array of pointer (Dynamic Jagged Array)Declare an array of pointers (jagged array),The size of this array will be the number of rows required in the Jagged arrayThen for each pointer in the array allocate memory for the number of elements you want in this row.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ // 2 Rows int* jagged[2]; // Allocate memory for elements in row 0 jagged[0] = malloc(sizeof(int) * 1); // Allocate memory for elements in row 1 jagged[1] = malloc(sizeof(int) * 3); // Array to hold the size of each row int Size[2] = { 1, 3 }, k = 0, number = 100; // User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; // move the pointer p++; } k++; } k = 0; // Display elements in Jagged array for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf(\"%d \", *p); // move the pointer to the next element p++; } printf(\"\\n\"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:100 \n101 102 103\n"
},
{
"code": null,
"e": 4257,
"s": 3052,
"text": "Using array and a pointer (Static Jagged Array)First declare 1-D arrays with the number of rows you will need,The size of each array (array for the elements in the row) will be the number of columns (or elements) in the row,Then declare a 1-D array of pointers that will hold the addresses of the rows,The size of the 1-D array is the number of rows you want in the jagged array.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ int row0[4] = { 1, 2, 3, 4 }; int row1[2] = { 5, 6 }; int* jagged[2] = { row0, row1 }; // Array to hold the size of each row int Size[2] = { 4, 2 }, k = 0; // To display elements of Jagged array for (int i = 0; i < 2; i++) { // pointer to hold the address of the row int* ptr = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf(\"%d \", *ptr); // move the pointer to the // next element in the row ptr++; } printf(\"\\n\"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:1 2 3 4 \n5 6\n"
},
{
"code": null,
"e": 4321,
"s": 4257,
"text": "First declare 1-D arrays with the number of rows you will need,"
},
{
"code": null,
"e": 4436,
"s": 4321,
"text": "The size of each array (array for the elements in the row) will be the number of columns (or elements) in the row,"
},
{
"code": null,
"e": 4515,
"s": 4436,
"text": "Then declare a 1-D array of pointers that will hold the addresses of the rows,"
},
{
"code": null,
"e": 4593,
"s": 4515,
"text": "The size of the 1-D array is the number of rows you want in the jagged array."
},
{
"code": null,
"e": 4652,
"s": 4593,
"text": "Below is the implementation of the above approach:Example:"
},
{
"code": "// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ int row0[4] = { 1, 2, 3, 4 }; int row1[2] = { 5, 6 }; int* jagged[2] = { row0, row1 }; // Array to hold the size of each row int Size[2] = { 4, 2 }, k = 0; // To display elements of Jagged array for (int i = 0; i < 2; i++) { // pointer to hold the address of the row int* ptr = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf(\"%d \", *ptr); // move the pointer to the // next element in the row ptr++; } printf(\"\\n\"); k++; // move the pointer to the next row jagged[i]++; } return 0;}",
"e": 5400,
"s": 4652,
"text": null
},
{
"code": null,
"e": 5414,
"s": 5400,
"text": "1 2 3 4 \n5 6\n"
},
{
"code": null,
"e": 6794,
"s": 5414,
"text": "Using an array of pointer (Dynamic Jagged Array)Declare an array of pointers (jagged array),The size of this array will be the number of rows required in the Jagged arrayThen for each pointer in the array allocate memory for the number of elements you want in this row.Below is the implementation of the above approach:Example:// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ // 2 Rows int* jagged[2]; // Allocate memory for elements in row 0 jagged[0] = malloc(sizeof(int) * 1); // Allocate memory for elements in row 1 jagged[1] = malloc(sizeof(int) * 3); // Array to hold the size of each row int Size[2] = { 1, 3 }, k = 0, number = 100; // User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; // move the pointer p++; } k++; } k = 0; // Display elements in Jagged array for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf(\"%d \", *p); // move the pointer to the next element p++; } printf(\"\\n\"); k++; // move the pointer to the next row jagged[i]++; } return 0;}Output:100 \n101 102 103\n"
},
{
"code": null,
"e": 6839,
"s": 6794,
"text": "Declare an array of pointers (jagged array),"
},
{
"code": null,
"e": 6918,
"s": 6839,
"text": "The size of this array will be the number of rows required in the Jagged array"
},
{
"code": null,
"e": 7018,
"s": 6918,
"text": "Then for each pointer in the array allocate memory for the number of elements you want in this row."
},
{
"code": null,
"e": 7077,
"s": 7018,
"text": "Below is the implementation of the above approach:Example:"
},
{
"code": "// C program to show the// implementation of Jagged Arrays #include <stdio.h>#include <stdlib.h> int main(){ // 2 Rows int* jagged[2]; // Allocate memory for elements in row 0 jagged[0] = malloc(sizeof(int) * 1); // Allocate memory for elements in row 1 jagged[1] = malloc(sizeof(int) * 3); // Array to hold the size of each row int Size[2] = { 1, 3 }, k = 0, number = 100; // User enters the numbers for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { *p = number++; // move the pointer p++; } k++; } k = 0; // Display elements in Jagged array for (int i = 0; i < 2; i++) { int* p = jagged[i]; for (int j = 0; j < Size[k]; j++) { printf(\"%d \", *p); // move the pointer to the next element p++; } printf(\"\\n\"); k++; // move the pointer to the next row jagged[i]++; } return 0;}",
"e": 8106,
"s": 7077,
"text": null
},
{
"code": null,
"e": 8124,
"s": 8106,
"text": "100 \n101 102 103\n"
},
{
"code": null,
"e": 8148,
"s": 8124,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 8155,
"s": 8148,
"text": "Arrays"
},
{
"code": null,
"e": 8166,
"s": 8155,
"text": "C Language"
},
{
"code": null,
"e": 8185,
"s": 8166,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8192,
"s": 8185,
"text": "Arrays"
}
] |
Estimating Currency Volatility Using GARCH | by Michael Grogan | Towards Data Science
|
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as investment advice, or any other sort of professional advice.
Asset prices have a high degree of stochastic trends inherent in the time series. In other words, price fluctuations are subject to a large degree of randomness, and therefore it is very difficult to forecast asset prices using traditional time series models such as ARIMA.
Moreover, with much of the trading done on an algorithmic basis today — prices are constantly adjusting on the basis of such forecasts — making it quite hard to exploit an advantage in the markets.
For instance, suppose I build a time series model to predict rainfall in a city for the next three months. My time series model could have a strong degree of accuracy as the forecasts will not influence rainfall levels in the future. However, if everyone uses an ARIMA model to predict asset price fluctuations for the next three months — then subsequent trading on the basis of those forecasts will directly influence previous forecasts — rendering them invalid in many cases.
As a result, it is common to model projected volatility of an asset price in the financial markets — as opposed to forecasting projected price outright.
Let’s see how this can be accomplished using Python. A GARCH model is used to forecast volatility for the EUR/USD and GBP/USD currency pairs, using data from January 2017 — January 2018.
The data is sourced from FRED using the Quandl library:
eurusd = quandl.get("FRED/DEXUSEU", start_date='2017-01-01', end_date='2018-01-01', api_key='enter_api_key')gbpusd = quandl.get("FRED/DEXUSUK", start_date='2017-01-01', end_date='2018-01-01', api_key='enter_api_key')
The series are converted to logarithmic format to smooth out the time series:
The data is then first-differenced to approximate a Gaussian distribution.
Dickey-Fuller tests show a p-value of 0 for both series — indicating that we reject the null hypothesis that a unit root is present at the 5% level of significance, i.e. stationarity or trend stationarity is indicated as being present in the model.
EUR/USD: Dickey-Fuller Test Results
>>> result = ts.adfuller(data, 1)>>> result(-16.26123019770431, 3.564065405943774e-29, 0, 247, {'1%': -3.457105309726321, '5%': -2.873313676101283, '10%': -2.5730443824681606}, -1959.704886024891)
GBP/USD: Dickey-Fuller Test Results
>>> result = ts.adfuller(data, 1)>>> result(-12.380335699861567, 5.045829408723097e-23, 1, 246, {'1%': -3.457215237265747, '5%': -2.873361841566324, '10%': -2.5730700760129555}, -1892.8308007824835)
Additionally, a visual screening of QQ plots show that the series now largely follow a normal distribution:
EUR/USD: QQ Plot
GBP/USD: QQ Plot
A GARCH(1,1) model is built to predict the volatility for the last 30 days of trading data for both currency pairs. The previous data is used as the training set for the GARCH model.
# split into train/testn_test = 30train, test = data[:-n_test], data[-n_test:]# define modelmodel = arch_model(train, mean='Zero', vol='GARCH', p=1, q=1)
The predictions are generated as follows:
# fit modelmodel_fit = model.fit()# forecast the test setyhat = model_fit.forecast(horizon=n_test)
Now, let’s compare the predicted variance with the actual 5-day rolling variance across the test set.
Predicted Variance
test.rolling(window=5).var().plot(style='g')pyplot.title("5-day Rolling Variance")
5-day Rolling Variance
pyplot.plot(yhat.variance.values[-1, :])pyplot.title("Predicted Variance")pyplot.show()
We see that the GARCH model predicts a drop in volatility for the last 30 days (as measured by variance) — this is confirmed by a visual inspection of the actual 5-day rolling variance.
Let’s have a look at the comparisons across the GBP/USD.
Predicted Variance
5-day Rolling Variance
We can see that while the scale for the predicted variance is much narrower than the actual 5-day rolling variance — both instances are predicting a decrease in variance across the 30-day test period.
This corresponds with what we actually observe — there was little movement in both the EUR/USD and GBP/USD currency pairs in December 2017 relative to that of other months in the trading year.
This has been an illustration of how GARCH can be used to model time series volatility.
Hope you found the article useful, and any questions or feedback are greatly appreciated.
Machine Learning Mastery: How to Model Volatility with ARCH and GARCH for Time Series Forecasting in Python
|
[
{
"code": null,
"e": 429,
"s": 172,
"text": "Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as investment advice, or any other sort of professional advice."
},
{
"code": null,
"e": 703,
"s": 429,
"text": "Asset prices have a high degree of stochastic trends inherent in the time series. In other words, price fluctuations are subject to a large degree of randomness, and therefore it is very difficult to forecast asset prices using traditional time series models such as ARIMA."
},
{
"code": null,
"e": 901,
"s": 703,
"text": "Moreover, with much of the trading done on an algorithmic basis today — prices are constantly adjusting on the basis of such forecasts — making it quite hard to exploit an advantage in the markets."
},
{
"code": null,
"e": 1379,
"s": 901,
"text": "For instance, suppose I build a time series model to predict rainfall in a city for the next three months. My time series model could have a strong degree of accuracy as the forecasts will not influence rainfall levels in the future. However, if everyone uses an ARIMA model to predict asset price fluctuations for the next three months — then subsequent trading on the basis of those forecasts will directly influence previous forecasts — rendering them invalid in many cases."
},
{
"code": null,
"e": 1532,
"s": 1379,
"text": "As a result, it is common to model projected volatility of an asset price in the financial markets — as opposed to forecasting projected price outright."
},
{
"code": null,
"e": 1719,
"s": 1532,
"text": "Let’s see how this can be accomplished using Python. A GARCH model is used to forecast volatility for the EUR/USD and GBP/USD currency pairs, using data from January 2017 — January 2018."
},
{
"code": null,
"e": 1775,
"s": 1719,
"text": "The data is sourced from FRED using the Quandl library:"
},
{
"code": null,
"e": 1992,
"s": 1775,
"text": "eurusd = quandl.get(\"FRED/DEXUSEU\", start_date='2017-01-01', end_date='2018-01-01', api_key='enter_api_key')gbpusd = quandl.get(\"FRED/DEXUSUK\", start_date='2017-01-01', end_date='2018-01-01', api_key='enter_api_key')"
},
{
"code": null,
"e": 2070,
"s": 1992,
"text": "The series are converted to logarithmic format to smooth out the time series:"
},
{
"code": null,
"e": 2145,
"s": 2070,
"text": "The data is then first-differenced to approximate a Gaussian distribution."
},
{
"code": null,
"e": 2394,
"s": 2145,
"text": "Dickey-Fuller tests show a p-value of 0 for both series — indicating that we reject the null hypothesis that a unit root is present at the 5% level of significance, i.e. stationarity or trend stationarity is indicated as being present in the model."
},
{
"code": null,
"e": 2430,
"s": 2394,
"text": "EUR/USD: Dickey-Fuller Test Results"
},
{
"code": null,
"e": 2629,
"s": 2430,
"text": ">>> result = ts.adfuller(data, 1)>>> result(-16.26123019770431, 3.564065405943774e-29, 0, 247, {'1%': -3.457105309726321, '5%': -2.873313676101283, '10%': -2.5730443824681606}, -1959.704886024891)"
},
{
"code": null,
"e": 2665,
"s": 2629,
"text": "GBP/USD: Dickey-Fuller Test Results"
},
{
"code": null,
"e": 2866,
"s": 2665,
"text": ">>> result = ts.adfuller(data, 1)>>> result(-12.380335699861567, 5.045829408723097e-23, 1, 246, {'1%': -3.457215237265747, '5%': -2.873361841566324, '10%': -2.5730700760129555}, -1892.8308007824835)"
},
{
"code": null,
"e": 2974,
"s": 2866,
"text": "Additionally, a visual screening of QQ plots show that the series now largely follow a normal distribution:"
},
{
"code": null,
"e": 2991,
"s": 2974,
"text": "EUR/USD: QQ Plot"
},
{
"code": null,
"e": 3008,
"s": 2991,
"text": "GBP/USD: QQ Plot"
},
{
"code": null,
"e": 3191,
"s": 3008,
"text": "A GARCH(1,1) model is built to predict the volatility for the last 30 days of trading data for both currency pairs. The previous data is used as the training set for the GARCH model."
},
{
"code": null,
"e": 3345,
"s": 3191,
"text": "# split into train/testn_test = 30train, test = data[:-n_test], data[-n_test:]# define modelmodel = arch_model(train, mean='Zero', vol='GARCH', p=1, q=1)"
},
{
"code": null,
"e": 3387,
"s": 3345,
"text": "The predictions are generated as follows:"
},
{
"code": null,
"e": 3486,
"s": 3387,
"text": "# fit modelmodel_fit = model.fit()# forecast the test setyhat = model_fit.forecast(horizon=n_test)"
},
{
"code": null,
"e": 3588,
"s": 3486,
"text": "Now, let’s compare the predicted variance with the actual 5-day rolling variance across the test set."
},
{
"code": null,
"e": 3607,
"s": 3588,
"text": "Predicted Variance"
},
{
"code": null,
"e": 3690,
"s": 3607,
"text": "test.rolling(window=5).var().plot(style='g')pyplot.title(\"5-day Rolling Variance\")"
},
{
"code": null,
"e": 3713,
"s": 3690,
"text": "5-day Rolling Variance"
},
{
"code": null,
"e": 3801,
"s": 3713,
"text": "pyplot.plot(yhat.variance.values[-1, :])pyplot.title(\"Predicted Variance\")pyplot.show()"
},
{
"code": null,
"e": 3987,
"s": 3801,
"text": "We see that the GARCH model predicts a drop in volatility for the last 30 days (as measured by variance) — this is confirmed by a visual inspection of the actual 5-day rolling variance."
},
{
"code": null,
"e": 4044,
"s": 3987,
"text": "Let’s have a look at the comparisons across the GBP/USD."
},
{
"code": null,
"e": 4063,
"s": 4044,
"text": "Predicted Variance"
},
{
"code": null,
"e": 4086,
"s": 4063,
"text": "5-day Rolling Variance"
},
{
"code": null,
"e": 4287,
"s": 4086,
"text": "We can see that while the scale for the predicted variance is much narrower than the actual 5-day rolling variance — both instances are predicting a decrease in variance across the 30-day test period."
},
{
"code": null,
"e": 4480,
"s": 4287,
"text": "This corresponds with what we actually observe — there was little movement in both the EUR/USD and GBP/USD currency pairs in December 2017 relative to that of other months in the trading year."
},
{
"code": null,
"e": 4568,
"s": 4480,
"text": "This has been an illustration of how GARCH can be used to model time series volatility."
},
{
"code": null,
"e": 4658,
"s": 4568,
"text": "Hope you found the article useful, and any questions or feedback are greatly appreciated."
}
] |
Releasing GIL and mixing threads from C and Python - GeeksforGeeks
|
29 Mar, 2019
Releasing GIL in C extension:Give a C extension code and one needs to concurrently execute it with other threads in the Python interpreter. For this Global Interpreter Lock (GIL) has to be released and reacquired.
Code #1 : Releasing and Reacquiring GIL by inserting following macros
#include "Python.h"...PyObject *pyfunc(PyObject *self, PyObject *args){ ... Py_BEGIN_ALLOW_THREADS // Threaded C code. // Must not use Python API functions ... Py_END_ALLOW_THREADS ... return result;}
Mixing Threads from C and Python:Considering a situation, that a given program involves a mix of C, Python and threads. But some of the given threads are created from C outside the control of the Python interpreter and also certain threads utilize functions in the Python C API.
What’s solution then?If there is a mix of Python, C and threads, proper initialization and management of Python’s Global Interpreter Lock (GIL) is important. Given code below explains the situation, their code can be used anywhere (prior to the creation of threads) in the C program.
Code #2 :
#include <Python.h>...if (!PyEval_ThreadsInitialized()){ PyEval_InitThreads();}...
For any C involving Python objects or the Python C API, GIL needs to be acquired and released first. This can be performed using PyGILState_Ensure() and PyGILState_Release() as in the code given below. Every call to PyGILState_Ensure() must have a matching call to PyGILState_Release().
Code #3 :
...// Make sure we own the GIL// Use functions in the interpreterPyGILState_STATE state = PyGILState_Ensure(); ...// Restore previous GIL state and return PyGILState_Release(state);...
Note :It is not so easy to have so much things going at once, involving a mix of a Python code, C code and their threads. To perform so, it is to be taken care that the interpreter is properly initialized and that C code involving the interpreter has the proper GIL management calls, it all should work.Also, the PyGILState_Ensure() call does not immediately preempt or interrupt the interpreter. If other code is currently executing, this function will block until that code decides to release the Global Interpreter Lock (GIL).
Python-ctype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26077,
"s": 26049,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 26291,
"s": 26077,
"text": "Releasing GIL in C extension:Give a C extension code and one needs to concurrently execute it with other threads in the Python interpreter. For this Global Interpreter Lock (GIL) has to be released and reacquired."
},
{
"code": null,
"e": 26361,
"s": 26291,
"text": "Code #1 : Releasing and Reacquiring GIL by inserting following macros"
},
{
"code": "#include \"Python.h\"...PyObject *pyfunc(PyObject *self, PyObject *args){ ... Py_BEGIN_ALLOW_THREADS // Threaded C code. // Must not use Python API functions ... Py_END_ALLOW_THREADS ... return result;}",
"e": 26593,
"s": 26361,
"text": null
},
{
"code": null,
"e": 26872,
"s": 26593,
"text": "Mixing Threads from C and Python:Considering a situation, that a given program involves a mix of C, Python and threads. But some of the given threads are created from C outside the control of the Python interpreter and also certain threads utilize functions in the Python C API."
},
{
"code": null,
"e": 27156,
"s": 26872,
"text": "What’s solution then?If there is a mix of Python, C and threads, proper initialization and management of Python’s Global Interpreter Lock (GIL) is important. Given code below explains the situation, their code can be used anywhere (prior to the creation of threads) in the C program."
},
{
"code": null,
"e": 27166,
"s": 27156,
"text": "Code #2 :"
},
{
"code": "#include <Python.h>...if (!PyEval_ThreadsInitialized()){ PyEval_InitThreads();}...",
"e": 27252,
"s": 27166,
"text": null
},
{
"code": null,
"e": 27539,
"s": 27252,
"text": "For any C involving Python objects or the Python C API, GIL needs to be acquired and released first. This can be performed using PyGILState_Ensure() and PyGILState_Release() as in the code given below. Every call to PyGILState_Ensure() must have a matching call to PyGILState_Release()."
},
{
"code": null,
"e": 27549,
"s": 27539,
"text": "Code #3 :"
},
{
"code": "...// Make sure we own the GIL// Use functions in the interpreterPyGILState_STATE state = PyGILState_Ensure(); ...// Restore previous GIL state and return PyGILState_Release(state);...",
"e": 27735,
"s": 27549,
"text": null
},
{
"code": null,
"e": 28265,
"s": 27735,
"text": "Note :It is not so easy to have so much things going at once, involving a mix of a Python code, C code and their threads. To perform so, it is to be taken care that the interpreter is properly initialized and that C code involving the interpreter has the proper GIL management calls, it all should work.Also, the PyGILState_Ensure() call does not immediately preempt or interrupt the interpreter. If other code is currently executing, this function will block until that code decides to release the Global Interpreter Lock (GIL)."
},
{
"code": null,
"e": 28278,
"s": 28265,
"text": "Python-ctype"
},
{
"code": null,
"e": 28285,
"s": 28278,
"text": "Python"
},
{
"code": null,
"e": 28383,
"s": 28285,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28401,
"s": 28383,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28433,
"s": 28401,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28455,
"s": 28433,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28497,
"s": 28455,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28523,
"s": 28497,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28552,
"s": 28523,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28596,
"s": 28552,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28633,
"s": 28596,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28669,
"s": 28633,
"text": "Convert integer to string in Python"
}
] |
How to iterate through Excel rows in Python? - GeeksforGeeks
|
25 Feb, 2021
In this article, we are going to discuss how to iterate through Excel Rows in Python. In order to perform this task, we will be using the Openpyxl module in python. Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows a Python program to read and modify Excel files.
We will be using this excel worksheet in the below examples:
Approach #1:
We will create an object of openpyxl, and then we’ll iterate through all rows from top to bottom.
Python3
# import moduleimport openpyxl # load excel with its pathwrkbk = openpyxl.load_workbook("Book1.xlsx") sh = wrkbk.active # iterate through excel and display datafor i in range(1, sh.max_row+1): print("\n") print("Row ", i, " data :") for j in range(1, sh.max_column+1): cell_obj = sh.cell(row=i, column=j) print(cell_obj.value, end=" ")
Output:
Approach #2
We will create an object of openpyxl, and then we’ll iterate through all rows using iter_rows() method.
Python3
# import moduleimport openpyxl # load excel with its pathwrkbk = openpyxl.load_workbook("Book1.xlsx") sh = wrkbk.active # iterate through excel and display datafor row in sh.iter_rows(min_row=1, min_col=1, max_row=12, max_col=3): for cell in row: print(cell.value, end=" ") print()
Output:
Picked
Python-excel
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n25 Feb, 2021"
},
{
"code": null,
"e": 25899,
"s": 25555,
"text": "In this article, we are going to discuss how to iterate through Excel Rows in Python. In order to perform this task, we will be using the Openpyxl module in python. Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows a Python program to read and modify Excel files."
},
{
"code": null,
"e": 25960,
"s": 25899,
"text": "We will be using this excel worksheet in the below examples:"
},
{
"code": null,
"e": 25973,
"s": 25960,
"text": "Approach #1:"
},
{
"code": null,
"e": 26071,
"s": 25973,
"text": "We will create an object of openpyxl, and then we’ll iterate through all rows from top to bottom."
},
{
"code": null,
"e": 26079,
"s": 26071,
"text": "Python3"
},
{
"code": "# import moduleimport openpyxl # load excel with its pathwrkbk = openpyxl.load_workbook(\"Book1.xlsx\") sh = wrkbk.active # iterate through excel and display datafor i in range(1, sh.max_row+1): print(\"\\n\") print(\"Row \", i, \" data :\") for j in range(1, sh.max_column+1): cell_obj = sh.cell(row=i, column=j) print(cell_obj.value, end=\" \")",
"e": 26447,
"s": 26079,
"text": null
},
{
"code": null,
"e": 26455,
"s": 26447,
"text": "Output:"
},
{
"code": null,
"e": 26467,
"s": 26455,
"text": "Approach #2"
},
{
"code": null,
"e": 26571,
"s": 26467,
"text": "We will create an object of openpyxl, and then we’ll iterate through all rows using iter_rows() method."
},
{
"code": null,
"e": 26579,
"s": 26571,
"text": "Python3"
},
{
"code": "# import moduleimport openpyxl # load excel with its pathwrkbk = openpyxl.load_workbook(\"Book1.xlsx\") sh = wrkbk.active # iterate through excel and display datafor row in sh.iter_rows(min_row=1, min_col=1, max_row=12, max_col=3): for cell in row: print(cell.value, end=\" \") print()",
"e": 26877,
"s": 26579,
"text": null
},
{
"code": null,
"e": 26885,
"s": 26877,
"text": "Output:"
},
{
"code": null,
"e": 26892,
"s": 26885,
"text": "Picked"
},
{
"code": null,
"e": 26905,
"s": 26892,
"text": "Python-excel"
},
{
"code": null,
"e": 26912,
"s": 26905,
"text": "Python"
},
{
"code": null,
"e": 27010,
"s": 26912,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27042,
"s": 27010,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27084,
"s": 27042,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27126,
"s": 27084,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27182,
"s": 27126,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27209,
"s": 27182,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27240,
"s": 27209,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27279,
"s": 27240,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27308,
"s": 27279,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27330,
"s": 27308,
"text": "Defaultdict in Python"
}
] |
Python | NLTK nltk.tokenize.ConditionalFreqDist() - GeeksforGeeks
|
22 Nov, 2019
With the help of nltk.tokenize.ConditionalFreqDist() method, we are able to count the frequency of words in a sentence by using tokenize.ConditionalFreqDist() method.
Syntax : tokenize.ConditionalFreqDist()Return : Return the frequency distribution of words in a dictionary.
Example #1 :In this example we can see that by using tokenize.ConditionalFreqDist() method, we are able to count the occurrence of words in a sentence.
# import ConditionalFreqDist() method from nltkfrom nltk.probability import ConditionalFreqDistfrom nltk.tokenize import word_tokenize # Create a reference variable for Class SExprTokenizertk = ConditionalFreqDist() # Create a string inputgfg = "Geeks for Geeks" for word in word_tokenize(gfg): condition = len(word) tk[condition][word] += 1 print(tk)
Output :
FreqDist({‘Geeks’: 2, ‘for’: 1})
Example #2 :
# import ConditionalFreqDist() method from nltkfrom nltk.probability import ConditionalFreqDistfrom nltk.tokenize import word_tokenize # Create a reference variable for Class SExprTokenizertk = ConditionalFreqDist() # Create a string inputgfg = "G F G" for word in word_tokenize(gfg): condition = len(word) tk[condition][word] += 1 print(tk)
Output :
FreqDist({‘G’: 2, ‘F’: 1})
ManasChhabra2
Python-nltk
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n22 Nov, 2019"
},
{
"code": null,
"e": 25704,
"s": 25537,
"text": "With the help of nltk.tokenize.ConditionalFreqDist() method, we are able to count the frequency of words in a sentence by using tokenize.ConditionalFreqDist() method."
},
{
"code": null,
"e": 25812,
"s": 25704,
"text": "Syntax : tokenize.ConditionalFreqDist()Return : Return the frequency distribution of words in a dictionary."
},
{
"code": null,
"e": 25964,
"s": 25812,
"text": "Example #1 :In this example we can see that by using tokenize.ConditionalFreqDist() method, we are able to count the occurrence of words in a sentence."
},
{
"code": "# import ConditionalFreqDist() method from nltkfrom nltk.probability import ConditionalFreqDistfrom nltk.tokenize import word_tokenize # Create a reference variable for Class SExprTokenizertk = ConditionalFreqDist() # Create a string inputgfg = \"Geeks for Geeks\" for word in word_tokenize(gfg): condition = len(word) tk[condition][word] += 1 print(tk)",
"e": 26336,
"s": 25964,
"text": null
},
{
"code": null,
"e": 26345,
"s": 26336,
"text": "Output :"
},
{
"code": null,
"e": 26378,
"s": 26345,
"text": "FreqDist({‘Geeks’: 2, ‘for’: 1})"
},
{
"code": null,
"e": 26391,
"s": 26378,
"text": "Example #2 :"
},
{
"code": "# import ConditionalFreqDist() method from nltkfrom nltk.probability import ConditionalFreqDistfrom nltk.tokenize import word_tokenize # Create a reference variable for Class SExprTokenizertk = ConditionalFreqDist() # Create a string inputgfg = \"G F G\" for word in word_tokenize(gfg): condition = len(word) tk[condition][word] += 1 print(tk)",
"e": 26753,
"s": 26391,
"text": null
},
{
"code": null,
"e": 26762,
"s": 26753,
"text": "Output :"
},
{
"code": null,
"e": 26789,
"s": 26762,
"text": "FreqDist({‘G’: 2, ‘F’: 1})"
},
{
"code": null,
"e": 26803,
"s": 26789,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 26815,
"s": 26803,
"text": "Python-nltk"
},
{
"code": null,
"e": 26822,
"s": 26815,
"text": "Python"
},
{
"code": null,
"e": 26920,
"s": 26822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26952,
"s": 26920,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26994,
"s": 26952,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27036,
"s": 26994,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27063,
"s": 27036,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27119,
"s": 27063,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27158,
"s": 27119,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27180,
"s": 27158,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27211,
"s": 27180,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27240,
"s": 27211,
"text": "Create a directory in Python"
}
] |
Numbers in Java (With 0 Prefix and with Strings) - GeeksforGeeks
|
30 May, 2018
Consider the following Java program.
import java.io.*;class GFG{ public static void main (String[] args) { int x = 012; System.out.print(x); }}
Output:
10
The reason for above output is, when a 0 is prefixed the value is considered octal, since 12 in octal is 10 in decimal, the result is 10. Similarly, if i = 0112, result will be 74 (in decimal). This behavior is same as C/C++ (see this).
Also,
import java.io.*;class GFG{ public static void main (String[] args) { String s = 3 + 2 + "hello" + 6 + 4; System.out.print(s); }}
Output :
5hello64
Java takes the numbers before the strings are introduced as int and once the string literals are introduced, all the following numbers are considered as strings.
This article is contributed by Hiresh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Constructors in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
|
[
{
"code": null,
"e": 24114,
"s": 24086,
"text": "\n30 May, 2018"
},
{
"code": null,
"e": 24151,
"s": 24114,
"text": "Consider the following Java program."
},
{
"code": "import java.io.*;class GFG{ public static void main (String[] args) { int x = 012; System.out.print(x); }}",
"e": 24281,
"s": 24151,
"text": null
},
{
"code": null,
"e": 24289,
"s": 24281,
"text": "Output:"
},
{
"code": null,
"e": 24292,
"s": 24289,
"text": "10"
},
{
"code": null,
"e": 24529,
"s": 24292,
"text": "The reason for above output is, when a 0 is prefixed the value is considered octal, since 12 in octal is 10 in decimal, the result is 10. Similarly, if i = 0112, result will be 74 (in decimal). This behavior is same as C/C++ (see this)."
},
{
"code": null,
"e": 24535,
"s": 24529,
"text": "Also,"
},
{
"code": "import java.io.*;class GFG{ public static void main (String[] args) { String s = 3 + 2 + \"hello\" + 6 + 4; System.out.print(s); }}",
"e": 24688,
"s": 24535,
"text": null
},
{
"code": null,
"e": 24697,
"s": 24688,
"text": "Output :"
},
{
"code": null,
"e": 24706,
"s": 24697,
"text": "5hello64"
},
{
"code": null,
"e": 24868,
"s": 24706,
"text": "Java takes the numbers before the strings are introduced as int and once the string literals are introduced, all the following numbers are considered as strings."
},
{
"code": null,
"e": 25170,
"s": 24868,
"text": "This article is contributed by Hiresh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 25295,
"s": 25170,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 25300,
"s": 25295,
"text": "Java"
},
{
"code": null,
"e": 25305,
"s": 25300,
"text": "Java"
},
{
"code": null,
"e": 25403,
"s": 25305,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25418,
"s": 25403,
"text": "Stream In Java"
},
{
"code": null,
"e": 25437,
"s": 25418,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25483,
"s": 25437,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25504,
"s": 25483,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25534,
"s": 25504,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25551,
"s": 25534,
"text": "Generics in Java"
},
{
"code": null,
"e": 25594,
"s": 25551,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 25616,
"s": 25594,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 25637,
"s": 25616,
"text": "Introduction to Java"
}
] |
How to show an Axes Subplot in Python?
|
To show an axes subplot in Python, we can use show() method. When multiple figures are created,
then those images are displayed using show() method.
Create x and y data points using numpy.
Plot x and y using plot() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.arange(10)
y = np.exp(x)
plt.plot(x, y)
plt.show()
|
[
{
"code": null,
"e": 1211,
"s": 1062,
"text": "To show an axes subplot in Python, we can use show() method. When multiple figures are created,\nthen those images are displayed using show() method."
},
{
"code": null,
"e": 1251,
"s": 1211,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1285,
"s": 1251,
"text": "Plot x and y using plot() method."
},
{
"code": null,
"e": 1327,
"s": 1285,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1528,
"s": 1327,
"text": "from matplotlib import pyplot as plt\nimport numpy as np\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.arange(10)\ny = np.exp(x)\nplt.plot(x, y)\nplt.show()"
}
] |
Docker - Logging
|
Docker has logging mechanisms in place which can be used to debug issues as and when they occur. There is logging at the daemon level and at the container level. Let’s look at the different levels of logging.
At the daemon logging level, there are four levels of logging available −
Debug − It details all the possible information handled by the daemon process.
Debug − It details all the possible information handled by the daemon process.
Info − It details all the errors + Information handled by the daemon process.
Info − It details all the errors + Information handled by the daemon process.
Errors − It details all the errors handled by the daemon process.
Errors − It details all the errors handled by the daemon process.
Fatal − It only details all the fatal errors handled by the daemon process.
Fatal − It only details all the fatal errors handled by the daemon process.
Go through the following steps to learn how to enable logging.
Step 1 − First, we need to stop the docker daemon process, if it is already running. It can be done using the following command −
sudo service docker stop
Step 2 − Now we need to start the docker daemon process. But this time, we need to append the –l parameter to specify the logging option. So let’s issue the following command when starting the docker daemon process.
sudo dockerd –l debug &
The following points need to be noted about the above command −
dockerd is the executable for the docker daemon process.
dockerd is the executable for the docker daemon process.
The –l option is used to specify the logging level. In our case, we are putting this as debug
The –l option is used to specify the logging level. In our case, we are putting this as debug
& is used to come back to the command prompt after the logging has been enabled.
& is used to come back to the command prompt after the logging has been enabled.
Once you start the Docker process with logging, you will also now see the Debug Logs being sent to the console.
Now, if you execute any Docker command such as docker images, the Debug information will also be sent to the console.
Logging is also available at the container level. So in our example, let’s spin up an Ubuntu container first. We can do it by using the following command.
sudo docker run –it ubuntu /bin/bash
Now, we can use the docker log command to see the logs of the container.
Docker logs containerID
containerID − This is the ID of the container for which you need to see the logs.
containerID − This is the ID of the container for which you need to see the logs.
On our Docker Host, let’s issue the following command. Before that, you can issue some commands whilst in the container.
sudo docker logs 6bfb1271fcdd
From the output, you can see that the commands executed in the container are shown in the logs.
70 Lectures
12 hours
Anshul Chauhan
41 Lectures
5 hours
AR Shankar
31 Lectures
3 hours
Abhilash Nelson
15 Lectures
2 hours
Harshit Srivastava, Pranjal Srivastava
33 Lectures
4 hours
Mumshad Mannambeth
13 Lectures
53 mins
Musab Zayadneh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2549,
"s": 2340,
"text": "Docker has logging mechanisms in place which can be used to debug issues as and when they occur. There is logging at the daemon level and at the container level. Let’s look at the different levels of logging."
},
{
"code": null,
"e": 2623,
"s": 2549,
"text": "At the daemon logging level, there are four levels of logging available −"
},
{
"code": null,
"e": 2702,
"s": 2623,
"text": "Debug − It details all the possible information handled by the daemon process."
},
{
"code": null,
"e": 2781,
"s": 2702,
"text": "Debug − It details all the possible information handled by the daemon process."
},
{
"code": null,
"e": 2859,
"s": 2781,
"text": "Info − It details all the errors + Information handled by the daemon process."
},
{
"code": null,
"e": 2937,
"s": 2859,
"text": "Info − It details all the errors + Information handled by the daemon process."
},
{
"code": null,
"e": 3003,
"s": 2937,
"text": "Errors − It details all the errors handled by the daemon process."
},
{
"code": null,
"e": 3069,
"s": 3003,
"text": "Errors − It details all the errors handled by the daemon process."
},
{
"code": null,
"e": 3145,
"s": 3069,
"text": "Fatal − It only details all the fatal errors handled by the daemon process."
},
{
"code": null,
"e": 3221,
"s": 3145,
"text": "Fatal − It only details all the fatal errors handled by the daemon process."
},
{
"code": null,
"e": 3284,
"s": 3221,
"text": "Go through the following steps to learn how to enable logging."
},
{
"code": null,
"e": 3414,
"s": 3284,
"text": "Step 1 − First, we need to stop the docker daemon process, if it is already running. It can be done using the following command −"
},
{
"code": null,
"e": 3441,
"s": 3414,
"text": "sudo service docker stop \n"
},
{
"code": null,
"e": 3657,
"s": 3441,
"text": "Step 2 − Now we need to start the docker daemon process. But this time, we need to append the –l parameter to specify the logging option. So let’s issue the following command when starting the docker daemon process."
},
{
"code": null,
"e": 3682,
"s": 3657,
"text": "sudo dockerd –l debug &\n"
},
{
"code": null,
"e": 3746,
"s": 3682,
"text": "The following points need to be noted about the above command −"
},
{
"code": null,
"e": 3803,
"s": 3746,
"text": "dockerd is the executable for the docker daemon process."
},
{
"code": null,
"e": 3860,
"s": 3803,
"text": "dockerd is the executable for the docker daemon process."
},
{
"code": null,
"e": 3954,
"s": 3860,
"text": "The –l option is used to specify the logging level. In our case, we are putting this as debug"
},
{
"code": null,
"e": 4048,
"s": 3954,
"text": "The –l option is used to specify the logging level. In our case, we are putting this as debug"
},
{
"code": null,
"e": 4129,
"s": 4048,
"text": "& is used to come back to the command prompt after the logging has been enabled."
},
{
"code": null,
"e": 4210,
"s": 4129,
"text": "& is used to come back to the command prompt after the logging has been enabled."
},
{
"code": null,
"e": 4322,
"s": 4210,
"text": "Once you start the Docker process with logging, you will also now see the Debug Logs being sent to the console."
},
{
"code": null,
"e": 4440,
"s": 4322,
"text": "Now, if you execute any Docker command such as docker images, the Debug information will also be sent to the console."
},
{
"code": null,
"e": 4595,
"s": 4440,
"text": "Logging is also available at the container level. So in our example, let’s spin up an Ubuntu container first. We can do it by using the following command."
},
{
"code": null,
"e": 4634,
"s": 4595,
"text": "sudo docker run –it ubuntu /bin/bash \n"
},
{
"code": null,
"e": 4707,
"s": 4634,
"text": "Now, we can use the docker log command to see the logs of the container."
},
{
"code": null,
"e": 4733,
"s": 4707,
"text": "Docker logs containerID \n"
},
{
"code": null,
"e": 4815,
"s": 4733,
"text": "containerID − This is the ID of the container for which you need to see the logs."
},
{
"code": null,
"e": 4897,
"s": 4815,
"text": "containerID − This is the ID of the container for which you need to see the logs."
},
{
"code": null,
"e": 5018,
"s": 4897,
"text": "On our Docker Host, let’s issue the following command. Before that, you can issue some commands whilst in the container."
},
{
"code": null,
"e": 5050,
"s": 5018,
"text": "sudo docker logs 6bfb1271fcdd \n"
},
{
"code": null,
"e": 5146,
"s": 5050,
"text": "From the output, you can see that the commands executed in the container are shown in the logs."
},
{
"code": null,
"e": 5180,
"s": 5146,
"text": "\n 70 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 5196,
"s": 5180,
"text": " Anshul Chauhan"
},
{
"code": null,
"e": 5229,
"s": 5196,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5241,
"s": 5229,
"text": " AR Shankar"
},
{
"code": null,
"e": 5274,
"s": 5241,
"text": "\n 31 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5291,
"s": 5274,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5324,
"s": 5291,
"text": "\n 15 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5364,
"s": 5324,
"text": " Harshit Srivastava, Pranjal Srivastava"
},
{
"code": null,
"e": 5397,
"s": 5364,
"text": "\n 33 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5417,
"s": 5397,
"text": " Mumshad Mannambeth"
},
{
"code": null,
"e": 5449,
"s": 5417,
"text": "\n 13 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 5465,
"s": 5449,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 5472,
"s": 5465,
"text": " Print"
},
{
"code": null,
"e": 5483,
"s": 5472,
"text": " Add Notes"
}
] |
How to use Boto3 to start the scheduler of a crawler in AWS Glue Data Catalog
|
In this article, we will see how a user can start the scheduler of a crawler in AWS Glue Data Catalog.
Start the scheduler of a crawler available in AWS Glue Data Catalog.
Problem Statement: Use boto3 library in Python to start the scheduler of a crawler.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2:
crawler_name is the required parameter in this function.
Step 2:
crawler_name is the required parameter in this function.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4: Create an AWS client for glue.
Step 4: Create an AWS client for glue.
Step 5: Now use the start_crawler_schedule function and pass the parameter crawler_name as CrawlerName.
Step 5: Now use the start_crawler_schedule function and pass the parameter crawler_name as CrawlerName.
Step 6: It returns the response metadata and sets the schedule state of the crawler as SCHEDULED. If the status of the crawler is running or the schedule state is already SCHEDULED, then it throws the exception - SchedulerRunningException.
Step 6: It returns the response metadata and sets the schedule state of the crawler as SCHEDULED. If the status of the crawler is running or the schedule state is already SCHEDULED, then it throws the exception - SchedulerRunningException.
Step 7: Handle the generic exception if something went wrong while starting the scheduler of a crawler.
Step 7: Handle the generic exception if something went wrong while starting the scheduler of a crawler.
The following code starts the scheduler of a crawler −
import boto3
from botocore.exceptions import ClientError
def start_scheduler_of_a_crawler(crawler_name)
session = boto3.session.Session()
glue_client = session.client('glue')
try:
response = glue_client.start_crawler_schedule(CrawlerName=crawler_name)
return response
except ClientError as e:
raise Exception("boto3 client error in start_scheduler_of_a_crawler: " + e.__str__())
except Exception as e:
raise Exception("Unexpected error in start_scheduler_of_a_crawler: " + e.__str__())
print(start_scheduler_of_a_crawler("Data Dimension"))
{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}
|
[
{
"code": null,
"e": 1165,
"s": 1062,
"text": "In this article, we will see how a user can start the scheduler of a crawler in AWS Glue Data Catalog."
},
{
"code": null,
"e": 1234,
"s": 1165,
"text": "Start the scheduler of a crawler available in AWS Glue Data Catalog."
},
{
"code": null,
"e": 1319,
"s": 1234,
"text": " Problem Statement: Use boto3 library in Python to start the scheduler of a crawler."
},
{
"code": null,
"e": 1386,
"s": 1319,
"text": "Step 1: Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1453,
"s": 1386,
"text": "Step 1: Import boto3 and botocore exceptions to handle exceptions."
},
{
"code": null,
"e": 1518,
"s": 1453,
"text": "Step 2:\ncrawler_name is the required parameter in this function."
},
{
"code": null,
"e": 1583,
"s": 1518,
"text": "Step 2:\ncrawler_name is the required parameter in this function."
},
{
"code": null,
"e": 1778,
"s": 1583,
"text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session."
},
{
"code": null,
"e": 1973,
"s": 1778,
"text": "Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session."
},
{
"code": null,
"e": 2012,
"s": 1973,
"text": "Step 4: Create an AWS client for glue."
},
{
"code": null,
"e": 2051,
"s": 2012,
"text": "Step 4: Create an AWS client for glue."
},
{
"code": null,
"e": 2155,
"s": 2051,
"text": "Step 5: Now use the start_crawler_schedule function and pass the parameter crawler_name as CrawlerName."
},
{
"code": null,
"e": 2259,
"s": 2155,
"text": "Step 5: Now use the start_crawler_schedule function and pass the parameter crawler_name as CrawlerName."
},
{
"code": null,
"e": 2499,
"s": 2259,
"text": "Step 6: It returns the response metadata and sets the schedule state of the crawler as SCHEDULED. If the status of the crawler is running or the schedule state is already SCHEDULED, then it throws the exception - SchedulerRunningException."
},
{
"code": null,
"e": 2739,
"s": 2499,
"text": "Step 6: It returns the response metadata and sets the schedule state of the crawler as SCHEDULED. If the status of the crawler is running or the schedule state is already SCHEDULED, then it throws the exception - SchedulerRunningException."
},
{
"code": null,
"e": 2843,
"s": 2739,
"text": "Step 7: Handle the generic exception if something went wrong while starting the scheduler of a crawler."
},
{
"code": null,
"e": 2947,
"s": 2843,
"text": "Step 7: Handle the generic exception if something went wrong while starting the scheduler of a crawler."
},
{
"code": null,
"e": 3002,
"s": 2947,
"text": "The following code starts the scheduler of a crawler −"
},
{
"code": null,
"e": 3582,
"s": 3002,
"text": "import boto3\nfrom botocore.exceptions import ClientError\n\ndef start_scheduler_of_a_crawler(crawler_name)\n session = boto3.session.Session()\n glue_client = session.client('glue')\n try:\n response = glue_client.start_crawler_schedule(CrawlerName=crawler_name)\n return response\n except ClientError as e:\n raise Exception(\"boto3 client error in start_scheduler_of_a_crawler: \" + e.__str__())\n except Exception as e:\n raise Exception(\"Unexpected error in start_scheduler_of_a_crawler: \" + e.__str__())\nprint(start_scheduler_of_a_crawler(\"Data Dimension\"))"
},
{
"code": null,
"e": 3898,
"s": 3582,
"text": "{'ResponseMetadata': {'RequestId': '73e50130-*****************8e', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 28 Mar 2021 07:26:55 GMT', 'content-type': 'application/x-amz-json-1.1', 'content-length': '2', 'connection': 'keep-alive', 'x-amzn-requestid': '73e50130-***************8e'}, 'RetryAttempts': 0}}"
}
] |
Python os.renames() Method
|
Python method renames() is recursive directory or file renaming function. It does the same functioning as os.rename(), but it also moves a file to a directory, or a whole tree of directories, that do not exist.
Following is the syntax for renames() method −
os.renames(old, new)
old − This is the actual name of the file or directory to be renamed.
old − This is the actual name of the file or directory to be renamed.
new − This is the new name of the file or directory.It can even include a file to a directory, or a whole tree of directories, that do not exist.
new − This is the new name of the file or directory.It can even include a file to a directory, or a whole tree of directories, that do not exist.
This method does not return any value.
The following example shows the usage of renames() method.
# !/usr/bin/python
import os, sys
print "Current directory is: %s" %os.getcwd()
# listing directories
print "The dir is: %s"%os.listdir(os.getcwd())
# renaming file "aa1.txt"
os.renames("aa1.txt","newdir/aanew.txt")
print "Successfully renamed."
# listing directories after renaming and moving "aa1.txt"
print "The dir is: %s" %os.listdir(os.getcwd())
When we run above program, it produces following result −
Current directory is: /tmp
The dir is:
[ 'a1.txt','resume.doc','a3.py','aa1.txt','Administrator','amrood.admin' ]
Successfully renamed.
The dir is:
[ 'a1.txt','resume.doc','a3.py','Administrator','amrood.admin' ]
The file aa1.txt is not visible here, as it is been moved to newdir and renamed as aanew.txt. The directory newdir and its contents are shown below −
[ 'aanew.txt' ]
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2456,
"s": 2244,
"text": "Python method renames() is recursive directory or file renaming function. It does the same functioning as os.rename(), but it also moves a file to a directory, or a whole tree of directories, that do not exist."
},
{
"code": null,
"e": 2503,
"s": 2456,
"text": "Following is the syntax for renames() method −"
},
{
"code": null,
"e": 2525,
"s": 2503,
"text": "os.renames(old, new)\n"
},
{
"code": null,
"e": 2595,
"s": 2525,
"text": "old − This is the actual name of the file or directory to be renamed."
},
{
"code": null,
"e": 2665,
"s": 2595,
"text": "old − This is the actual name of the file or directory to be renamed."
},
{
"code": null,
"e": 2811,
"s": 2665,
"text": "new − This is the new name of the file or directory.It can even include a file to a directory, or a whole tree of directories, that do not exist."
},
{
"code": null,
"e": 2957,
"s": 2811,
"text": "new − This is the new name of the file or directory.It can even include a file to a directory, or a whole tree of directories, that do not exist."
},
{
"code": null,
"e": 2996,
"s": 2957,
"text": "This method does not return any value."
},
{
"code": null,
"e": 3055,
"s": 2996,
"text": "The following example shows the usage of renames() method."
},
{
"code": null,
"e": 3412,
"s": 3055,
"text": "# !/usr/bin/python\n\nimport os, sys\nprint \"Current directory is: %s\" %os.getcwd()\n\n# listing directories\nprint \"The dir is: %s\"%os.listdir(os.getcwd())\n\n# renaming file \"aa1.txt\"\nos.renames(\"aa1.txt\",\"newdir/aanew.txt\")\n\nprint \"Successfully renamed.\"\n\n# listing directories after renaming and moving \"aa1.txt\"\nprint \"The dir is: %s\" %os.listdir(os.getcwd())"
},
{
"code": null,
"e": 3470,
"s": 3412,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 3688,
"s": 3470,
"text": "Current directory is: /tmp\nThe dir is:\n [ 'a1.txt','resume.doc','a3.py','aa1.txt','Administrator','amrood.admin' ]\nSuccessfully renamed.\nThe dir is:\n [ 'a1.txt','resume.doc','a3.py','Administrator','amrood.admin' ]\n"
},
{
"code": null,
"e": 3838,
"s": 3688,
"text": "The file aa1.txt is not visible here, as it is been moved to newdir and renamed as aanew.txt. The directory newdir and its contents are shown below −"
},
{
"code": null,
"e": 3855,
"s": 3838,
"text": "[ 'aanew.txt' ]\n"
},
{
"code": null,
"e": 3892,
"s": 3855,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3908,
"s": 3892,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3941,
"s": 3908,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3960,
"s": 3941,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3995,
"s": 3960,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4017,
"s": 3995,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4051,
"s": 4017,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4079,
"s": 4051,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4114,
"s": 4079,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4128,
"s": 4114,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4161,
"s": 4128,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4178,
"s": 4161,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4185,
"s": 4178,
"text": " Print"
},
{
"code": null,
"e": 4196,
"s": 4185,
"text": " Add Notes"
}
] |
Display the Pandas DataFrame in table style and border around the table and not around the rows - GeeksforGeeks
|
21 Aug, 2020
Let us see how to style a Pandas DataFrame such that it has a border around the table. We will be using the set_table_styles() method of the Styler class in the Pandas module.
Syntax : set_table_styles(self, table_styles)
Parameters :table_styles : List, each individual table_style should be a dictionary with selector and props keys.
Returns : Styler
Example 1 :
# import the moduleimport pandas as pd # create a DataFrame ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting', 'Jayasurya', 'Jayawardene', 'Kohli', 'Haq', 'Kallis', 'Ganguly', 'Dravid'], 'runs': [18426, 14234, 13704, 13430, 12650, 11867, 11739, 11579, 11363, 10889]} df = pd.DataFrame(ODI_runs) # making a yellow borderdf.style.set_table_styles([{'selector' : '', 'props' : [('border', '10px solid yellow')]}])
Output :
Example 2 :
# import the moduleimport pandas as pd # create a DataFrame df = pd.DataFrame({"A":[14, 4, 5, 4, 1], "B":[5, 2, 54, 3, 2], "C":[20, 20, 7, 3, 8], "D":[14, 3, 6, 2, 6]}) # making a green borderdf.style.set_table_styles([{'selector' : '', 'props' : [('border', '2px solid green')]}])
Output :
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 24611,
"s": 24583,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 24787,
"s": 24611,
"text": "Let us see how to style a Pandas DataFrame such that it has a border around the table. We will be using the set_table_styles() method of the Styler class in the Pandas module."
},
{
"code": null,
"e": 24833,
"s": 24787,
"text": "Syntax : set_table_styles(self, table_styles)"
},
{
"code": null,
"e": 24947,
"s": 24833,
"text": "Parameters :table_styles : List, each individual table_style should be a dictionary with selector and props keys."
},
{
"code": null,
"e": 24964,
"s": 24947,
"text": "Returns : Styler"
},
{
"code": null,
"e": 24976,
"s": 24964,
"text": "Example 1 :"
},
{
"code": "# import the moduleimport pandas as pd # create a DataFrame ODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting', 'Jayasurya', 'Jayawardene', 'Kohli', 'Haq', 'Kallis', 'Ganguly', 'Dravid'], 'runs': [18426, 14234, 13704, 13430, 12650, 11867, 11739, 11579, 11363, 10889]} df = pd.DataFrame(ODI_runs) # making a yellow borderdf.style.set_table_styles([{'selector' : '', 'props' : [('border', '10px solid yellow')]}])",
"e": 25543,
"s": 24976,
"text": null
},
{
"code": null,
"e": 25552,
"s": 25543,
"text": "Output :"
},
{
"code": null,
"e": 25564,
"s": 25552,
"text": "Example 2 :"
},
{
"code": "# import the moduleimport pandas as pd # create a DataFrame df = pd.DataFrame({\"A\":[14, 4, 5, 4, 1], \"B\":[5, 2, 54, 3, 2], \"C\":[20, 20, 7, 3, 8], \"D\":[14, 3, 6, 2, 6]}) # making a green borderdf.style.set_table_styles([{'selector' : '', 'props' : [('border', '2px solid green')]}])",
"e": 25976,
"s": 25564,
"text": null
},
{
"code": null,
"e": 25985,
"s": 25976,
"text": "Output :"
},
{
"code": null,
"e": 26009,
"s": 25985,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26032,
"s": 26009,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 26046,
"s": 26032,
"text": "Python-pandas"
},
{
"code": null,
"e": 26053,
"s": 26046,
"text": "Python"
},
{
"code": null,
"e": 26151,
"s": 26053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26160,
"s": 26151,
"text": "Comments"
},
{
"code": null,
"e": 26173,
"s": 26160,
"text": "Old Comments"
},
{
"code": null,
"e": 26191,
"s": 26173,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26226,
"s": 26191,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26248,
"s": 26226,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26280,
"s": 26248,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26310,
"s": 26280,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26353,
"s": 26310,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 26397,
"s": 26353,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26422,
"s": 26397,
"text": "sum() function in Python"
},
{
"code": null,
"e": 26459,
"s": 26422,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to fetch only a single result from a table in Java-MySQL?
|
Let us first create a table −
mysql> create table DemoTable
-> (
-> Id int,
-> Name varchar(20)
-> );
Query OK, 0 rows affected (1.37 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.54 sec)
mysql> insert into DemoTable values(102,'David');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(103,'Mike');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+------+-------+
| Id | Name |
+------+-------+
| 101 | Chris |
| 102 | David |
| 103 | Mike |
+------+-------+
3 rows in set (0.00 sec)
Let us now see the Java-MySQL code. This will fetch only a single record from the top of the table −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import com.mysql.jdbc.ResultSetMetaData;
public class OneResultDemo {
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
Statement st = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/web?useSSL=false", "root", "123456");
String query = "select *from DemoTable " + " limit 1";
st = con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
System.out.println("Id=" + rs.getInt("Id"));
System.out.println("Name=" + rs.getString("Name"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This will produce the following output −
Id=101
Name=Chris
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1213,
"s": 1092,
"text": "mysql> create table DemoTable\n -> (\n -> Id int,\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (1.37 sec)"
},
{
"code": null,
"e": 1269,
"s": 1213,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1526,
"s": 1269,
"text": "mysql> insert into DemoTable values(101,'Chris');\nQuery OK, 1 row affected (0.54 sec)\nmysql> insert into DemoTable values(102,'David');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values(103,'Mike');\nQuery OK, 1 row affected (0.12 sec)"
},
{
"code": null,
"e": 1586,
"s": 1526,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1618,
"s": 1586,
"text": "mysql> select * from DemoTable;"
},
{
"code": null,
"e": 1659,
"s": 1618,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1803,
"s": 1659,
"text": "+------+-------+\n| Id | Name |\n+------+-------+\n| 101 | Chris |\n| 102 | David |\n| 103 | Mike |\n+------+-------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1904,
"s": 1803,
"text": "Let us now see the Java-MySQL code. This will fetch only a single record from the top of the table −"
},
{
"code": null,
"e": 2787,
"s": 1904,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport com.mysql.jdbc.ResultSetMetaData;\npublic class OneResultDemo {\n public static void main(String[] args) {\n Connection con = null;\n PreparedStatement ps = null;\n Statement st = null;\n ResultSet rs = null;\n try {\n con = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/web?useSSL=false\", \"root\", \"123456\");\n String query = \"select *from DemoTable \" + \" limit 1\";\n st = con.createStatement();\n rs = st.executeQuery(query);\n while (rs.next()) {\n System.out.println(\"Id=\" + rs.getInt(\"Id\"));\n System.out.println(\"Name=\" + rs.getString(\"Name\"));\n }\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"code": null,
"e": 2828,
"s": 2787,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2846,
"s": 2828,
"text": "Id=101\nName=Chris"
}
] |
How to Import All Python Libraries With One Line of Code | by Ismael Araujo | Towards Data Science
|
If you are a Data Scientist or are learning how to become one, you know the drill when starting a new Jupyter Notebook project. You import libraries, use some of them, and start working. You will likely get an error message at some point because you forgot to import another library. You stop whatever you were working on, import that specific library, and start working again. Depending on the size of your project, this can happen a few times. It’s also highly likely that you have checked on Google how to import matplotlib.plot.
Yes, you can make your life easier and copy and paste all the packages you will need from another project, but what if I tell you that you can import all your essential packages with one line of code and focus on what is important? The solution is called PyForest. PyForest is a lazy import. As the name says, it imports the most popular Data Science libraries for Python. The PyForest developers aim to import 99% of all the most used libraries.
Sounds great, right? However, what if you don’t use all the libraries? Why would you import all of them? The good news is that PyForest will only import the libraries if you use them. For this reason, there is no reason to worry about slowing down your computer. Since the libraries are not imported unless you use their functions or methods, this is a better solution than copying and pasting code from other projects.
Installation
Now, how to use this magic solution? Just as easy as it gets. Pyforest can be installed from Pypl. You can type the following command on your terminal:
pip install pyforest
If you are on Jupyter Notebook, you can type:
!pip install pyforest
To import, you can use
import pyforest
or
from pyforest import *
These options should work the same way, but you know, Python can be tricky sometimes. If one way doesn’t work, you can always try another. Voilá, you have some of the most important libraries, and you can focus on your project.
But what is actually being imported?
The good news is that the list is long, and to mention a few, it includes Pandas, NumPy, Matplotlib, Seaborn, Sklearn, Keras, NLTK, and the list goes on and on. The coolest part, in my opinion? They use aliases that are standard conventions for Data Scientists, such as importing Pandas as pd and NumPy as np. Life can be effortless!
You can find the complete list of libraries typing lazy_imports() and you will be able to see the full list.
Adding more libraries to PyForest
As we can see, there is a large variety of libraries, and this should cover most of your project. However, some essential libraries are missing. We can quickly fix that by manually adding your favorite libraries. You can try the following steps to add libraries that don’t come initially with PyForest.
First, go to your terminal and type:
pip show pyforest
You will see that the terminal is going to return the location of the PyForest directory. If you are using macOS, you can type Command+Space and paste the directory address. Find the file called _imports.py and add all the libraries you need.
Done! You will now have all your favorites libraries and worry about what matters for your project. I created a micro project — and you can find it here — where I show how I used PyForest without importing anything from other libraries. Remember that if you want to run the Jupyter Notebook, you will have to install PyForest in your environment.
|
[
{
"code": null,
"e": 704,
"s": 171,
"text": "If you are a Data Scientist or are learning how to become one, you know the drill when starting a new Jupyter Notebook project. You import libraries, use some of them, and start working. You will likely get an error message at some point because you forgot to import another library. You stop whatever you were working on, import that specific library, and start working again. Depending on the size of your project, this can happen a few times. It’s also highly likely that you have checked on Google how to import matplotlib.plot."
},
{
"code": null,
"e": 1151,
"s": 704,
"text": "Yes, you can make your life easier and copy and paste all the packages you will need from another project, but what if I tell you that you can import all your essential packages with one line of code and focus on what is important? The solution is called PyForest. PyForest is a lazy import. As the name says, it imports the most popular Data Science libraries for Python. The PyForest developers aim to import 99% of all the most used libraries."
},
{
"code": null,
"e": 1571,
"s": 1151,
"text": "Sounds great, right? However, what if you don’t use all the libraries? Why would you import all of them? The good news is that PyForest will only import the libraries if you use them. For this reason, there is no reason to worry about slowing down your computer. Since the libraries are not imported unless you use their functions or methods, this is a better solution than copying and pasting code from other projects."
},
{
"code": null,
"e": 1584,
"s": 1571,
"text": "Installation"
},
{
"code": null,
"e": 1736,
"s": 1584,
"text": "Now, how to use this magic solution? Just as easy as it gets. Pyforest can be installed from Pypl. You can type the following command on your terminal:"
},
{
"code": null,
"e": 1757,
"s": 1736,
"text": "pip install pyforest"
},
{
"code": null,
"e": 1803,
"s": 1757,
"text": "If you are on Jupyter Notebook, you can type:"
},
{
"code": null,
"e": 1826,
"s": 1803,
"text": "!pip install pyforest "
},
{
"code": null,
"e": 1849,
"s": 1826,
"text": "To import, you can use"
},
{
"code": null,
"e": 1865,
"s": 1849,
"text": "import pyforest"
},
{
"code": null,
"e": 1868,
"s": 1865,
"text": "or"
},
{
"code": null,
"e": 1891,
"s": 1868,
"text": "from pyforest import *"
},
{
"code": null,
"e": 2120,
"s": 1891,
"text": "These options should work the same way, but you know, Python can be tricky sometimes. If one way doesn’t work, you can always try another. Voilá, you have some of the most important libraries, and you can focus on your project."
},
{
"code": null,
"e": 2157,
"s": 2120,
"text": "But what is actually being imported?"
},
{
"code": null,
"e": 2491,
"s": 2157,
"text": "The good news is that the list is long, and to mention a few, it includes Pandas, NumPy, Matplotlib, Seaborn, Sklearn, Keras, NLTK, and the list goes on and on. The coolest part, in my opinion? They use aliases that are standard conventions for Data Scientists, such as importing Pandas as pd and NumPy as np. Life can be effortless!"
},
{
"code": null,
"e": 2600,
"s": 2491,
"text": "You can find the complete list of libraries typing lazy_imports() and you will be able to see the full list."
},
{
"code": null,
"e": 2634,
"s": 2600,
"text": "Adding more libraries to PyForest"
},
{
"code": null,
"e": 2937,
"s": 2634,
"text": "As we can see, there is a large variety of libraries, and this should cover most of your project. However, some essential libraries are missing. We can quickly fix that by manually adding your favorite libraries. You can try the following steps to add libraries that don’t come initially with PyForest."
},
{
"code": null,
"e": 2974,
"s": 2937,
"text": "First, go to your terminal and type:"
},
{
"code": null,
"e": 2992,
"s": 2974,
"text": "pip show pyforest"
},
{
"code": null,
"e": 3235,
"s": 2992,
"text": "You will see that the terminal is going to return the location of the PyForest directory. If you are using macOS, you can type Command+Space and paste the directory address. Find the file called _imports.py and add all the libraries you need."
}
] |
React-Bootstrap Pagination Component - GeeksforGeeks
|
30 Apr, 2021
React-Bootstrap is a front-end framework that was designed keeping react in mind. Pagination Component provides a way for users to switch between pages easily. It is basically a set of presentational components for providing a better UI experience to the user. We can use the following approach in ReactJS to use the react-bootstrap Pagination Component.
Pagination Props:
size: It is used to define the size of all PageItems.
bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS.
PageItem Props:
active: It is used to style the Page items as for the active state.
activeLabel: It is used to indicate the active state by an accessible label.
disabled: It is used to disable the page item component.
href: t is used to provide the href attribute for this element.
onClick: It is a callback function that is triggered when this component is clicked.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap
npm install bootstrap
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install react-bootstrap
npm install bootstrap
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Pagination from 'react-bootstrap/Pagination'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Pagination Component</h4> <Pagination> <Pagination.Prev /> <Pagination.Ellipsis /> <Pagination.Item>{3}</Pagination.Item> <Pagination.Item>{4}</Pagination.Item> <Pagination.Item>{5}</Pagination.Item> <Pagination.Ellipsis /> <Pagination.Next /> </Pagination> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://react-bootstrap.github.io/components/pagination/
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to pass data from one component to other component in ReactJS ?
Re-rendering Components in ReactJS
How to set background images in ReactJS ?
ReactJS useCallback Hook
How to create a table in ReactJS ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 24807,
"s": 24779,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25162,
"s": 24807,
"text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Pagination Component provides a way for users to switch between pages easily. It is basically a set of presentational components for providing a better UI experience to the user. We can use the following approach in ReactJS to use the react-bootstrap Pagination Component."
},
{
"code": null,
"e": 25180,
"s": 25162,
"text": "Pagination Props:"
},
{
"code": null,
"e": 25234,
"s": 25180,
"text": "size: It is used to define the size of all PageItems."
},
{
"code": null,
"e": 25318,
"s": 25234,
"text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS."
},
{
"code": null,
"e": 25334,
"s": 25318,
"text": "PageItem Props:"
},
{
"code": null,
"e": 25402,
"s": 25334,
"text": "active: It is used to style the Page items as for the active state."
},
{
"code": null,
"e": 25479,
"s": 25402,
"text": "activeLabel: It is used to indicate the active state by an accessible label."
},
{
"code": null,
"e": 25536,
"s": 25479,
"text": "disabled: It is used to disable the page item component."
},
{
"code": null,
"e": 25600,
"s": 25536,
"text": "href: t is used to provide the href attribute for this element."
},
{
"code": null,
"e": 25685,
"s": 25600,
"text": "onClick: It is a callback function that is triggered when this component is clicked."
},
{
"code": null,
"e": 25735,
"s": 25685,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 25830,
"s": 25735,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 25894,
"s": 25830,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 25926,
"s": 25894,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 26039,
"s": 25926,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 26139,
"s": 26039,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 26153,
"s": 26139,
"text": "cd foldername"
},
{
"code": null,
"e": 26308,
"s": 26153,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 26413,
"s": 26308,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 26464,
"s": 26413,
"text": "npm install react-bootstrap \nnpm install bootstrap"
},
{
"code": null,
"e": 26516,
"s": 26464,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 26534,
"s": 26516,
"text": "Project Structure"
},
{
"code": null,
"e": 26664,
"s": 26534,
"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": 26671,
"s": 26664,
"text": "App.js"
},
{
"code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import Pagination from 'react-bootstrap/Pagination'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Pagination Component</h4> <Pagination> <Pagination.Prev /> <Pagination.Ellipsis /> <Pagination.Item>{3}</Pagination.Item> <Pagination.Item>{4}</Pagination.Item> <Pagination.Item>{5}</Pagination.Item> <Pagination.Ellipsis /> <Pagination.Next /> </Pagination> </div> );}",
"e": 27255,
"s": 26671,
"text": null
},
{
"code": null,
"e": 27368,
"s": 27255,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 27378,
"s": 27368,
"text": "npm start"
},
{
"code": null,
"e": 27477,
"s": 27378,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 27545,
"s": 27477,
"text": "Reference: https://react-bootstrap.github.io/components/pagination/"
},
{
"code": null,
"e": 27561,
"s": 27545,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 27569,
"s": 27561,
"text": "ReactJS"
},
{
"code": null,
"e": 27586,
"s": 27569,
"text": "Web Technologies"
},
{
"code": null,
"e": 27684,
"s": 27586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27693,
"s": 27684,
"text": "Comments"
},
{
"code": null,
"e": 27706,
"s": 27693,
"text": "Old Comments"
},
{
"code": null,
"e": 27774,
"s": 27706,
"text": "How to pass data from one component to other component in ReactJS ?"
},
{
"code": null,
"e": 27809,
"s": 27774,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 27851,
"s": 27809,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 27876,
"s": 27851,
"text": "ReactJS useCallback Hook"
},
{
"code": null,
"e": 27911,
"s": 27876,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 27967,
"s": 27911,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 28000,
"s": 27967,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28062,
"s": 28000,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28112,
"s": 28062,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to change the owner of a file using Python?
|
You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner:
import pwd
import grp
import os
uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = 'my_folder'
os.chown(path, uid, gid)
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner:"
},
{
"code": null,
"e": 1411,
"s": 1262,
"text": "import pwd\nimport grp\nimport os\nuid = pwd.getpwnam(\"nobody\").pw_uid\ngid = grp.getgrnam(\"nogroup\").gr_gid\npath = 'my_folder'\nos.chown(path, uid, gid)"
}
] |
How to find numbers in an array that are greater than, less than, or equal to a value in java?
|
You can find numbers in an array that are greater than, less than, or equal to a value as:
Live Demo
public class GreaterOrLess {
public static void main(String args[]) {
int value = 65;
int[] myArray = {41, 52, 63, 74, 85, 96 };
System.out.println("Elements of the array that are equal to the given value are::");
for(int i = 0; i<myArray.length; i++) {
if(value==myArray[i]) {
System.out.println("Index ::"+i+" Element::"+myArray[i]);
}
}
System.out.println("Elements of the array that are greater than the given value are::");
for(int i = 0; i<myArray.length; i++) {
if(value<=myArray[i]) {
System.out.println("Index ::"+i+" Element::"+myArray[i]);
}
}
System.out.println("Elements of the array that are less than the given value are::");
for(int i = 0; i<myArray.length; i++) {
if(value>myArray[i]) {
System.out.println("Index ::"+i+" Element::"+myArray[i]);
}
}
}
}
Elements of the array that are equal to the given value are::
Elements of the array that are greater than the given value are::
Index ::3 Element::74
Index ::4 Element::85
Index ::5 Element::96
Elements of the array that are less than the given value are::
Index ::0 Element::41
Index ::1 Element::52
Index ::2 Element::63
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "You can find numbers in an array that are greater than, less than, or equal to a value as:"
},
{
"code": null,
"e": 1163,
"s": 1153,
"text": "Live Demo"
},
{
"code": null,
"e": 2095,
"s": 1163,
"text": "public class GreaterOrLess {\n public static void main(String args[]) {\n int value = 65;\n int[] myArray = {41, 52, 63, 74, 85, 96 };\n System.out.println(\"Elements of the array that are equal to the given value are::\");\n for(int i = 0; i<myArray.length; i++) {\n if(value==myArray[i]) {\n System.out.println(\"Index ::\"+i+\" Element::\"+myArray[i]);\n }\n }\n System.out.println(\"Elements of the array that are greater than the given value are::\");\n for(int i = 0; i<myArray.length; i++) {\n if(value<=myArray[i]) {\n System.out.println(\"Index ::\"+i+\" Element::\"+myArray[i]);\n }\n }\n System.out.println(\"Elements of the array that are less than the given value are::\");\n for(int i = 0; i<myArray.length; i++) {\n if(value>myArray[i]) {\n System.out.println(\"Index ::\"+i+\" Element::\"+myArray[i]);\n }\n }\n }\n}"
},
{
"code": null,
"e": 2418,
"s": 2095,
"text": "Elements of the array that are equal to the given value are::\nElements of the array that are greater than the given value are::\nIndex ::3 Element::74\nIndex ::4 Element::85\nIndex ::5 Element::96\nElements of the array that are less than the given value are::\nIndex ::0 Element::41\nIndex ::1 Element::52\nIndex ::2 Element::63"
}
] |
Quickly Navigating Python Libraries With ctags | by Zach Monge, PhD | Towards Data Science
|
As a machine learning practitioner, I often use open-source machine learning libraries, such as fastai and scikit-learn. After working with these libraries for awhile, you may reach the point where you want to do something that is not currently supported by a library (e.g., create a customized model), but you still may want to use many of the library functions. For example, I use fastai/PyTorch to design and train customized deep learning models. fastai provides a nice framework for reading in the data, so it is often the case I still want to use many fastai components, but with some degree of customization. Or perhaps you are just curious how a certain function works and want to examine the source code. In order to efficiently achieve this level of examination, it’s important that you are able to easily jump around the source code of your machine learning library of choice. Therefore, you need to choose a good code editor and know how to use it well. For users not working in a command line interface, I strongly recommend Visual Studio (VS) Code. VS Code is completely free and has some really great functions. VS Code combined with a programming tool called ctags will allow you to efficiently explore Python libraries. Here, I give a step-by-step tutorial on how to set up ctags in VS Code. It should be noted that this tutorial is designed for Windows users, but it should for the most part generalize well to other operating systems with minor modifications.
A lot of the tips I provide here previously come this blog post and from the fast.ai course, so I would like to thank these authors for laying the groundwork! I also have to admit that I am definitely not an expert at VS Code, so suggestions/comments would be greatly appreciated. Okay lets get started!
First, if you already do not have Python, install Python. I strongly recommend downloading Python through Anaconda.Second, download and install Visual Studio Code. Again, it is completely free and is compatible with either Windows, Linux or Mac, so this should be easy enough!Next, open Visual Studio Code. First, you are going to have to select Python as your interpreter. To do this type Ctrl+Shift+P and start typing “Python: Select Interpreter.” Then select the Python version and environment you want to load. Again, I often use fastai so I select the Python environment for fastai. If “Python: Select Interpreter” is not appearing, this means that Python is not installed on your system. This is an easy fix, so just follow the instructions here.
First, if you already do not have Python, install Python. I strongly recommend downloading Python through Anaconda.
Second, download and install Visual Studio Code. Again, it is completely free and is compatible with either Windows, Linux or Mac, so this should be easy enough!
Next, open Visual Studio Code. First, you are going to have to select Python as your interpreter. To do this type Ctrl+Shift+P and start typing “Python: Select Interpreter.” Then select the Python version and environment you want to load. Again, I often use fastai so I select the Python environment for fastai. If “Python: Select Interpreter” is not appearing, this means that Python is not installed on your system. This is an easy fix, so just follow the instructions here.
4. Now open the folder that contains the Python library that you want to easily explore (e.g., fastai). When you do this, VS Code is going to create a directory there labeled .vscode. This directory contains a JSON file labeled settings.json. Open up the settings.json file in VS Code (or any text editor). We will edit this file in a couple of steps.
5. For Windows users, next, you will need to download the ctags package. Ctags generates an index (or tag) file of names found in source and headers files. This is how we can quickly search through our code, by creating these tags. You can download them from this GitHub site. If you are using Windows, you can click on releases, select the most recent version, and select the zip file to download. Unzip this zip file wherever you like, but I usually just put it in the .vscode directory.
For Linux users, you will need to install exuberant-ctags by typing in the terminal the following line of code
sudo apt-get install exuberant-ctags
6. Remember the settings.json file? Windows users (Linux users skip to step 7), you are going to need to edit it now. Already in the JSON should be a line that specifies the path to the Python executable. Now you are going to need to add a line specifying the path to the ctags.exe file. Create a new line and add the following line of code (replace LIBRARY_PATH with the path to your Python library or wherever you chose to place the ctags.exe file):
"python.workspaceSymbols.ctagsPath": "LIBRARY_PATH\\.vscode\\ctags-2018-11-06_0f27679c-x64\\ctags.exe"
Your settings.json file should look like this:
7. Next, generate the tags! VS Code makes this really easy. For Windows users, all you have to do is type Ctrl + t. This should create a tags file, which contains all of the tags. If this does not work, open up the Terminal is VS Code, go to the Output tab, type Ctrl + t again, and see what the output says. Also, both Windows and Linux users, make sure that Python Workspace Symbols are Enabled, which can either be selected in the settings (see picture below) or by adding the following line of code to your settings.json file:
"python.workspaceSymbols.enabled": true
For Linux users, to generate the tags file, in the terminal make sure you are in the directory of the Python library, and type the following in the terminal:
ctags-exuberant -R -f tags
This will generate the tags file. I typically move this tags file to the .vscode directory. Then, in the settings.json file, you need to specify the path to the tags file by adding the following addition line:
“python.workspaceSymbols.tagFilePath”: “LIBRARY_PATH/.vscode/tags”
8. You can now navigate tags by typing Ctrl + t and typing names of classes and functions you would like to search. Easy enough!
The tags have been created and now are ready to be used. There are many other useful shortcuts in VS Code. Here are a few that I am shamelessly stealing from the fast.ai course:
Command palette: Ctrl-shift-p
Go to symbol: Ctril-t
Find references: Shift-F12
Go to definition: F12
Go back: Alt-left
Go forward: Alt-right
Hide sidebar: Ctrl-b
Zen mode: Ctrl-k,z
I hope you found this useful and comments/suggestions are more than welcome!
|
[
{
"code": null,
"e": 1651,
"s": 172,
"text": "As a machine learning practitioner, I often use open-source machine learning libraries, such as fastai and scikit-learn. After working with these libraries for awhile, you may reach the point where you want to do something that is not currently supported by a library (e.g., create a customized model), but you still may want to use many of the library functions. For example, I use fastai/PyTorch to design and train customized deep learning models. fastai provides a nice framework for reading in the data, so it is often the case I still want to use many fastai components, but with some degree of customization. Or perhaps you are just curious how a certain function works and want to examine the source code. In order to efficiently achieve this level of examination, it’s important that you are able to easily jump around the source code of your machine learning library of choice. Therefore, you need to choose a good code editor and know how to use it well. For users not working in a command line interface, I strongly recommend Visual Studio (VS) Code. VS Code is completely free and has some really great functions. VS Code combined with a programming tool called ctags will allow you to efficiently explore Python libraries. Here, I give a step-by-step tutorial on how to set up ctags in VS Code. It should be noted that this tutorial is designed for Windows users, but it should for the most part generalize well to other operating systems with minor modifications."
},
{
"code": null,
"e": 1955,
"s": 1651,
"text": "A lot of the tips I provide here previously come this blog post and from the fast.ai course, so I would like to thank these authors for laying the groundwork! I also have to admit that I am definitely not an expert at VS Code, so suggestions/comments would be greatly appreciated. Okay lets get started!"
},
{
"code": null,
"e": 2708,
"s": 1955,
"text": "First, if you already do not have Python, install Python. I strongly recommend downloading Python through Anaconda.Second, download and install Visual Studio Code. Again, it is completely free and is compatible with either Windows, Linux or Mac, so this should be easy enough!Next, open Visual Studio Code. First, you are going to have to select Python as your interpreter. To do this type Ctrl+Shift+P and start typing “Python: Select Interpreter.” Then select the Python version and environment you want to load. Again, I often use fastai so I select the Python environment for fastai. If “Python: Select Interpreter” is not appearing, this means that Python is not installed on your system. This is an easy fix, so just follow the instructions here."
},
{
"code": null,
"e": 2824,
"s": 2708,
"text": "First, if you already do not have Python, install Python. I strongly recommend downloading Python through Anaconda."
},
{
"code": null,
"e": 2986,
"s": 2824,
"text": "Second, download and install Visual Studio Code. Again, it is completely free and is compatible with either Windows, Linux or Mac, so this should be easy enough!"
},
{
"code": null,
"e": 3463,
"s": 2986,
"text": "Next, open Visual Studio Code. First, you are going to have to select Python as your interpreter. To do this type Ctrl+Shift+P and start typing “Python: Select Interpreter.” Then select the Python version and environment you want to load. Again, I often use fastai so I select the Python environment for fastai. If “Python: Select Interpreter” is not appearing, this means that Python is not installed on your system. This is an easy fix, so just follow the instructions here."
},
{
"code": null,
"e": 3815,
"s": 3463,
"text": "4. Now open the folder that contains the Python library that you want to easily explore (e.g., fastai). When you do this, VS Code is going to create a directory there labeled .vscode. This directory contains a JSON file labeled settings.json. Open up the settings.json file in VS Code (or any text editor). We will edit this file in a couple of steps."
},
{
"code": null,
"e": 4305,
"s": 3815,
"text": "5. For Windows users, next, you will need to download the ctags package. Ctags generates an index (or tag) file of names found in source and headers files. This is how we can quickly search through our code, by creating these tags. You can download them from this GitHub site. If you are using Windows, you can click on releases, select the most recent version, and select the zip file to download. Unzip this zip file wherever you like, but I usually just put it in the .vscode directory."
},
{
"code": null,
"e": 4416,
"s": 4305,
"text": "For Linux users, you will need to install exuberant-ctags by typing in the terminal the following line of code"
},
{
"code": null,
"e": 4453,
"s": 4416,
"text": "sudo apt-get install exuberant-ctags"
},
{
"code": null,
"e": 4905,
"s": 4453,
"text": "6. Remember the settings.json file? Windows users (Linux users skip to step 7), you are going to need to edit it now. Already in the JSON should be a line that specifies the path to the Python executable. Now you are going to need to add a line specifying the path to the ctags.exe file. Create a new line and add the following line of code (replace LIBRARY_PATH with the path to your Python library or wherever you chose to place the ctags.exe file):"
},
{
"code": null,
"e": 5008,
"s": 4905,
"text": "\"python.workspaceSymbols.ctagsPath\": \"LIBRARY_PATH\\\\.vscode\\\\ctags-2018-11-06_0f27679c-x64\\\\ctags.exe\""
},
{
"code": null,
"e": 5055,
"s": 5008,
"text": "Your settings.json file should look like this:"
},
{
"code": null,
"e": 5586,
"s": 5055,
"text": "7. Next, generate the tags! VS Code makes this really easy. For Windows users, all you have to do is type Ctrl + t. This should create a tags file, which contains all of the tags. If this does not work, open up the Terminal is VS Code, go to the Output tab, type Ctrl + t again, and see what the output says. Also, both Windows and Linux users, make sure that Python Workspace Symbols are Enabled, which can either be selected in the settings (see picture below) or by adding the following line of code to your settings.json file:"
},
{
"code": null,
"e": 5626,
"s": 5586,
"text": "\"python.workspaceSymbols.enabled\": true"
},
{
"code": null,
"e": 5784,
"s": 5626,
"text": "For Linux users, to generate the tags file, in the terminal make sure you are in the directory of the Python library, and type the following in the terminal:"
},
{
"code": null,
"e": 5811,
"s": 5784,
"text": "ctags-exuberant -R -f tags"
},
{
"code": null,
"e": 6021,
"s": 5811,
"text": "This will generate the tags file. I typically move this tags file to the .vscode directory. Then, in the settings.json file, you need to specify the path to the tags file by adding the following addition line:"
},
{
"code": null,
"e": 6088,
"s": 6021,
"text": "“python.workspaceSymbols.tagFilePath”: “LIBRARY_PATH/.vscode/tags”"
},
{
"code": null,
"e": 6217,
"s": 6088,
"text": "8. You can now navigate tags by typing Ctrl + t and typing names of classes and functions you would like to search. Easy enough!"
},
{
"code": null,
"e": 6395,
"s": 6217,
"text": "The tags have been created and now are ready to be used. There are many other useful shortcuts in VS Code. Here are a few that I am shamelessly stealing from the fast.ai course:"
},
{
"code": null,
"e": 6425,
"s": 6395,
"text": "Command palette: Ctrl-shift-p"
},
{
"code": null,
"e": 6447,
"s": 6425,
"text": "Go to symbol: Ctril-t"
},
{
"code": null,
"e": 6474,
"s": 6447,
"text": "Find references: Shift-F12"
},
{
"code": null,
"e": 6496,
"s": 6474,
"text": "Go to definition: F12"
},
{
"code": null,
"e": 6514,
"s": 6496,
"text": "Go back: Alt-left"
},
{
"code": null,
"e": 6536,
"s": 6514,
"text": "Go forward: Alt-right"
},
{
"code": null,
"e": 6557,
"s": 6536,
"text": "Hide sidebar: Ctrl-b"
},
{
"code": null,
"e": 6576,
"s": 6557,
"text": "Zen mode: Ctrl-k,z"
}
] |
HTML <option> selected Attribute
|
The selected attribute in the <option> element pre-selects an option when the page loads. The same option would be visible.
Following is the syntax −
<option selected>
Let us now see an example to implement the selected attribute of the <option> element −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h1>Educational Qualification</h1>
<h2>Postgraduation</h2>
<select>
<option value="mca">MCA</option>
<option value="mcom">M.COM</option>
<option value="mtech" selected>M.TECH</option>
<option value="msc">M.Sc</option>
</select>
</body>
</html>
In the above example, we have a <select> to set a drop-down list:
<select>
<option value="mca">MCA</option>
<option value="mcom">M.COM</option>
<option value="mtech" selected>M.TECH</option>
<option value="msc">M.Sc</option>
</select>
In that, different options are set with <option> element −
<option value="mca">MCA</option>
<option value="mcom">M.COM</option>
<option value="mtech" selected>M.TECH</option>
<option value="msc">M.Sc</option>
We have set the default visible option when the page loads using the selected attribute −
<option value="mtech" selected>M.TECH</option>
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "The selected attribute in the <option> element pre-selects an option when the page loads. The same option would be visible."
},
{
"code": null,
"e": 1212,
"s": 1186,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1230,
"s": 1212,
"text": "<option selected>"
},
{
"code": null,
"e": 1318,
"s": 1230,
"text": "Let us now see an example to implement the selected attribute of the <option> element −"
},
{
"code": null,
"e": 1329,
"s": 1318,
"text": " Live Demo"
},
{
"code": null,
"e": 1615,
"s": 1329,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h1>Educational Qualification</h1>\n<h2>Postgraduation</h2>\n<select>\n <option value=\"mca\">MCA</option>\n <option value=\"mcom\">M.COM</option>\n <option value=\"mtech\" selected>M.TECH</option>\n <option value=\"msc\">M.Sc</option>\n</select>\n</body>\n</html>"
},
{
"code": null,
"e": 1681,
"s": 1615,
"text": "In the above example, we have a <select> to set a drop-down list:"
},
{
"code": null,
"e": 1850,
"s": 1681,
"text": "<select>\n<option value=\"mca\">MCA</option>\n<option value=\"mcom\">M.COM</option>\n<option value=\"mtech\" selected>M.TECH</option>\n<option value=\"msc\">M.Sc</option>\n</select>"
},
{
"code": null,
"e": 1909,
"s": 1850,
"text": "In that, different options are set with <option> element −"
},
{
"code": null,
"e": 2059,
"s": 1909,
"text": "<option value=\"mca\">MCA</option>\n<option value=\"mcom\">M.COM</option>\n<option value=\"mtech\" selected>M.TECH</option>\n<option value=\"msc\">M.Sc</option>"
},
{
"code": null,
"e": 2149,
"s": 2059,
"text": "We have set the default visible option when the page loads using the selected attribute −"
},
{
"code": null,
"e": 2196,
"s": 2149,
"text": "<option value=\"mtech\" selected>M.TECH</option>"
}
] |
How to Play Video from URL in Android?
|
18 Jul, 2021
In this article, you will see how to play a video from URL on Android. For showing the video in our android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can play media files from the local storage and also from the internet. A sample GIF 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 Java language.
Now let’s see the step-by-step implementation of the above application shown in the gif.
Step 1: Create a new project
So the first step is to create a new project, On the Welcome screen of Android Studio, click on Create New Project and If you have a project already opened, Go to File > New > New Project. Then select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field and select Java from the Language drop-down menu.
Step 2: Add the Internet Permission
Navigate to app > manifest > AndroidManifest.xml and the internet permission to that file as shown below.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Working with the activity_main.xml
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- adding VideoView to the layout --> <VideoView android:id="@+id/videoView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" /> </RelativeLayout>
Step 4: Working with the MainActivity.java
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.net.Uri;import android.os.Bundle;import android.widget.MediaController;import android.widget.VideoView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Your Video URL String videoUrl = "https://media.geeksforgeeks.org/wp-content/uploads/20201217192146/Screenrecorder-2020-12-17-19-17-36-828.mp4?_=1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // finding videoview by its id VideoView videoView = findViewById(R.id.videoView); // Uri object to refer the // resource from the videoUrl Uri uri = Uri.parse(videoUrl); // sets the resource from the // videoUrl to the videoView videoView.setVideoURI(uri); // creating object of // media controller class MediaController mediaController = new MediaController(this); // sets the anchor view // anchor view for the videoView mediaController.setAnchorView(videoView); // sets the media player to the videoView mediaController.setMediaPlayer(videoView); // sets the media controller to the videoView videoView.setMediaController(mediaController); // starts the video videoView.start(); }}
Output:
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 558,
"s": 28,
"text": "In this article, you will see how to play a video from URL on Android. For showing the video in our android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can play media files from the local storage and also from the internet. A sample GIF 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 Java language. "
},
{
"code": null,
"e": 647,
"s": 558,
"text": "Now let’s see the step-by-step implementation of the above application shown in the gif."
},
{
"code": null,
"e": 676,
"s": 647,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 1030,
"s": 676,
"text": "So the first step is to create a new project, On the Welcome screen of Android Studio, click on Create New Project and If you have a project already opened, Go to File > New > New Project. Then select a Project Template window, select Empty Activity and click Next. Enter your App Name in the Name field and select Java from the Language drop-down menu."
},
{
"code": null,
"e": 1066,
"s": 1030,
"text": "Step 2: Add the Internet Permission"
},
{
"code": null,
"e": 1172,
"s": 1066,
"text": "Navigate to app > manifest > AndroidManifest.xml and the internet permission to that file as shown below."
},
{
"code": null,
"e": 1234,
"s": 1172,
"text": "<uses-permission android:name=\"android.permission.INTERNET\"/>"
},
{
"code": null,
"e": 1277,
"s": 1234,
"text": "Step 3: Working with the activity_main.xml"
},
{
"code": null,
"e": 1420,
"s": 1277,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 1424,
"s": 1420,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- adding VideoView to the layout --> <VideoView android:id=\"@+id/videoView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_centerInParent=\"true\" /> </RelativeLayout>",
"e": 1951,
"s": 1424,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1951,
"text": "Step 4: Working with the MainActivity.java"
},
{
"code": null,
"e": 2184,
"s": 1994,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 2189,
"s": 2184,
"text": "Java"
},
{
"code": "import android.net.Uri;import android.os.Bundle;import android.widget.MediaController;import android.widget.VideoView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Your Video URL String videoUrl = \"https://media.geeksforgeeks.org/wp-content/uploads/20201217192146/Screenrecorder-2020-12-17-19-17-36-828.mp4?_=1\"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // finding videoview by its id VideoView videoView = findViewById(R.id.videoView); // Uri object to refer the // resource from the videoUrl Uri uri = Uri.parse(videoUrl); // sets the resource from the // videoUrl to the videoView videoView.setVideoURI(uri); // creating object of // media controller class MediaController mediaController = new MediaController(this); // sets the anchor view // anchor view for the videoView mediaController.setAnchorView(videoView); // sets the media player to the videoView mediaController.setMediaPlayer(videoView); // sets the media controller to the videoView videoView.setMediaController(mediaController); // starts the video videoView.start(); }}",
"e": 3630,
"s": 2189,
"text": null
},
{
"code": null,
"e": 3638,
"s": 3630,
"text": "Output:"
},
{
"code": null,
"e": 3646,
"s": 3638,
"text": "Android"
},
{
"code": null,
"e": 3651,
"s": 3646,
"text": "Java"
},
{
"code": null,
"e": 3656,
"s": 3651,
"text": "Java"
},
{
"code": null,
"e": 3664,
"s": 3656,
"text": "Android"
}
] |
Adding Tags Using Django-Taggit in Django Project
|
18 Apr, 2022
Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project
Installing django-taggit
pip install django-taggit
ADD it to Main Project’s settings.py file
Python3
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'taggit']
Changes To models.py file
Add TaggableManager in your post, blog, article modal
Python3
from django.db import modelsfrom django.utils.timezone import nowfrom taggit.managers import TaggableManager class Post(models.Model): postid = models.AutoField(primary_key=True) title = models.CharField(max_length=255) content = models.TextField() author = models.CharField(max_length=100) postauthor = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) category = models.CharField(max_length=200) timestamp = models.DateTimeField(default=now, blank=True) tags = TaggableManager()
After adding TaggableManager run following commands in terminal
python manage.py makemigrationspython manage.py migrate
The TaggableManager will show up automatically as a field in post modal
The Taggit Modal will also appear automatically as a separate modal in admin panel
Taggit Modal In Admin Panel
Adding tags
1) If the tags input doesn’t contain any commas or double quotes, it will be taken as space-delimited list of tag names.
geeks for geeks => "geeks", "for", "geeks"
2) If the tags input does contain commas or double quotes then :
a) geeks, geeks for geeks => "geeks", "geeks for geeks"
b) "geeks, forgeeks" geek geeksfor => "geeks, forgeeks", "geek", "geeksfor"
c) "geeks, forgeeks", geek geeksfor => "geeks, forgeeks", "geeks geeksfor"
d) geeks "for" geeks => "geeks", "for", "geeks"
After Adding Tags to the posts the taggit modal will look like :
All the tags which are associated with different posts will appear in tags modal under taggit
On clicking the particular tag, There will come a list of all the posts associated with that particular tag. Now this model can be used with the project like other models
sagar0719kumar
rkbhola5
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 253,
"s": 52,
"text": "Django-Taggit is a Django application which is used to add tags to blogs, articles etc. It makes very easy for us to make adding the tags functionality to our django project.Setting up Django Project "
},
{
"code": null,
"e": 280,
"s": 253,
"text": "Installing django-taggit "
},
{
"code": null,
"e": 306,
"s": 280,
"text": "pip install django-taggit"
},
{
"code": null,
"e": 350,
"s": 306,
"text": "ADD it to Main Project’s settings.py file "
},
{
"code": null,
"e": 358,
"s": 350,
"text": "Python3"
},
{
"code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'taggit']",
"e": 600,
"s": 358,
"text": null
},
{
"code": null,
"e": 628,
"s": 600,
"text": "Changes To models.py file "
},
{
"code": null,
"e": 682,
"s": 628,
"text": "Add TaggableManager in your post, blog, article modal"
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Python3"
},
{
"code": "from django.db import modelsfrom django.utils.timezone import nowfrom taggit.managers import TaggableManager class Post(models.Model): postid = models.AutoField(primary_key=True) title = models.CharField(max_length=255) content = models.TextField() author = models.CharField(max_length=100) postauthor = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(unique=True) category = models.CharField(max_length=200) timestamp = models.DateTimeField(default=now, blank=True) tags = TaggableManager()",
"e": 1235,
"s": 690,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1235,
"text": "After adding TaggableManager run following commands in terminal"
},
{
"code": null,
"e": 1355,
"s": 1299,
"text": "python manage.py makemigrationspython manage.py migrate"
},
{
"code": null,
"e": 1429,
"s": 1355,
"text": "The TaggableManager will show up automatically as a field in post modal "
},
{
"code": null,
"e": 1515,
"s": 1431,
"text": "The Taggit Modal will also appear automatically as a separate modal in admin panel "
},
{
"code": null,
"e": 1545,
"s": 1517,
"text": "Taggit Modal In Admin Panel"
},
{
"code": null,
"e": 1562,
"s": 1549,
"text": "Adding tags "
},
{
"code": null,
"e": 1685,
"s": 1562,
"text": "1) If the tags input doesn’t contain any commas or double quotes, it will be taken as space-delimited list of tag names. "
},
{
"code": null,
"e": 1728,
"s": 1685,
"text": "geeks for geeks => \"geeks\", \"for\", \"geeks\""
},
{
"code": null,
"e": 1795,
"s": 1728,
"text": "2) If the tags input does contain commas or double quotes then : "
},
{
"code": null,
"e": 2097,
"s": 1795,
"text": " \na) geeks, geeks for geeks => \"geeks\", \"geeks for geeks\" \nb) \"geeks, forgeeks\" geek geeksfor => \"geeks, forgeeks\", \"geek\", \"geeksfor\"\nc) \"geeks, forgeeks\", geek geeksfor => \"geeks, forgeeks\", \"geeks geeksfor\"\nd) geeks \"for\" geeks => \"geeks\", \"for\", \"geeks\""
},
{
"code": null,
"e": 2164,
"s": 2099,
"text": "After Adding Tags to the posts the taggit modal will look like :"
},
{
"code": null,
"e": 2260,
"s": 2166,
"text": "All the tags which are associated with different posts will appear in tags modal under taggit"
},
{
"code": null,
"e": 2433,
"s": 2262,
"text": "On clicking the particular tag, There will come a list of all the posts associated with that particular tag. Now this model can be used with the project like other models"
},
{
"code": null,
"e": 2450,
"s": 2435,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2459,
"s": 2450,
"text": "rkbhola5"
},
{
"code": null,
"e": 2473,
"s": 2459,
"text": "Python Django"
},
{
"code": null,
"e": 2480,
"s": 2473,
"text": "Python"
}
] |
DIFFERENCE() Function in SQL Server
|
13 Oct, 2020
The DIFFERENCE() function compares two different SOUNDEX values, and return the value of the integer. This value measures the degree that the SOUNDEX values match, on a scale of 0 to 4. A value of 0 indicates a weak or no similarity between the SOUNDEX values; 4 indicates that the SOUNDEX values are extremely similar, or even identical.
Syntax :
DIFFERENCE(string, string)
Parameter : This method accepts two-parameters as mentioned above and described below –
string, string –It is an alphanumeric expression of character data. It can be a constant, variable, or column.
Returns : It returns an integer value measuring the difference between the SOUNDEX() values of two different string.
Example-1 :Using DIFFERENCE() function with similar SOUNDEX() values.
SELECT SOUNDEX('poor') soundex_poor, SOUNDEX('pour') soundex_pour,
DIFFERENCE('poor', 'pour') similarity;
Output :
Example-2 :Returns a DIFFERENCE value of 3, the less possible difference.
SELECT SOUNDEX('GeeksForGeeks'), SOUNDEX('GeeksOfGeeks'),
DIFFERENCE('GeeksForGeeks', 'GeeksOfGeeks');
Output :
3
Example-3 :Returns a DIFFERENCE value of 2, the medium possible difference.
SELECT SOUNDEX('GeeksForGeeks') soundex_GeeksForGeeks, SOUNDEX('GFG') soundex_GFG,
DIFFERENCE('GeeksForGeeks', 'GFG') similarity;
Output :
Example-4 :Returns a DIFFERENCE value of 0, the highest possible difference.
SELECT SOUNDEX('javascript') soundex_javascript, SOUNDEX('c#') soundex_c#,
DIFFERENCE('javascript', 'c#') similarity;
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Oct, 2020"
},
{
"code": null,
"e": 367,
"s": 28,
"text": "The DIFFERENCE() function compares two different SOUNDEX values, and return the value of the integer. This value measures the degree that the SOUNDEX values match, on a scale of 0 to 4. A value of 0 indicates a weak or no similarity between the SOUNDEX values; 4 indicates that the SOUNDEX values are extremely similar, or even identical."
},
{
"code": null,
"e": 376,
"s": 367,
"text": "Syntax :"
},
{
"code": null,
"e": 403,
"s": 376,
"text": "DIFFERENCE(string, string)"
},
{
"code": null,
"e": 491,
"s": 403,
"text": "Parameter : This method accepts two-parameters as mentioned above and described below –"
},
{
"code": null,
"e": 602,
"s": 491,
"text": "string, string –It is an alphanumeric expression of character data. It can be a constant, variable, or column."
},
{
"code": null,
"e": 719,
"s": 602,
"text": "Returns : It returns an integer value measuring the difference between the SOUNDEX() values of two different string."
},
{
"code": null,
"e": 789,
"s": 719,
"text": "Example-1 :Using DIFFERENCE() function with similar SOUNDEX() values."
},
{
"code": null,
"e": 896,
"s": 789,
"text": "SELECT SOUNDEX('poor') soundex_poor, SOUNDEX('pour') soundex_pour, \nDIFFERENCE('poor', 'pour') similarity;"
},
{
"code": null,
"e": 905,
"s": 896,
"text": "Output :"
},
{
"code": null,
"e": 979,
"s": 905,
"text": "Example-2 :Returns a DIFFERENCE value of 3, the less possible difference."
},
{
"code": null,
"e": 1082,
"s": 979,
"text": "SELECT SOUNDEX('GeeksForGeeks'), SOUNDEX('GeeksOfGeeks'),\nDIFFERENCE('GeeksForGeeks', 'GeeksOfGeeks');"
},
{
"code": null,
"e": 1091,
"s": 1082,
"text": "Output :"
},
{
"code": null,
"e": 1093,
"s": 1091,
"text": "3"
},
{
"code": null,
"e": 1169,
"s": 1093,
"text": "Example-3 :Returns a DIFFERENCE value of 2, the medium possible difference."
},
{
"code": null,
"e": 1299,
"s": 1169,
"text": "SELECT SOUNDEX('GeeksForGeeks') soundex_GeeksForGeeks, SOUNDEX('GFG') soundex_GFG,\nDIFFERENCE('GeeksForGeeks', 'GFG') similarity;"
},
{
"code": null,
"e": 1308,
"s": 1299,
"text": "Output :"
},
{
"code": null,
"e": 1385,
"s": 1308,
"text": "Example-4 :Returns a DIFFERENCE value of 0, the highest possible difference."
},
{
"code": null,
"e": 1503,
"s": 1385,
"text": "SELECT SOUNDEX('javascript') soundex_javascript, SOUNDEX('c#') soundex_c#,\nDIFFERENCE('javascript', 'c#') similarity;"
},
{
"code": null,
"e": 1512,
"s": 1503,
"text": "Output :"
},
{
"code": null,
"e": 1521,
"s": 1512,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1532,
"s": 1521,
"text": "SQL-Server"
},
{
"code": null,
"e": 1536,
"s": 1532,
"text": "SQL"
},
{
"code": null,
"e": 1540,
"s": 1536,
"text": "SQL"
}
] |
Longest Repeated Subsequence
|
10 May, 2022
Given a string, print the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., any i’th character in the two subsequences shouldn’t have the same index in the original string.
Examples:
Input: str = "aabb"
Output: "ab"
Input: str = "aab"
Output: "a"
The two subsequence are 'a'(first) and 'a'
(second). Note that 'b' cannot be considered
as part of subsequence as it would be at same
index in both.
This problem is just the modification of Longest Common Subsequence problem. The idea is to find the LCS(str, str) where str is the input string with the restriction that when both the characters are same, they shouldn’t be on the same index in the two strings. We have discussed a solution to find length of the longest repeated subsequence.
C++
Java
Python3
C#
PHP
Javascript
// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.int findLongestRepeatingSubSeq(string str){ int n = str.length(); // Create and initialize DP table int dp[n+1][n+1]; //initializing first row and column in dp table for(int i=0;i<=n;i++){ dp[i][0] =0; dp[0][i] =0; } // Fill dp table (similar to LCS loops) for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { // If characters match and indexes are // not same if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i-1][j-1]; // If characters do not match else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); } } return dp[n][n];}
// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static int findLongestRepeatingSubSeq(String str){ int n = str.length(); // Create and initialize DP table int dp[][] = new int[n+1][n+1]; for (int i=0; i<=n; i++) for (int j=0; j<=n; j++) dp[i][j] = 0; // Fill dp table (similar to LCS loops) for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { // If characters match and indexes are // not same if (str.charAt(i-1)== str.charAt(j-1) && i != j) dp[i][j] = 1 + dp[i-1][j-1]; // If characters do not match else dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]); } } return dp[n][n];}
# Python method for Longest Repeated# Subsequence # Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/# for complete code.# This function mainly returns LCS(str, str)# with a condition that same characters at# same index are not considered.def findLongestRepeatingSubSeq(str): n = len(str) # Create and initialize DP table dp = [[0 for k in range(n+1)] for l in range(n+1)] # Fill dp table (similar to LCS loops) for i in range(1, n+1): for j in range(1, n+1): # If characters match and indices are not same if (str[i-1] == str[j-1] and i != j): dp[i][j] = 1 + dp[i-1][j-1] # If characters do not match else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) return dp[n][n] # This code is contributed by Soumen Ghosh
// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static int findLongestRepeatingSubSeq(String str){ int n = str.Length; // Create and initialize DP table int [,]dp = new int[n+1,n+1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dp[i, j] = 0; // Fill dp table (similar to LCS loops) for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // If characters match and indexes are // not same if (str[i-1]== str[j-1] && i != j) dp[i, j] = 1 + dp[i-1, j-1]; // If characters do not match else dp[i,j] = Math.Max(dp[i, j-1], dp[i-1, j]); } } return dp[n, n];} // This code is contributed by 29AjayKumar
<?php// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.function findLongestRepeatingSubSeq($str){ $n = strlen($str); // Create and initialize DP table $dp = array_fill(0, $n + 1, array_fill(0, $n + 1, NULL)); for ($i = 0; $i <= $n; $i++) for ($j = 0; $j <= $n; $j++) $dp[$i][$j] = 0; // Fill dp table (similar to LCS loops) for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { // If characters match and indexes // are not same if ($str[$i - 1] == $str[$j - 1] && $i != $j) $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1]; // If characters do not match else $dp[$i][$j] = max($dp[$i][$j - 1], $dp[$i - 1][$j]); } } return $dp[$n][$n];} // This code is contributed by ita_c?>
<script>// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered. function findLongestRepeatingSubSeq(str) { let n = str.length; // Create and initialize DP table let dp = new Array(n+1); for (let i = 0; i <= n; i++) { dp[i] = new Array(n+1); for (let j = 0; j <= n; j++) dp[i][j] = 0; } // Fill dp table (similar to LCS loops) for (let i = 1; i <= n; i++) { for (let j = 1; j <= n; j++) { // If characters match and indexes are // not same if (str[i - 1] == str[j - 1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1]; // If characters do not match else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); } } return dp[n][n]; } // This code is contributed by avanitrachhadiya2155</script>
Time Complexity: O(n^2)How to print the subsequence? The above solution only finds length of subsequence. We can print the subsequence using dp[n+1][n+1] table built. The idea is similar to printing LCS.
// Pseudo code to find longest repeated
// subsequence using the dp[][] table filled
// above.
// Initialize result
string res = "";
// Traverse dp[][] from bottom right
i = n, j = n;
while (i > 0 && j > 0)
{
// If this cell is same as diagonally
// adjacent cell just above it, then
// same characters are present at
// str[i-1] and str[j-1]. Append any
// of them to result.
if (dp[i][j] == dp[i-1][j-1] + 1)
{
res = res + str[i-1];
i--;
j--;
}
// Otherwise we move to the side
// that gave us maximum result
else if (dp[i][j] == dp[i-1][j])
i--;
else
j--;
}
// Since we traverse dp[][] from bottom,
// we get result in reverse order.
reverse(res.begin(), res.end());
return res;
Below is implementation of above steps.
C++
Java
Python3
PHP
C#
Javascript
// C++ program to find the longest repeated// subsequence#include <bits/stdc++.h>using namespace std; // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.string longestRepeatedSubSeq(string str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.length(); int dp[n+1][n+1]; for (int i=0; i<=n; i++) for (int j=0; j<=n; j++) dp[i][j] = 0; for (int i=1; i<=n; i++) for (int j=1; j<=n; j++) if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i-1][j-1]; else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); // THIS PART OF CODE FINDS THE RESULT STRING USING DP[][] // Initialize result string res = ""; // Traverse dp[][] from bottom right int i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i-1][j-1] + 1) { res = res + str[i-1]; i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i][j] == dp[i-1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. reverse(res.begin(), res.end()); return res;} // Driver Programint main(){ string str = "AABEBCDD"; cout << longestRepeatedSubSeq(str); return 0;}
// Java program to find the longest repeated// subsequenceimport java.util.*; class GFG{ // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static String longestRepeatedSubSeq(String str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.length(); int[][] dp = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dp[i][j] = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (str.charAt(i - 1) == str.charAt(j - 1) && i != j) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); // THIS PART OF CODE FINDS // THE RESULT STRING USING DP[][] // Initialize result String res = ""; // Traverse dp[][] from bottom right int i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i - 1][j - 1] + 1) { res = res + str.charAt(i - 1); i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i][j] == dp[i - 1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. String reverse = ""; for(int k = res.length() - 1; k >= 0; k--) { reverse = reverse + res.charAt(k); } return reverse;} // Driver codepublic static void main(String args[]){ String str = "AABEBCDD"; System.out.println(longestRepeatedSubSeq(str));}} // This code is contributed by// Surendra_Gangwar
# Python3 program to find the# longest repeated subsequence # This function mainly returns LCS(str, str)# with a condition that same characters# at same index are not considered.def longestRepeatedSubSeq(str): # This part of code is same as # below post it fills dp[][] # https://www.geeksforgeeks.org/longest-repeating-subsequence/ # OR the code mentioned above n = len(str) dp = [[0 for i in range(n+1)] for j in range(n+1)] for i in range(1, n + 1): for j in range(1, n + 1): if (str[i-1] == str[j-1] and i != j): dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) # This part of code finds the result # string using dp[][] Initialize result res = '' # Traverse dp[][] from bottom right i = n j = n while (i > 0 and j > 0): # If this cell is same as diagonally # adjacent cell just above it, then # same characters are present at # str[i-1] and str[j-1]. Append any # of them to result. if (dp[i][j] == dp[i-1][j-1] + 1): res += str[i-1] i -= 1 j -= 1 # Otherwise we move to the side # that gave us maximum result. elif (dp[i][j] == dp[i-1][j]): i -= 1 else: j -= 1 # Since we traverse dp[][] from bottom, # we get result in reverse order. res = ''.join(reversed(res)) return res # Driver Programstr = 'AABEBCDD'print(longestRepeatedSubSeq(str)) # This code is contributed by Soumen Ghosh
<?php// Php program to find the longest repeated// subsequence // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.function longestRepeatedSubSeq($str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. $n = strlen($str); $dp = array(array()); for ($i = 0; $i <= $n; $i++) for ($j = 0; $j <= $n; $j++) $dp[$i][$j] = 0; for ($i = 1; $i <= $n; $i++) for ($j = 1; $j <= $n; $j++) if ($str[$i - 1] == $str[$j - 1] && $i != $j) $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1]; else $dp[$i][$j] = max($dp[$i][$j - 1], $dp[$i - 1][$j]); // THIS PART OF CODE FINDS THE RESULT // STRING USING DP[][], Initialize result $res = ""; // Traverse dp[][] from bottom right $i = $n; $j = $n; while ($i > 0 && $j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if ($dp[$i][$j] == $dp[$i - 1][$j - 1] + 1) { $res = $res.$str[$i - 1]; $i--; $j--; } // Otherwise we move to the side // that gave us maximum result else if ($dp[$i][$j] == $dp[$i - 1][$j]) $i--; else $j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. return strrev($res) ;} // Driver Code$str = "AABEBCDD";echo longestRepeatedSubSeq($str); // This code is contributed by Ryuga?>
// C# program to find the longest repeated// subsequenceusing System;using System.Collections.Generic; class GFG{ // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static String longestRepeatedSubSeq(String str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[,] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.Length,i,j; int[,] dp = new int[n + 1,n + 1]; for (i = 0; i <= n; i++) for (j = 0; j <= n; j++) dp[i, j] = 0; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) if (str[i - 1] == str[j - 1] && i != j) dp[i, j] = 1 + dp[i - 1, j - 1]; else dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]); // THIS PART OF CODE FINDS // THE RESULT STRING USING DP[,] // Initialize result String res = ""; // Traverse dp[,] from bottom right i = n; j= n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i, j] == dp[i - 1,j - 1] + 1) { res = res + str[i - 1]; i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i,j] == dp[i - 1,j]) i--; else j--; } // Since we traverse dp[,] from bottom, // we get result in reverse order. String reverse = ""; for(int k = res.Length - 1; k >= 0; k--) { reverse = reverse + res[k]; } return reverse;} // Driver codepublic static void Main(String []args){ String str = "AABEBCDD"; Console.WriteLine(longestRepeatedSubSeq(str));}} // This code is contributed by Princi Singh
<script> // Javascript program to find the longest repeated// subsequence // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered. function longestRepeatedSubSeq(str) { // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating- subsequence/ // OR the code mentioned above. let n = str.length; let dp = new Array(n + 1); for (let i = 0; i <= n; i++) { dp[i]=new Array(n+1); for (let j = 0; j <= n; j++) dp[i][j] = 0; } for (let i = 1; i <= n; i++) for (let j = 1; j <= n; j++) if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); // THIS PART OF CODE FINDS // THE RESULT STRING USING DP[][] // Initialize result let res = ""; // Traverse dp[][] from bottom right let i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i - 1][j - 1] + 1) { res = res + str[i-1]; i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i][j] == dp[i - 1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. let reverse = ""; for(let k = res.length - 1; k >= 0; k--) { reverse = reverse + res[k]; } return reverse; } // Driver code let str = "AABEBCDD"; document.write(longestRepeatedSubSeq(str)); // This code is contributed by rag2127 </script>
Output:
ABD
Time Complexity : O(n2) Auxiliary Space : O(n2)This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ankthon
princiraj1992
29AjayKumar
ukasp
gfg_sal_gfg
SURENDRA_GANGWAR
princi singh
Akanksha_Rai
vivekdusad55
avanitrachhadiya2155
rag2127
saurabh1990aror
sagartomar9927
LCS
Dynamic Programming
Dynamic Programming
LCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "Given a string, print the longest repeating subsequence such that the two subsequence don’t have same string character at same position, i.e., any i’th character in the two subsequences shouldn’t have the same index in the original string. "
},
{
"code": null,
"e": 306,
"s": 295,
"text": "Examples: "
},
{
"code": null,
"e": 522,
"s": 306,
"text": "Input: str = \"aabb\"\nOutput: \"ab\"\n\nInput: str = \"aab\"\nOutput: \"a\"\nThe two subsequence are 'a'(first) and 'a' \n(second). Note that 'b' cannot be considered \nas part of subsequence as it would be at same\nindex in both."
},
{
"code": null,
"e": 866,
"s": 522,
"text": "This problem is just the modification of Longest Common Subsequence problem. The idea is to find the LCS(str, str) where str is the input string with the restriction that when both the characters are same, they shouldn’t be on the same index in the two strings. We have discussed a solution to find length of the longest repeated subsequence. "
},
{
"code": null,
"e": 870,
"s": 866,
"text": "C++"
},
{
"code": null,
"e": 875,
"s": 870,
"text": "Java"
},
{
"code": null,
"e": 883,
"s": 875,
"text": "Python3"
},
{
"code": null,
"e": 886,
"s": 883,
"text": "C#"
},
{
"code": null,
"e": 890,
"s": 886,
"text": "PHP"
},
{
"code": null,
"e": 901,
"s": 890,
"text": "Javascript"
},
{
"code": "// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.int findLongestRepeatingSubSeq(string str){ int n = str.length(); // Create and initialize DP table int dp[n+1][n+1]; //initializing first row and column in dp table for(int i=0;i<=n;i++){ dp[i][0] =0; dp[0][i] =0; } // Fill dp table (similar to LCS loops) for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { // If characters match and indexes are // not same if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i-1][j-1]; // If characters do not match else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); } } return dp[n][n];}",
"e": 1823,
"s": 901,
"text": null
},
{
"code": " // Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static int findLongestRepeatingSubSeq(String str){ int n = str.length(); // Create and initialize DP table int dp[][] = new int[n+1][n+1]; for (int i=0; i<=n; i++) for (int j=0; j<=n; j++) dp[i][j] = 0; // Fill dp table (similar to LCS loops) for (int i=1; i<=n; i++) { for (int j=1; j<=n; j++) { // If characters match and indexes are // not same if (str.charAt(i-1)== str.charAt(j-1) && i != j) dp[i][j] = 1 + dp[i-1][j-1]; // If characters do not match else dp[i][j] = Math.max(dp[i][j-1], dp[i-1][j]); } } return dp[n][n];}",
"e": 2758,
"s": 1823,
"text": null
},
{
"code": "# Python method for Longest Repeated# Subsequence # Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/# for complete code.# This function mainly returns LCS(str, str)# with a condition that same characters at# same index are not considered.def findLongestRepeatingSubSeq(str): n = len(str) # Create and initialize DP table dp = [[0 for k in range(n+1)] for l in range(n+1)] # Fill dp table (similar to LCS loops) for i in range(1, n+1): for j in range(1, n+1): # If characters match and indices are not same if (str[i-1] == str[j-1] and i != j): dp[i][j] = 1 + dp[i-1][j-1] # If characters do not match else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) return dp[n][n] # This code is contributed by Soumen Ghosh",
"e": 3584,
"s": 2758,
"text": null
},
{
"code": "// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static int findLongestRepeatingSubSeq(String str){ int n = str.Length; // Create and initialize DP table int [,]dp = new int[n+1,n+1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dp[i, j] = 0; // Fill dp table (similar to LCS loops) for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // If characters match and indexes are // not same if (str[i-1]== str[j-1] && i != j) dp[i, j] = 1 + dp[i-1, j-1]; // If characters do not match else dp[i,j] = Math.Max(dp[i, j-1], dp[i-1, j]); } } return dp[n, n];} // This code is contributed by 29AjayKumar",
"e": 4557,
"s": 3584,
"text": null
},
{
"code": "<?php// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.function findLongestRepeatingSubSeq($str){ $n = strlen($str); // Create and initialize DP table $dp = array_fill(0, $n + 1, array_fill(0, $n + 1, NULL)); for ($i = 0; $i <= $n; $i++) for ($j = 0; $j <= $n; $j++) $dp[$i][$j] = 0; // Fill dp table (similar to LCS loops) for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { // If characters match and indexes // are not same if ($str[$i - 1] == $str[$j - 1] && $i != $j) $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1]; // If characters do not match else $dp[$i][$j] = max($dp[$i][$j - 1], $dp[$i - 1][$j]); } } return $dp[$n][$n];} // This code is contributed by ita_c?>",
"e": 5656,
"s": 4557,
"text": null
},
{
"code": "<script>// Refer https://www.geeksforgeeks.org/longest-repeating-subsequence/// for complete code.// This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered. function findLongestRepeatingSubSeq(str) { let n = str.length; // Create and initialize DP table let dp = new Array(n+1); for (let i = 0; i <= n; i++) { dp[i] = new Array(n+1); for (let j = 0; j <= n; j++) dp[i][j] = 0; } // Fill dp table (similar to LCS loops) for (let i = 1; i <= n; i++) { for (let j = 1; j <= n; j++) { // If characters match and indexes are // not same if (str[i - 1] == str[j - 1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1]; // If characters do not match else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); } } return dp[n][n]; } // This code is contributed by avanitrachhadiya2155</script>",
"e": 6736,
"s": 5656,
"text": null
},
{
"code": null,
"e": 6940,
"s": 6736,
"text": "Time Complexity: O(n^2)How to print the subsequence? The above solution only finds length of subsequence. We can print the subsequence using dp[n+1][n+1] table built. The idea is similar to printing LCS."
},
{
"code": null,
"e": 7707,
"s": 6940,
"text": " \n// Pseudo code to find longest repeated\n// subsequence using the dp[][] table filled\n// above.\n\n// Initialize result\nstring res = \"\";\n\n// Traverse dp[][] from bottom right\ni = n, j = n;\nwhile (i > 0 && j > 0)\n{\n // If this cell is same as diagonally\n // adjacent cell just above it, then \n // same characters are present at \n // str[i-1] and str[j-1]. Append any \n // of them to result.\n if (dp[i][j] == dp[i-1][j-1] + 1)\n {\n res = res + str[i-1];\n i--;\n j--;\n }\n\n // Otherwise we move to the side\n // that gave us maximum result\n else if (dp[i][j] == dp[i-1][j])\n i--;\n else\n j--;\n }\n\n // Since we traverse dp[][] from bottom,\n // we get result in reverse order.\n reverse(res.begin(), res.end());\n\nreturn res;"
},
{
"code": null,
"e": 7748,
"s": 7707,
"text": "Below is implementation of above steps. "
},
{
"code": null,
"e": 7752,
"s": 7748,
"text": "C++"
},
{
"code": null,
"e": 7757,
"s": 7752,
"text": "Java"
},
{
"code": null,
"e": 7765,
"s": 7757,
"text": "Python3"
},
{
"code": null,
"e": 7769,
"s": 7765,
"text": "PHP"
},
{
"code": null,
"e": 7772,
"s": 7769,
"text": "C#"
},
{
"code": null,
"e": 7783,
"s": 7772,
"text": "Javascript"
},
{
"code": "// C++ program to find the longest repeated// subsequence#include <bits/stdc++.h>using namespace std; // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.string longestRepeatedSubSeq(string str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.length(); int dp[n+1][n+1]; for (int i=0; i<=n; i++) for (int j=0; j<=n; j++) dp[i][j] = 0; for (int i=1; i<=n; i++) for (int j=1; j<=n; j++) if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i-1][j-1]; else dp[i][j] = max(dp[i][j-1], dp[i-1][j]); // THIS PART OF CODE FINDS THE RESULT STRING USING DP[][] // Initialize result string res = \"\"; // Traverse dp[][] from bottom right int i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i-1][j-1] + 1) { res = res + str[i-1]; i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i][j] == dp[i-1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. reverse(res.begin(), res.end()); return res;} // Driver Programint main(){ string str = \"AABEBCDD\"; cout << longestRepeatedSubSeq(str); return 0;}",
"e": 9512,
"s": 7783,
"text": null
},
{
"code": "// Java program to find the longest repeated// subsequenceimport java.util.*; class GFG{ // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static String longestRepeatedSubSeq(String str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.length(); int[][] dp = new int[n + 1][n + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= n; j++) dp[i][j] = 0; for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (str.charAt(i - 1) == str.charAt(j - 1) && i != j) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); // THIS PART OF CODE FINDS // THE RESULT STRING USING DP[][] // Initialize result String res = \"\"; // Traverse dp[][] from bottom right int i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i - 1][j - 1] + 1) { res = res + str.charAt(i - 1); i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i][j] == dp[i - 1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. String reverse = \"\"; for(int k = res.length() - 1; k >= 0; k--) { reverse = reverse + res.charAt(k); } return reverse;} // Driver codepublic static void main(String args[]){ String str = \"AABEBCDD\"; System.out.println(longestRepeatedSubSeq(str));}} // This code is contributed by// Surendra_Gangwar",
"e": 11506,
"s": 9512,
"text": null
},
{
"code": "# Python3 program to find the# longest repeated subsequence # This function mainly returns LCS(str, str)# with a condition that same characters# at same index are not considered.def longestRepeatedSubSeq(str): # This part of code is same as # below post it fills dp[][] # https://www.geeksforgeeks.org/longest-repeating-subsequence/ # OR the code mentioned above n = len(str) dp = [[0 for i in range(n+1)] for j in range(n+1)] for i in range(1, n + 1): for j in range(1, n + 1): if (str[i-1] == str[j-1] and i != j): dp[i][j] = 1 + dp[i-1][j-1] else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) # This part of code finds the result # string using dp[][] Initialize result res = '' # Traverse dp[][] from bottom right i = n j = n while (i > 0 and j > 0): # If this cell is same as diagonally # adjacent cell just above it, then # same characters are present at # str[i-1] and str[j-1]. Append any # of them to result. if (dp[i][j] == dp[i-1][j-1] + 1): res += str[i-1] i -= 1 j -= 1 # Otherwise we move to the side # that gave us maximum result. elif (dp[i][j] == dp[i-1][j]): i -= 1 else: j -= 1 # Since we traverse dp[][] from bottom, # we get result in reverse order. res = ''.join(reversed(res)) return res # Driver Programstr = 'AABEBCDD'print(longestRepeatedSubSeq(str)) # This code is contributed by Soumen Ghosh",
"e": 13076,
"s": 11506,
"text": null
},
{
"code": "<?php// Php program to find the longest repeated// subsequence // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.function longestRepeatedSubSeq($str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. $n = strlen($str); $dp = array(array()); for ($i = 0; $i <= $n; $i++) for ($j = 0; $j <= $n; $j++) $dp[$i][$j] = 0; for ($i = 1; $i <= $n; $i++) for ($j = 1; $j <= $n; $j++) if ($str[$i - 1] == $str[$j - 1] && $i != $j) $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1]; else $dp[$i][$j] = max($dp[$i][$j - 1], $dp[$i - 1][$j]); // THIS PART OF CODE FINDS THE RESULT // STRING USING DP[][], Initialize result $res = \"\"; // Traverse dp[][] from bottom right $i = $n; $j = $n; while ($i > 0 && $j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if ($dp[$i][$j] == $dp[$i - 1][$j - 1] + 1) { $res = $res.$str[$i - 1]; $i--; $j--; } // Otherwise we move to the side // that gave us maximum result else if ($dp[$i][$j] == $dp[$i - 1][$j]) $i--; else $j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. return strrev($res) ;} // Driver Code$str = \"AABEBCDD\";echo longestRepeatedSubSeq($str); // This code is contributed by Ryuga?>",
"e": 14843,
"s": 13076,
"text": null
},
{
"code": "// C# program to find the longest repeated// subsequenceusing System;using System.Collections.Generic; class GFG{ // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered.static String longestRepeatedSubSeq(String str){ // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[,] // https://www.geeksforgeeks.org/longest-repeating-subsequence/ // OR the code mentioned above. int n = str.Length,i,j; int[,] dp = new int[n + 1,n + 1]; for (i = 0; i <= n; i++) for (j = 0; j <= n; j++) dp[i, j] = 0; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) if (str[i - 1] == str[j - 1] && i != j) dp[i, j] = 1 + dp[i - 1, j - 1]; else dp[i, j] = Math.Max(dp[i, j - 1], dp[i - 1, j]); // THIS PART OF CODE FINDS // THE RESULT STRING USING DP[,] // Initialize result String res = \"\"; // Traverse dp[,] from bottom right i = n; j= n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i, j] == dp[i - 1,j - 1] + 1) { res = res + str[i - 1]; i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i,j] == dp[i - 1,j]) i--; else j--; } // Since we traverse dp[,] from bottom, // we get result in reverse order. String reverse = \"\"; for(int k = res.Length - 1; k >= 0; k--) { reverse = reverse + res[k]; } return reverse;} // Driver codepublic static void Main(String []args){ String str = \"AABEBCDD\"; Console.WriteLine(longestRepeatedSubSeq(str));}} // This code is contributed by Princi Singh",
"e": 16814,
"s": 14843,
"text": null
},
{
"code": "<script> // Javascript program to find the longest repeated// subsequence // This function mainly returns LCS(str, str)// with a condition that same characters at// same index are not considered. function longestRepeatedSubSeq(str) { // THIS PART OF CODE IS SAME AS BELOW POST. // IT FILLS dp[][] // https://www.geeksforgeeks.org/longest-repeating- subsequence/ // OR the code mentioned above. let n = str.length; let dp = new Array(n + 1); for (let i = 0; i <= n; i++) { dp[i]=new Array(n+1); for (let j = 0; j <= n; j++) dp[i][j] = 0; } for (let i = 1; i <= n; i++) for (let j = 1; j <= n; j++) if (str[i-1] == str[j-1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); // THIS PART OF CODE FINDS // THE RESULT STRING USING DP[][] // Initialize result let res = \"\"; // Traverse dp[][] from bottom right let i = n, j = n; while (i > 0 && j > 0) { // If this cell is same as diagonally // adjacent cell just above it, then // same characters are present at // str[i-1] and str[j-1]. Append any // of them to result. if (dp[i][j] == dp[i - 1][j - 1] + 1) { res = res + str[i-1]; i--; j--; } // Otherwise we move to the side // that gave us maximum result else if (dp[i][j] == dp[i - 1][j]) i--; else j--; } // Since we traverse dp[][] from bottom, // we get result in reverse order. let reverse = \"\"; for(let k = res.length - 1; k >= 0; k--) { reverse = reverse + res[k]; } return reverse; } // Driver code let str = \"AABEBCDD\"; document.write(longestRepeatedSubSeq(str)); // This code is contributed by rag2127 </script>",
"e": 18842,
"s": 16814,
"text": null
},
{
"code": null,
"e": 18851,
"s": 18842,
"text": "Output: "
},
{
"code": null,
"e": 18855,
"s": 18851,
"text": "ABD"
},
{
"code": null,
"e": 19317,
"s": 18855,
"text": "Time Complexity : O(n2) Auxiliary Space : O(n2)This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 19325,
"s": 19317,
"text": "ankthon"
},
{
"code": null,
"e": 19339,
"s": 19325,
"text": "princiraj1992"
},
{
"code": null,
"e": 19351,
"s": 19339,
"text": "29AjayKumar"
},
{
"code": null,
"e": 19357,
"s": 19351,
"text": "ukasp"
},
{
"code": null,
"e": 19369,
"s": 19357,
"text": "gfg_sal_gfg"
},
{
"code": null,
"e": 19386,
"s": 19369,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 19399,
"s": 19386,
"text": "princi singh"
},
{
"code": null,
"e": 19412,
"s": 19399,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 19425,
"s": 19412,
"text": "vivekdusad55"
},
{
"code": null,
"e": 19446,
"s": 19425,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 19454,
"s": 19446,
"text": "rag2127"
},
{
"code": null,
"e": 19470,
"s": 19454,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 19485,
"s": 19470,
"text": "sagartomar9927"
},
{
"code": null,
"e": 19489,
"s": 19485,
"text": "LCS"
},
{
"code": null,
"e": 19509,
"s": 19489,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 19529,
"s": 19509,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 19533,
"s": 19529,
"text": "LCS"
}
] |
Number of pairs such that path between pairs has the two vertices A and B
|
05 Dec, 2021
Given an undirected connected graph and two vertices A and B, the task is to find the number of pairs of vertices {X, Y} such that any path from X to Y contains both vertices A and B.Note:
{ X, Y } is treated equivalent to { Y, X }.
X != A, X != B, Y != A and Y != B.
Examples:
For the above graph: Input: A = 3, B = 5 Output:4 Explanation: There are four pairs { X, Y } such that all the paths from the source X to the destination Y contain the vertices A, B. They are: {1, 6}, {1, 7}, {2, 6} and {2, 7}.
For the above graph: Input: A = 2, B = 1 Output: 1 Explanation: There is only one pair { X, Y } such that all the paths from the source X to the destination Y contain the vertices A, B. That is: {4, 3}.
Approach:
For the given graph, if for any pair {X, Y}, if some other path exists between them apart from the given vertices A and B, then those two vertices are not included in the final answer. That is because we need the count of pairs such that any path from those pairs consists the vertices A and B.
Therefore, we are interested in pairs of vertices { X, Y } such that deleting the vertex A(while going from B) breaks the connection from X to Y and deleting the vertex B(while going from A) breaks the connection from X to Y.
In other words the pair {X, Y} interests us if X and Y belong to the different components of the graph both when removing A and when removing B.
Therefore, in order to find the above pairs, the following steps are followed:
Consider a random directed connected graph where some group of nodes which are interconnected is connected to A and some group of interconnected nodes are connected to B. A and B may or may not have nodes between them.
What if we remove both A and B? Then the graph can either become disconnected or remain connected.
If the graph remains connected, then no pair of vertices exists because there are other paths in the graph for all the pairs {X, Y} without the vertices A and B in it.
If the graph becomes disconnected, then there arise two cases: On removing vertices A and B, the graph is converted to two disconnected components.On removing vertices A and B, the graph is converted to three disconnected components.
On removing vertices A and B, the graph is converted to two disconnected components.On removing vertices A and B, the graph is converted to three disconnected components.
On removing vertices A and B, the graph is converted to two disconnected components.
On removing vertices A and B, the graph is converted to three disconnected components.
If on removing vertices A and B, the graph is converted to two disconnected components, then three cases arise:
When there is a group of interconnected nodes connected to the vertex A, some independent nodes are connected to A and B and the vertex B is the leaf node of the graph:
When there is a group of interconnected nodes connected to the vertex A, some independent nodes are connected to A and B and the vertex B is the leaf node of the graph:
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex B. So no pair exists.When there is a group of interconnected nodes connected to the vertex B, some independent nodes are connected to A and B and the vertex A is the leaf node of the graph:
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex B. So no pair exists.
When there is a group of interconnected nodes connected to the vertex B, some independent nodes are connected to A and B and the vertex A is the leaf node of the graph:
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex A. So no pair exists.When there are no nodes between vertex A and vertex B and neither of the vertices A and B are the leaf nodes of the graph:
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex A. So no pair exists.
When there are no nodes between vertex A and vertex B and neither of the vertices A and B are the leaf nodes of the graph:
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. Here, any one of the vertex of one component can be paired up with any vertex of the other component. Therefore, the number of pairs in this graph becomes the product of the count of number of interconnected nodes in component 1 and component two.
Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. Here, any one of the vertex of one component can be paired up with any vertex of the other component. Therefore, the number of pairs in this graph becomes the product of the count of number of interconnected nodes in component 1 and component two.
If on removing vertices A and B, the graph is converted to three disconnected components, then only one case arises:
When there is a group of interconnected nodes connected to vertex A, vertex B and there is another group of nodes between vertex A and vertex B and none of the vertices A and B are the leaf nodes:
When there is a group of interconnected nodes connected to vertex A, vertex B and there is another group of nodes between vertex A and vertex B and none of the vertices A and B are the leaf nodes:
In this case, the component between vertex A and B can be discarded due to the above-mentioned reasons. And, once its discarded, it is directly the case 3 in the two-component graph. The same concept is applied to find the number of vertices.
In this case, the component between vertex A and B can be discarded due to the above-mentioned reasons. And, once its discarded, it is directly the case 3 in the two-component graph. The same concept is applied to find the number of vertices.
Therefore, the above idea is implemented in the following steps:
Store the graph as adjacency list by using vector STL.Run DFS such that we fix the vertex B as if we removed it. This can be done using base condition of the DFS function i.e. the call is returned on reaching the vertex B.Count the vertices that can not be reached by A after removing B.Repeat the above two steps by fixing the vertex A and counting the number of vertices that cannot be reached by B after removing the vertex A.Store both counts in two different variables. This represents the count of vertices set first on removing B and then removing A.Multiplying both the counts is the required answer.
Store the graph as adjacency list by using vector STL.
Run DFS such that we fix the vertex B as if we removed it. This can be done using base condition of the DFS function i.e. the call is returned on reaching the vertex B.
Count the vertices that can not be reached by A after removing B.
Repeat the above two steps by fixing the vertex A and counting the number of vertices that cannot be reached by B after removing the vertex A.
Store both counts in two different variables. This represents the count of vertices set first on removing B and then removing A.
Multiplying both the counts is the required answer.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the number// of pairs such that the path between// every pair contains two given vertices #include <bits/stdc++.h>using namespace std; int cnt, num_vertices, num_edges, a, b; // Function to perform DFS on the given graph// by fixing the a vertexvoid dfs(int a, int b, vector<int> v[], int vis[]){ // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a cnt++; // Performing the DFS by iterating over // the visited array for (auto i : v[a]) { // If the vertex is not visited // and removing the vertex b if (!vis[i] && i != b) dfs(i, b, v, vis); }} // Function to return the number of pairs// such that path between any two pairs// consists the given two vertices A and Bvoid Calculate(vector<int> v[]){ // Initializing the visited array // and assigning it with 0's int vis[num_vertices + 1]; memset(vis, 0, sizeof(vis)); // Initially, the count of vertices is 0 cnt = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B int ans1 = num_vertices - cnt - 1; // Again reinitializing the visited array memset(vis, 0, sizeof(vis)); // Setting the count of vertices to 0 to // perform the DFS again cnt = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A int ans2 = num_vertices - cnt - 1; // Multiplying both the vertices set cout << ans1 * ans2 << "\n";} // Driver codeint main(){ num_vertices = 7, num_edges = 7, a = 3, b = 5; int edges[][2] = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 5 } }; vector<int> v[num_vertices + 1]; // Loop to store the graph for (int i = 0; i < num_edges; i++) { v[edges[i][0]].push_back(edges[i][1]); v[edges[i][1]].push_back(edges[i][0]); } Calculate(v); return 0;}
// Java program to find the number// of pairs such that the path between// every pair contains two given verticesimport java.util.*; class GFG{static int N = 1000001;static int c, n, m, a, b; // Function to perform DFS on the given graph// by fixing the a vertexstatic void dfs(int a, int b, Vector<Integer> v[], int vis[]){ // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a c++; // Performing the DFS by iterating over // the visited array for (int i : v[a]) { // If the vertex is not visited // and removing the vertex b if (vis[i] == 0 && i != b) dfs(i, b, v, vis); }} // Function to return the number of pairs// such that path between any two pairs// consists of the given two vertices A and Bstatic void Calculate(Vector<Integer> v[]){ // Initializing the visited array // and assigning it with 0's int []vis = new int[n + 1]; Arrays.fill(vis, 0); // Initially, the count of vertices is 0 c = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B int ans1 = n - c - 1; // Again reinitializing the visited array Arrays.fill(vis, 0); // Setting the count of vertices to 0 to // perform the DFS again c = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A int ans2 = n - c - 1; // Multiplying both the vertices set System.out.print(ans1 * ans2+ "\n");} // Driver codepublic static void main(String[] args){ n = 7; m = 7; a = 3; b = 5; int edges[][] = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 5 } }; Vector<Integer> []v = new Vector[n + 1]; for(int i= 0; i <= n; i++) { v[i] = new Vector<Integer>(); } // Loop to store the graph for (int i = 0; i < m; i++) { v[edges[i][0]].add(edges[i][1]); v[edges[i][1]].add(edges[i][0]); } Calculate(v);}} // This code is contributed by Rajput-Ji
# Python 3 program to find the number# of pairs such that the path between# every pair contains two given vertices N = 1000001c = 0n = 0m = 0a = 0b = 0 # Function to perform DFS on the given graph# by fixing the a vertexdef dfs(a,b,v,vis): global c # To mark a particular vertex as visited vis[a] = 1 # Variable to store the count of the # vertices which can be reached from a c += 1 # Performing the DFS by iterating over # the visited array for i in v[a]: # If the vertex is not visited # and removing the vertex b if (vis[i]==0 and i != b): dfs(i, b, v, vis) # Function to return the number of pairs# such that path between any two pairs# consists of the given two vertices A and Bdef Calculate(v): global c # Initializing the visited array # and assigning it with 0's vis = [0 for i in range(n + 1)] # Initially, the count of vertices is 0 c = 0 # Performing DFS by removing the vertex B dfs(a, b, v, vis) # Count the vertices which cannot be # reached after removing the vertex B ans1 = n - c - 1 # Again reinitializing the visited array vis = [0 for i in range(len(vis))] # Setting the count of vertices to 0 to # perform the DFS again c = 0 # Performing the DFS by removing the vertex A dfs(b, a, v, vis) # Count the vertices which cannot be # reached after removing the vertex A ans2 = n - c - 1 # Multiplying both the vertices set print(ans1 * ans2) # Driver codeif __name__ == '__main__': n = 7 m = 7 a = 3 b = 5 edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 5]] v = [[] for i in range(n + 1)] # Loop to store the graph for i in range(m): v[edges[i][0]].append(edges[i][1]) v[edges[i][1]].append(edges[i][0]) Calculate(v) # This code is contributed by Surendra_Gangwar
// C# program to find the number// of pairs such that the path between// every pair contains two given verticesusing System;using System.Collections.Generic; class GFG{static int N = 1000001;static int c, n, m, a, b; // Function to perform DFS on the given graph// by fixing the a vertexstatic void dfs(int a, int b, List<int> []v, int []vis){ // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a c++; // Performing the DFS by iterating over // the visited array foreach (int i in v[a]) { // If the vertex is not visited // and removing the vertex b if (vis[i] == 0 && i != b) dfs(i, b, v, vis); }} // Function to return the number of pairs// such that path between any two pairs// consists of the given two vertices A and Bstatic void Calculate(List<int> []v){ // Initializing the visited array // and assigning it with 0's int []vis = new int[n + 1]; for(int i = 0; i < n + 1; i++) vis[i] = 0; // Initially, the count of vertices is 0 c = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B int ans1 = n - c - 1; // Again reinitializing the visited array for(int i = 0; i < n + 1; i++) vis[i] = 0; // Setting the count of vertices to 0 to // perform the DFS again c = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A int ans2 = n - c - 1; // Multiplying both the vertices set Console.Write(ans1 * ans2+ "\n");} // Driver codepublic static void Main(String[] args){ n = 7; m = 7; a = 3; b = 5; int [,]edges = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 5 } }; List<int> []v = new List<int>[n + 1]; for(int i= 0; i <= n; i++) { v[i] = new List<int>(); } // Loop to store the graph for (int i = 0; i < m; i++) { v[edges[i,0]].Add(edges[i,1]); v[edges[i,1]].Add(edges[i,0]); } Calculate(v);}} // This code is contributed by Princi Singh
<script> // Javascript program to find the number // of pairs such that the path between // every pair contains two given vertices let N = 1000001; let c, n, m, a, b; // Function to perform DFS on the given graph // by fixing the a vertex function dfs(a, b, v, vis) { // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a c++; // Performing the DFS by iterating over // the visited array for(let i of v[a]) { // If the vertex is not visited // and removing the vertex b if (vis[i] == 0 && i != b) dfs(i, b, v, vis); } } // Function to return the number of pairs // such that path between any two pairs // consists of the given two vertices A and B function Calculate(v) { // Initializing the visited array // and assigning it with 0's let vis = new Array(n + 1); for(let i = 0; i < n + 1; i++) vis[i] = 0; // Initially, the count of vertices is 0 c = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B let ans1 = n - c - 1; // Again reinitializing the visited array for(let i = 0; i < n + 1; i++) vis[i] = 0; // Setting the count of vertices to 0 to // perform the DFS again c = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A let ans2 = n - c - 1; // Multiplying both the vertices set document.write((ans1 * ans2)+ "</br>"); } n = 7; m = 7; a = 3; b = 5; let edges = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ], [ 6, 7 ], [ 7, 5 ] ]; let v = new Array(n + 1); for(let i= 0; i <= n; i++) { v[i] = []; } // Loop to store the graph for (let i = 0; i < m; i++) { v[edges[i][0]].push(edges[i][1]); v[edges[i][1]].push(edges[i][0]); } Calculate(v); // This code is contributed by divyeshrabadiya07.</script>
4
Time Complexity Analysis:
Here, DFS is performed twice. Therefore, the overall time complexity is O(V + E).
Auxiliary Space : O(V + E)
SURENDRA_GANGWAR
Rajput-Ji
princi singh
Akanksha_Rai
pankajsharmagfg
divyeshrabadiya07
ashutoshsinghgeeksforgeeks
Algorithms
Backtracking
Combinatorial
Graph
Recursion
Recursion
Graph
Combinatorial
Backtracking
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Dec, 2021"
},
{
"code": null,
"e": 218,
"s": 28,
"text": "Given an undirected connected graph and two vertices A and B, the task is to find the number of pairs of vertices {X, Y} such that any path from X to Y contains both vertices A and B.Note: "
},
{
"code": null,
"e": 262,
"s": 218,
"text": "{ X, Y } is treated equivalent to { Y, X }."
},
{
"code": null,
"e": 297,
"s": 262,
"text": "X != A, X != B, Y != A and Y != B."
},
{
"code": null,
"e": 309,
"s": 297,
"text": "Examples: "
},
{
"code": null,
"e": 538,
"s": 309,
"text": "For the above graph: Input: A = 3, B = 5 Output:4 Explanation: There are four pairs { X, Y } such that all the paths from the source X to the destination Y contain the vertices A, B. They are: {1, 6}, {1, 7}, {2, 6} and {2, 7}. "
},
{
"code": null,
"e": 742,
"s": 538,
"text": "For the above graph: Input: A = 2, B = 1 Output: 1 Explanation: There is only one pair { X, Y } such that all the paths from the source X to the destination Y contain the vertices A, B. That is: {4, 3}. "
},
{
"code": null,
"e": 755,
"s": 744,
"text": "Approach: "
},
{
"code": null,
"e": 1050,
"s": 755,
"text": "For the given graph, if for any pair {X, Y}, if some other path exists between them apart from the given vertices A and B, then those two vertices are not included in the final answer. That is because we need the count of pairs such that any path from those pairs consists the vertices A and B."
},
{
"code": null,
"e": 1276,
"s": 1050,
"text": "Therefore, we are interested in pairs of vertices { X, Y } such that deleting the vertex A(while going from B) breaks the connection from X to Y and deleting the vertex B(while going from A) breaks the connection from X to Y."
},
{
"code": null,
"e": 1421,
"s": 1276,
"text": "In other words the pair {X, Y} interests us if X and Y belong to the different components of the graph both when removing A and when removing B."
},
{
"code": null,
"e": 1501,
"s": 1421,
"text": "Therefore, in order to find the above pairs, the following steps are followed: "
},
{
"code": null,
"e": 1720,
"s": 1501,
"text": "Consider a random directed connected graph where some group of nodes which are interconnected is connected to A and some group of interconnected nodes are connected to B. A and B may or may not have nodes between them."
},
{
"code": null,
"e": 1819,
"s": 1720,
"text": "What if we remove both A and B? Then the graph can either become disconnected or remain connected."
},
{
"code": null,
"e": 1987,
"s": 1819,
"text": "If the graph remains connected, then no pair of vertices exists because there are other paths in the graph for all the pairs {X, Y} without the vertices A and B in it."
},
{
"code": null,
"e": 2221,
"s": 1987,
"text": "If the graph becomes disconnected, then there arise two cases: On removing vertices A and B, the graph is converted to two disconnected components.On removing vertices A and B, the graph is converted to three disconnected components."
},
{
"code": null,
"e": 2392,
"s": 2221,
"text": "On removing vertices A and B, the graph is converted to two disconnected components.On removing vertices A and B, the graph is converted to three disconnected components."
},
{
"code": null,
"e": 2477,
"s": 2392,
"text": "On removing vertices A and B, the graph is converted to two disconnected components."
},
{
"code": null,
"e": 2564,
"s": 2477,
"text": "On removing vertices A and B, the graph is converted to three disconnected components."
},
{
"code": null,
"e": 2678,
"s": 2564,
"text": "If on removing vertices A and B, the graph is converted to two disconnected components, then three cases arise: "
},
{
"code": null,
"e": 2849,
"s": 2678,
"text": "When there is a group of interconnected nodes connected to the vertex A, some independent nodes are connected to A and B and the vertex B is the leaf node of the graph: "
},
{
"code": null,
"e": 3020,
"s": 2849,
"text": "When there is a group of interconnected nodes connected to the vertex A, some independent nodes are connected to A and B and the vertex B is the leaf node of the graph: "
},
{
"code": null,
"e": 3487,
"s": 3020,
"text": "Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex B. So no pair exists.When there is a group of interconnected nodes connected to the vertex B, some independent nodes are connected to A and B and the vertex A is the leaf node of the graph: "
},
{
"code": null,
"e": 3784,
"s": 3487,
"text": "Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex B. So no pair exists."
},
{
"code": null,
"e": 3955,
"s": 3784,
"text": "When there is a group of interconnected nodes connected to the vertex B, some independent nodes are connected to A and B and the vertex A is the leaf node of the graph: "
},
{
"code": null,
"e": 4376,
"s": 3955,
"text": "Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex A. So no pair exists.When there are no nodes between vertex A and vertex B and neither of the vertices A and B are the leaf nodes of the graph: "
},
{
"code": null,
"e": 4673,
"s": 4376,
"text": "Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. And, any component can be discarded because vertices of one component may go to vertices of any other component without traversing through vertex A. So no pair exists."
},
{
"code": null,
"e": 4798,
"s": 4673,
"text": "When there are no nodes between vertex A and vertex B and neither of the vertices A and B are the leaf nodes of the graph: "
},
{
"code": null,
"e": 5175,
"s": 4798,
"text": "Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. Here, any one of the vertex of one component can be paired up with any vertex of the other component. Therefore, the number of pairs in this graph becomes the product of the count of number of interconnected nodes in component 1 and component two."
},
{
"code": null,
"e": 5552,
"s": 5175,
"text": "Clearly, in the above graph, the graph is converted into two different components when vertex A and vertex B is removed from it. Here, any one of the vertex of one component can be paired up with any vertex of the other component. Therefore, the number of pairs in this graph becomes the product of the count of number of interconnected nodes in component 1 and component two."
},
{
"code": null,
"e": 5671,
"s": 5552,
"text": "If on removing vertices A and B, the graph is converted to three disconnected components, then only one case arises: "
},
{
"code": null,
"e": 5870,
"s": 5671,
"text": "When there is a group of interconnected nodes connected to vertex A, vertex B and there is another group of nodes between vertex A and vertex B and none of the vertices A and B are the leaf nodes: "
},
{
"code": null,
"e": 6069,
"s": 5870,
"text": "When there is a group of interconnected nodes connected to vertex A, vertex B and there is another group of nodes between vertex A and vertex B and none of the vertices A and B are the leaf nodes: "
},
{
"code": null,
"e": 6312,
"s": 6069,
"text": "In this case, the component between vertex A and B can be discarded due to the above-mentioned reasons. And, once its discarded, it is directly the case 3 in the two-component graph. The same concept is applied to find the number of vertices."
},
{
"code": null,
"e": 6555,
"s": 6312,
"text": "In this case, the component between vertex A and B can be discarded due to the above-mentioned reasons. And, once its discarded, it is directly the case 3 in the two-component graph. The same concept is applied to find the number of vertices."
},
{
"code": null,
"e": 6622,
"s": 6555,
"text": "Therefore, the above idea is implemented in the following steps: "
},
{
"code": null,
"e": 7231,
"s": 6622,
"text": "Store the graph as adjacency list by using vector STL.Run DFS such that we fix the vertex B as if we removed it. This can be done using base condition of the DFS function i.e. the call is returned on reaching the vertex B.Count the vertices that can not be reached by A after removing B.Repeat the above two steps by fixing the vertex A and counting the number of vertices that cannot be reached by B after removing the vertex A.Store both counts in two different variables. This represents the count of vertices set first on removing B and then removing A.Multiplying both the counts is the required answer."
},
{
"code": null,
"e": 7286,
"s": 7231,
"text": "Store the graph as adjacency list by using vector STL."
},
{
"code": null,
"e": 7455,
"s": 7286,
"text": "Run DFS such that we fix the vertex B as if we removed it. This can be done using base condition of the DFS function i.e. the call is returned on reaching the vertex B."
},
{
"code": null,
"e": 7521,
"s": 7455,
"text": "Count the vertices that can not be reached by A after removing B."
},
{
"code": null,
"e": 7664,
"s": 7521,
"text": "Repeat the above two steps by fixing the vertex A and counting the number of vertices that cannot be reached by B after removing the vertex A."
},
{
"code": null,
"e": 7793,
"s": 7664,
"text": "Store both counts in two different variables. This represents the count of vertices set first on removing B and then removing A."
},
{
"code": null,
"e": 7845,
"s": 7793,
"text": "Multiplying both the counts is the required answer."
},
{
"code": null,
"e": 7898,
"s": 7845,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 7902,
"s": 7898,
"text": "C++"
},
{
"code": null,
"e": 7907,
"s": 7902,
"text": "Java"
},
{
"code": null,
"e": 7915,
"s": 7907,
"text": "Python3"
},
{
"code": null,
"e": 7918,
"s": 7915,
"text": "C#"
},
{
"code": null,
"e": 7929,
"s": 7918,
"text": "Javascript"
},
{
"code": "// C++ program to find the number// of pairs such that the path between// every pair contains two given vertices #include <bits/stdc++.h>using namespace std; int cnt, num_vertices, num_edges, a, b; // Function to perform DFS on the given graph// by fixing the a vertexvoid dfs(int a, int b, vector<int> v[], int vis[]){ // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a cnt++; // Performing the DFS by iterating over // the visited array for (auto i : v[a]) { // If the vertex is not visited // and removing the vertex b if (!vis[i] && i != b) dfs(i, b, v, vis); }} // Function to return the number of pairs// such that path between any two pairs// consists the given two vertices A and Bvoid Calculate(vector<int> v[]){ // Initializing the visited array // and assigning it with 0's int vis[num_vertices + 1]; memset(vis, 0, sizeof(vis)); // Initially, the count of vertices is 0 cnt = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B int ans1 = num_vertices - cnt - 1; // Again reinitializing the visited array memset(vis, 0, sizeof(vis)); // Setting the count of vertices to 0 to // perform the DFS again cnt = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A int ans2 = num_vertices - cnt - 1; // Multiplying both the vertices set cout << ans1 * ans2 << \"\\n\";} // Driver codeint main(){ num_vertices = 7, num_edges = 7, a = 3, b = 5; int edges[][2] = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 5 } }; vector<int> v[num_vertices + 1]; // Loop to store the graph for (int i = 0; i < num_edges; i++) { v[edges[i][0]].push_back(edges[i][1]); v[edges[i][1]].push_back(edges[i][0]); } Calculate(v); return 0;}",
"e": 10146,
"s": 7929,
"text": null
},
{
"code": "// Java program to find the number// of pairs such that the path between// every pair contains two given verticesimport java.util.*; class GFG{static int N = 1000001;static int c, n, m, a, b; // Function to perform DFS on the given graph// by fixing the a vertexstatic void dfs(int a, int b, Vector<Integer> v[], int vis[]){ // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a c++; // Performing the DFS by iterating over // the visited array for (int i : v[a]) { // If the vertex is not visited // and removing the vertex b if (vis[i] == 0 && i != b) dfs(i, b, v, vis); }} // Function to return the number of pairs// such that path between any two pairs// consists of the given two vertices A and Bstatic void Calculate(Vector<Integer> v[]){ // Initializing the visited array // and assigning it with 0's int []vis = new int[n + 1]; Arrays.fill(vis, 0); // Initially, the count of vertices is 0 c = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B int ans1 = n - c - 1; // Again reinitializing the visited array Arrays.fill(vis, 0); // Setting the count of vertices to 0 to // perform the DFS again c = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A int ans2 = n - c - 1; // Multiplying both the vertices set System.out.print(ans1 * ans2+ \"\\n\");} // Driver codepublic static void main(String[] args){ n = 7; m = 7; a = 3; b = 5; int edges[][] = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 5 } }; Vector<Integer> []v = new Vector[n + 1]; for(int i= 0; i <= n; i++) { v[i] = new Vector<Integer>(); } // Loop to store the graph for (int i = 0; i < m; i++) { v[edges[i][0]].add(edges[i][1]); v[edges[i][1]].add(edges[i][0]); } Calculate(v);}} // This code is contributed by Rajput-Ji",
"e": 12469,
"s": 10146,
"text": null
},
{
"code": "# Python 3 program to find the number# of pairs such that the path between# every pair contains two given vertices N = 1000001c = 0n = 0m = 0a = 0b = 0 # Function to perform DFS on the given graph# by fixing the a vertexdef dfs(a,b,v,vis): global c # To mark a particular vertex as visited vis[a] = 1 # Variable to store the count of the # vertices which can be reached from a c += 1 # Performing the DFS by iterating over # the visited array for i in v[a]: # If the vertex is not visited # and removing the vertex b if (vis[i]==0 and i != b): dfs(i, b, v, vis) # Function to return the number of pairs# such that path between any two pairs# consists of the given two vertices A and Bdef Calculate(v): global c # Initializing the visited array # and assigning it with 0's vis = [0 for i in range(n + 1)] # Initially, the count of vertices is 0 c = 0 # Performing DFS by removing the vertex B dfs(a, b, v, vis) # Count the vertices which cannot be # reached after removing the vertex B ans1 = n - c - 1 # Again reinitializing the visited array vis = [0 for i in range(len(vis))] # Setting the count of vertices to 0 to # perform the DFS again c = 0 # Performing the DFS by removing the vertex A dfs(b, a, v, vis) # Count the vertices which cannot be # reached after removing the vertex A ans2 = n - c - 1 # Multiplying both the vertices set print(ans1 * ans2) # Driver codeif __name__ == '__main__': n = 7 m = 7 a = 3 b = 5 edges = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 5]] v = [[] for i in range(n + 1)] # Loop to store the graph for i in range(m): v[edges[i][0]].append(edges[i][1]) v[edges[i][1]].append(edges[i][0]) Calculate(v) # This code is contributed by Surendra_Gangwar",
"e": 14349,
"s": 12469,
"text": null
},
{
"code": "// C# program to find the number// of pairs such that the path between// every pair contains two given verticesusing System;using System.Collections.Generic; class GFG{static int N = 1000001;static int c, n, m, a, b; // Function to perform DFS on the given graph// by fixing the a vertexstatic void dfs(int a, int b, List<int> []v, int []vis){ // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a c++; // Performing the DFS by iterating over // the visited array foreach (int i in v[a]) { // If the vertex is not visited // and removing the vertex b if (vis[i] == 0 && i != b) dfs(i, b, v, vis); }} // Function to return the number of pairs// such that path between any two pairs// consists of the given two vertices A and Bstatic void Calculate(List<int> []v){ // Initializing the visited array // and assigning it with 0's int []vis = new int[n + 1]; for(int i = 0; i < n + 1; i++) vis[i] = 0; // Initially, the count of vertices is 0 c = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B int ans1 = n - c - 1; // Again reinitializing the visited array for(int i = 0; i < n + 1; i++) vis[i] = 0; // Setting the count of vertices to 0 to // perform the DFS again c = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A int ans2 = n - c - 1; // Multiplying both the vertices set Console.Write(ans1 * ans2+ \"\\n\");} // Driver codepublic static void Main(String[] args){ n = 7; m = 7; a = 3; b = 5; int [,]edges = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 5 } }; List<int> []v = new List<int>[n + 1]; for(int i= 0; i <= n; i++) { v[i] = new List<int>(); } // Loop to store the graph for (int i = 0; i < m; i++) { v[edges[i,0]].Add(edges[i,1]); v[edges[i,1]].Add(edges[i,0]); } Calculate(v);}} // This code is contributed by Princi Singh",
"e": 16700,
"s": 14349,
"text": null
},
{
"code": "<script> // Javascript program to find the number // of pairs such that the path between // every pair contains two given vertices let N = 1000001; let c, n, m, a, b; // Function to perform DFS on the given graph // by fixing the a vertex function dfs(a, b, v, vis) { // To mark a particular vertex as visited vis[a] = 1; // Variable to store the count of the // vertices which can be reached from a c++; // Performing the DFS by iterating over // the visited array for(let i of v[a]) { // If the vertex is not visited // and removing the vertex b if (vis[i] == 0 && i != b) dfs(i, b, v, vis); } } // Function to return the number of pairs // such that path between any two pairs // consists of the given two vertices A and B function Calculate(v) { // Initializing the visited array // and assigning it with 0's let vis = new Array(n + 1); for(let i = 0; i < n + 1; i++) vis[i] = 0; // Initially, the count of vertices is 0 c = 0; // Performing DFS by removing the vertex B dfs(a, b, v, vis); // Count the vertices which cannot be // reached after removing the vertex B let ans1 = n - c - 1; // Again reinitializing the visited array for(let i = 0; i < n + 1; i++) vis[i] = 0; // Setting the count of vertices to 0 to // perform the DFS again c = 0; // Performing the DFS by removing the vertex A dfs(b, a, v, vis); // Count the vertices which cannot be // reached after removing the vertex A let ans2 = n - c - 1; // Multiplying both the vertices set document.write((ans1 * ans2)+ \"</br>\"); } n = 7; m = 7; a = 3; b = 5; let edges = [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ], [ 5, 6 ], [ 6, 7 ], [ 7, 5 ] ]; let v = new Array(n + 1); for(let i= 0; i <= n; i++) { v[i] = []; } // Loop to store the graph for (let i = 0; i < m; i++) { v[edges[i][0]].push(edges[i][1]); v[edges[i][1]].push(edges[i][0]); } Calculate(v); // This code is contributed by divyeshrabadiya07.</script>",
"e": 19118,
"s": 16700,
"text": null
},
{
"code": null,
"e": 19120,
"s": 19118,
"text": "4"
},
{
"code": null,
"e": 19150,
"s": 19122,
"text": "Time Complexity Analysis: "
},
{
"code": null,
"e": 19232,
"s": 19150,
"text": "Here, DFS is performed twice. Therefore, the overall time complexity is O(V + E)."
},
{
"code": null,
"e": 19259,
"s": 19232,
"text": "Auxiliary Space : O(V + E)"
},
{
"code": null,
"e": 19276,
"s": 19259,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 19286,
"s": 19276,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 19299,
"s": 19286,
"text": "princi singh"
},
{
"code": null,
"e": 19312,
"s": 19299,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 19328,
"s": 19312,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 19346,
"s": 19328,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 19373,
"s": 19346,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 19384,
"s": 19373,
"text": "Algorithms"
},
{
"code": null,
"e": 19397,
"s": 19384,
"text": "Backtracking"
},
{
"code": null,
"e": 19411,
"s": 19397,
"text": "Combinatorial"
},
{
"code": null,
"e": 19417,
"s": 19411,
"text": "Graph"
},
{
"code": null,
"e": 19427,
"s": 19417,
"text": "Recursion"
},
{
"code": null,
"e": 19437,
"s": 19427,
"text": "Recursion"
},
{
"code": null,
"e": 19443,
"s": 19437,
"text": "Graph"
},
{
"code": null,
"e": 19457,
"s": 19443,
"text": "Combinatorial"
},
{
"code": null,
"e": 19470,
"s": 19457,
"text": "Backtracking"
},
{
"code": null,
"e": 19481,
"s": 19470,
"text": "Algorithms"
}
] |
Ruby Integer odd? function with example
|
07 Jan, 2020
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false.
Syntax: number.odd?
Parameter: The function takes the integer which is to be checked for odd or not.
Return Value: The function returns a boolean value which determines if the value is odd or not.
Example #1:
# Ruby program of integer odd? function # Initializing the numbers num1 = 19num2 = 2num3 = 28num4 = 13 # Prints true if number is oddputs num1.odd? puts num2.odd?puts num3.odd? puts num4.odd?
Output:
true
false
false
true
Example #2:
# Ruby program of integer odd? function # Initializing the numbers num1 = 18num2 = 200num3 = 2987num4 = 13 # Prints true if number is odd puts num1.odd? puts num2.odd?puts num3.odd? puts num4.odd?
Output:
false
false
true
true
Ruby Integer-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby on Rails Introduction
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby | String concat Method
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | Array shift() function
Ruby | Exception handling
Ruby | Types of Variables
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jan, 2020"
},
{
"code": null,
"e": 140,
"s": 28,
"text": "The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false."
},
{
"code": null,
"e": 160,
"s": 140,
"text": "Syntax: number.odd?"
},
{
"code": null,
"e": 241,
"s": 160,
"text": "Parameter: The function takes the integer which is to be checked for odd or not."
},
{
"code": null,
"e": 337,
"s": 241,
"text": "Return Value: The function returns a boolean value which determines if the value is odd or not."
},
{
"code": null,
"e": 349,
"s": 337,
"text": "Example #1:"
},
{
"code": "# Ruby program of integer odd? function # Initializing the numbers num1 = 19num2 = 2num3 = 28num4 = 13 # Prints true if number is oddputs num1.odd? puts num2.odd?puts num3.odd? puts num4.odd?",
"e": 544,
"s": 349,
"text": null
},
{
"code": null,
"e": 552,
"s": 544,
"text": "Output:"
},
{
"code": null,
"e": 575,
"s": 552,
"text": "true\nfalse\nfalse\ntrue\n"
},
{
"code": null,
"e": 587,
"s": 575,
"text": "Example #2:"
},
{
"code": "# Ruby program of integer odd? function # Initializing the numbers num1 = 18num2 = 200num3 = 2987num4 = 13 # Prints true if number is odd puts num1.odd? puts num2.odd?puts num3.odd? puts num4.odd?",
"e": 787,
"s": 587,
"text": null
},
{
"code": null,
"e": 795,
"s": 787,
"text": "Output:"
},
{
"code": null,
"e": 818,
"s": 795,
"text": "false\nfalse\ntrue\ntrue\n"
},
{
"code": null,
"e": 837,
"s": 818,
"text": "Ruby Integer-class"
},
{
"code": null,
"e": 850,
"s": 837,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 855,
"s": 850,
"text": "Ruby"
},
{
"code": null,
"e": 953,
"s": 855,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 999,
"s": 953,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1026,
"s": 999,
"text": "Ruby on Rails Introduction"
},
{
"code": null,
"e": 1069,
"s": 1026,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1113,
"s": 1069,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1141,
"s": 1113,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 1183,
"s": 1141,
"text": "Ruby | Array class find_index() operation"
},
{
"code": null,
"e": 1202,
"s": 1183,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 1232,
"s": 1202,
"text": "Ruby | Array shift() function"
},
{
"code": null,
"e": 1258,
"s": 1232,
"text": "Ruby | Exception handling"
}
] |
Why is a C++ pure virtual function initialized by 0?
|
It’s just a syntax, nothing more than that for saying that “the function is pure virtual”.
A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in declaration.
Here is an example of pure virtual function in C++ program
Live Demo
#include<iostream>
using namespace std;
class B {
public: virtual void s() = 0; // Pure Virtual Function
};
class D:public B {
public: void s() {
cout << " Virtual Function in Derived class\n";
}
};
int main() {
B *b;
D dobj;
b = &dobj;
b->s();
}
Virtual Function in Derived class
|
[
{
"code": null,
"e": 1153,
"s": 1062,
"text": "It’s just a syntax, nothing more than that for saying that “the function is pure virtual”."
},
{
"code": null,
"e": 1339,
"s": 1153,
"text": "A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in declaration."
},
{
"code": null,
"e": 1398,
"s": 1339,
"text": "Here is an example of pure virtual function in C++ program"
},
{
"code": null,
"e": 1409,
"s": 1398,
"text": " Live Demo"
},
{
"code": null,
"e": 1685,
"s": 1409,
"text": "#include<iostream>\nusing namespace std;\nclass B {\n public: virtual void s() = 0; // Pure Virtual Function\n};\n\nclass D:public B {\n public: void s() {\n cout << \" Virtual Function in Derived class\\n\";\n }\n};\n\nint main() {\n B *b;\n D dobj;\n b = &dobj;\n b->s();\n}"
},
{
"code": null,
"e": 1719,
"s": 1685,
"text": "Virtual Function in Derived class"
}
] |
Add comment to column in MySQL using Python - GeeksforGeeks
|
11 Dec, 2020
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such as PyMySQL, mysql.connector, etc.
A comment is a readable explanation or a statement placed in the SQL queries. It is used for the purpose of making the SQL statements easier for humans to understand. MySQL generally ignores them during the parsing of the SQL code. Comments can be written in a single line or multiple lines.
In this article, we’re using a database called test and which has a table called geeksfoegeeks. Look at the below image.
Database=test and Table=geeksfoegeeks
To check if there is any comment for any column, see below statement.
SHOW FULL COLUMNS FROM table_name;
Below is the image which shows that no column is associated with any kind of comment.
No Comment for any columns
The statement to add any comment to a column is given below:
ALTER TABLE table_name MODIFY column_name type_of_that_column COMMENT ‘enter comment here’;
Below are some examples which depict how to add a comment to a column in a MySQL table using Python:
Example 1
Adding Single line comment.
Python3
# import required module import pymysql # make connectionconn = pymysql.connect(host="localhost", user="root", password="1234",db="test") # create cursor objectmycursor = conn.cursor() # execute querymycursor.execute("ALTER TABLE geeksforgeeks MODIFY name \ CHAR(50) COMMENT 'ENTER NAMES HERE'") # display comments of all columnsmycursor.execute("SHOW FULL COLUMNS FROM GEEKSFOEGEEKS")result = mycursor.fetchall()for i in result: print(i)mycursor.execute("COMMIT") #terminate connectionconn.close()
Output:
After adding comments
We could see that the comment “ENTER NAMES HERE” for column “Name” has been added.
Example 2
Adding multi-line comments.
Python3
# import required module import pymysql # establish connection connectionconn = pymysql.connect(host="localhost", user="root", password="1234",db="test") # create cursor objectmycursor = conn.cursor() # execute querymycursor.execute("ALTER TABLE geeksforgeeks MODIFY NAME CHAR(50) \ COMMENT 'ENTER NAMES HERE',MODIFY ADDRESS CHAR(50) \ COMMENT 'Do not Enter Address\nmore than 50 \ characters',MODIFY AGE INT COMMENT \ 'Enter Age here',MODIFY MOB_NUMBER INT COMMENT \ 'Mobile number should be of 10 digits', \ MODIFY ID_NO VARCHAR(50) COMMENT 'Id Number \ is Unique\nKindly Enter different Ids'") # display comments of all attributesmycursor.execute("SHOW FULL COLUMNS FROM GEEKSFOEGEEKS")result = mycursor.fetchall()for i in result: print(i)mycursor.execute("COMMIT") # terminate connectionconn.close()
Output:
After adding Comments
We could see that comments have been added successfully. Below is a screenshot of the MySQL database is also added.
MySQL Database
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 26030,
"s": 25647,
"text": "MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server we use various modules in Python such as PyMySQL, mysql.connector, etc."
},
{
"code": null,
"e": 26323,
"s": 26030,
"text": "A comment is a readable explanation or a statement placed in the SQL queries. It is used for the purpose of making the SQL statements easier for humans to understand. MySQL generally ignores them during the parsing of the SQL code. Comments can be written in a single line or multiple lines. "
},
{
"code": null,
"e": 26444,
"s": 26323,
"text": "In this article, we’re using a database called test and which has a table called geeksfoegeeks. Look at the below image."
},
{
"code": null,
"e": 26482,
"s": 26444,
"text": "Database=test and Table=geeksfoegeeks"
},
{
"code": null,
"e": 26552,
"s": 26482,
"text": "To check if there is any comment for any column, see below statement."
},
{
"code": null,
"e": 26587,
"s": 26552,
"text": "SHOW FULL COLUMNS FROM table_name;"
},
{
"code": null,
"e": 26673,
"s": 26587,
"text": "Below is the image which shows that no column is associated with any kind of comment."
},
{
"code": null,
"e": 26700,
"s": 26673,
"text": "No Comment for any columns"
},
{
"code": null,
"e": 26761,
"s": 26700,
"text": "The statement to add any comment to a column is given below:"
},
{
"code": null,
"e": 26853,
"s": 26761,
"text": "ALTER TABLE table_name MODIFY column_name type_of_that_column COMMENT ‘enter comment here’;"
},
{
"code": null,
"e": 26954,
"s": 26853,
"text": "Below are some examples which depict how to add a comment to a column in a MySQL table using Python:"
},
{
"code": null,
"e": 26964,
"s": 26954,
"text": "Example 1"
},
{
"code": null,
"e": 26992,
"s": 26964,
"text": "Adding Single line comment."
},
{
"code": null,
"e": 27000,
"s": 26992,
"text": "Python3"
},
{
"code": "# import required module import pymysql # make connectionconn = pymysql.connect(host=\"localhost\", user=\"root\", password=\"1234\",db=\"test\") # create cursor objectmycursor = conn.cursor() # execute querymycursor.execute(\"ALTER TABLE geeksforgeeks MODIFY name \\ CHAR(50) COMMENT 'ENTER NAMES HERE'\") # display comments of all columnsmycursor.execute(\"SHOW FULL COLUMNS FROM GEEKSFOEGEEKS\")result = mycursor.fetchall()for i in result: print(i)mycursor.execute(\"COMMIT\") #terminate connectionconn.close()",
"e": 27545,
"s": 27000,
"text": null
},
{
"code": null,
"e": 27553,
"s": 27545,
"text": "Output:"
},
{
"code": null,
"e": 27575,
"s": 27553,
"text": "After adding comments"
},
{
"code": null,
"e": 27658,
"s": 27575,
"text": "We could see that the comment “ENTER NAMES HERE” for column “Name” has been added."
},
{
"code": null,
"e": 27669,
"s": 27658,
"text": "Example 2 "
},
{
"code": null,
"e": 27697,
"s": 27669,
"text": "Adding multi-line comments."
},
{
"code": null,
"e": 27705,
"s": 27697,
"text": "Python3"
},
{
"code": "# import required module import pymysql # establish connection connectionconn = pymysql.connect(host=\"localhost\", user=\"root\", password=\"1234\",db=\"test\") # create cursor objectmycursor = conn.cursor() # execute querymycursor.execute(\"ALTER TABLE geeksforgeeks MODIFY NAME CHAR(50) \\ COMMENT 'ENTER NAMES HERE',MODIFY ADDRESS CHAR(50) \\ COMMENT 'Do not Enter Address\\nmore than 50 \\ characters',MODIFY AGE INT COMMENT \\ 'Enter Age here',MODIFY MOB_NUMBER INT COMMENT \\ 'Mobile number should be of 10 digits', \\ MODIFY ID_NO VARCHAR(50) COMMENT 'Id Number \\ is Unique\\nKindly Enter different Ids'\") # display comments of all attributesmycursor.execute(\"SHOW FULL COLUMNS FROM GEEKSFOEGEEKS\")result = mycursor.fetchall()for i in result: print(i)mycursor.execute(\"COMMIT\") # terminate connectionconn.close()",
"e": 28654,
"s": 27705,
"text": null
},
{
"code": null,
"e": 28662,
"s": 28654,
"text": "Output:"
},
{
"code": null,
"e": 28684,
"s": 28662,
"text": "After adding Comments"
},
{
"code": null,
"e": 28800,
"s": 28684,
"text": "We could see that comments have been added successfully. Below is a screenshot of the MySQL database is also added."
},
{
"code": null,
"e": 28815,
"s": 28800,
"text": "MySQL Database"
},
{
"code": null,
"e": 28828,
"s": 28815,
"text": "Python-mySQL"
},
{
"code": null,
"e": 28835,
"s": 28828,
"text": "Python"
},
{
"code": null,
"e": 28933,
"s": 28835,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28965,
"s": 28933,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29007,
"s": 28965,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29049,
"s": 29007,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29105,
"s": 29049,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29132,
"s": 29105,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29163,
"s": 29132,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29199,
"s": 29163,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29228,
"s": 29199,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29250,
"s": 29228,
"text": "Defaultdict in Python"
}
] |
C++ Program to Perform Finite State Automaton based Search
|
This is a C++ program to perform finite state automaton based search. An automaton with a finite number of states is called a Finite Automaton. Here, a text is given text[0 ... t-1] and a pattern p[0 ... p-1] is also given. We have to find the pattern in the text and print its all occurrences at the respective indices.
Begin
Function void transitiontable():
1) put the entries in first row and filled it up. All entries in first row are always 0 except the entry for p[0] character. Always we need to go to state 1.
for p[0].
2) Initialize longestprefixsuffix as 0.
3) for i = 1 to P. (Here P is the length of the pattern)
a) Copy the entries from the row at index equal to longestprefixsuffix.
b) Update the entry for p[i] character to i+1.
c) Update longestprefixsuffix = TF[lps][pat[i]]
where TT is the 2D array.
End
#include<iostream>
#include<cstring>
#define NO_OF_CHARS 512
using namespace std;
// builds the TF table which represents Finite Automata for a given pattern
void transitiontable(char *p, int P, int TT[][NO_OF_CHARS]) {
int i, longestprefixsuffix = 0, y;
// put entries in first row
for (y =0; y < NO_OF_CHARS; y++)
TT[0][y] = 0;
TT[0][p[0]] = 1;
// put entries in other rows
for (i = 1; i<= P; i++) { // Copy values from row at index longestprefixsuffix
for (y = 0; y < NO_OF_CHARS; y++)
TT[i][y] = TT[longestprefixsuffix][y];
// Update the entry
TT[i][p[i]] = i + 1;
// Update lps for next row to be filled
if (i < P)
longestprefixsuffix = TT[longestprefixsuffix][p[i]]; // TT is the 2D array which is being constructed.
}
}
//Prints all occurrences of pattern in text
void patternsearch(char *p, char *t) {
int P = strlen(p);
int T = strlen(t);
int TT[P+1][NO_OF_CHARS];
transitiontable(p, P, TT);
// process text over FA.
int i, j=0;
for (i = 0; i < T; i++) {
j = TT[j][t[i]];
if (j == P) {
cout<<"\n pattern is found at index: "<< i-P+1;
}
}
}
int main() {
char *text = "AABAA ABBAACCDD CCDDAABAA"; //take the text as input
char *pattern = "AABAA"; //take the pattern as input
patternsearch(pattern, text);
getchar();
return 0;
}
pattern is found at index: 0
pattern is found at index: 20
|
[
{
"code": null,
"e": 1383,
"s": 1062,
"text": "This is a C++ program to perform finite state automaton based search. An automaton with a finite number of states is called a Finite Automaton. Here, a text is given text[0 ... t-1] and a pattern p[0 ... p-1] is also given. We have to find the pattern in the text and print its all occurrences at the respective indices."
},
{
"code": null,
"e": 1923,
"s": 1383,
"text": "Begin\n Function void transitiontable():\n 1) put the entries in first row and filled it up. All entries in first row are always 0 except the entry for p[0] character. Always we need to go to state 1.\n for p[0].\n 2) Initialize longestprefixsuffix as 0.\n 3) for i = 1 to P. (Here P is the length of the pattern)\n a) Copy the entries from the row at index equal to longestprefixsuffix.\n b) Update the entry for p[i] character to i+1.\n c) Update longestprefixsuffix = TF[lps][pat[i]]\n where TT is the 2D array.\nEnd"
},
{
"code": null,
"e": 3293,
"s": 1923,
"text": "#include<iostream>\n#include<cstring>\n#define NO_OF_CHARS 512\nusing namespace std;\n// builds the TF table which represents Finite Automata for a given pattern\nvoid transitiontable(char *p, int P, int TT[][NO_OF_CHARS]) {\n int i, longestprefixsuffix = 0, y;\n // put entries in first row\n for (y =0; y < NO_OF_CHARS; y++)\n TT[0][y] = 0;\n TT[0][p[0]] = 1;\n // put entries in other rows\n for (i = 1; i<= P; i++) { // Copy values from row at index longestprefixsuffix\n for (y = 0; y < NO_OF_CHARS; y++)\n TT[i][y] = TT[longestprefixsuffix][y];\n // Update the entry\n TT[i][p[i]] = i + 1;\n // Update lps for next row to be filled\n if (i < P)\n longestprefixsuffix = TT[longestprefixsuffix][p[i]]; // TT is the 2D array which is being constructed.\n }\n}\n//Prints all occurrences of pattern in text\nvoid patternsearch(char *p, char *t) {\n int P = strlen(p);\n int T = strlen(t);\n int TT[P+1][NO_OF_CHARS];\n transitiontable(p, P, TT);\n // process text over FA.\n int i, j=0;\n for (i = 0; i < T; i++) {\n j = TT[j][t[i]];\n if (j == P) {\n cout<<\"\\n pattern is found at index: \"<< i-P+1;\n }\n }\n}\nint main() {\n char *text = \"AABAA ABBAACCDD CCDDAABAA\"; //take the text as input\n char *pattern = \"AABAA\"; //take the pattern as input\n patternsearch(pattern, text);\n getchar();\n return 0;\n}"
},
{
"code": null,
"e": 3352,
"s": 3293,
"text": "pattern is found at index: 0\npattern is found at index: 20"
}
] |
Use Pandas to Calculate Statistics in Python
|
23 Jun, 2021
Performing various complex statistical operations in python can be easily reduced to single line commands using pandas. We will discuss some of the most useful and common statistical operations in this post. We will be using the Titanic survival dataset to demonstrate such operations.
Python3
# Import Pandas Libraryimport pandas as pd # Load Titanic Dataset as Dataframedataset = pd.read_csv('train.csv') # Show dataset# head() bydefault show# 5 rows of the dataframedataset.head()
Output:
Calculates the mean or average value by using DataFrame/Series.mean() method.
Syntax: DataFrame/Series.mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters:
axis: {index (0), columns (1)}
Specify the axis for the function to be applied on.
skipna: This parameter takes bool value, default value is True
It excludes null values when computing the result.
level: This parameter takes int value or level name, default value is None.
If the axis is a MultiIndex, count along a particular level, collapsing into a Series.
numeric_only: This parameter takes bool value, default value is None
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data values. Not implemented for Series.
**kwargs: Additional arguments to be passed to the function.
Returns: Mean of Series or DataFrame (if level specified)
Code:
Python3
# Calculate the Mean# of 'Age' columnmean = dataset['Age'].mean() # Print meanprint(mean)
Output:
29.69911764705882
Calculates the median value by using DataFrame/Series.median() method.
Syntax: DataFrame/Series.median(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters:
axis: {index (0), columns (1)}
Specify the axis for the function to be applied on.
skipna: This parameter takes bool value, default value is True
It excludes null values when computing the result.
level: This parameter takes int or level name, default None
If the axis is a MultiIndex, count along a particular level, collapsing into a Series.
numeric_only: This parameter takes bool value, default value is None
Include only float, int, boolean columns. If value is None, will attempt to use everything, then use only numeric data.
**kwargs: Additional arguments to be passed to the function.
Returns: Median of Series or DataFrame (if level specified)
Code:
Python3
# Calculate Median of 'Fare' columnmedian = dataset['Fare'].median() # Print medianprint(median)
Output:
14.4542
Calculates the mode or most frequent value by using DataFrame.mode() method.
Syntax: DataFrame/Series.mode(self, axis=0, numeric_only=False, dropna=True)
Parameters:
axis: {index (0), columns (1)}
The axis to iterate over while searching for the mode value:
0 value or ‘index’ : get mode of each column
1 value or ‘columns’ : get mode of each row.
numeric_only: This parameter takes bool value, default value is False.
If True, only apply to numeric value columns.
dropna: This parameter takes bool value, default value is True.
Don’t consider counts of NaN/None value.
Returns: Highest frequency value.
Code:
Python3
# Calculate Mode of 'Sex' columnmode = dataset['Sex'].mode() # Print modeprint(mode)
Output:
0 male
dtype: object
Calculates the count or frequency of non-null values by using DataFrame/Series.count() Method.
Syntax: DataFrame/Series.count(self, axis=0, level=None, numeric_only=False)
Parameters:
axis: {0 or ‘index’, 1 or ‘columns’}, default value is 0
If value is 0 or ‘index’ counts are generated for each column. If value is 1 or ‘columns’ counts are generated for each row.
level: (optional)This parameter takes int or str value.
If the axis is a MultiIndex type, count along a particular level, collapsing into a DataFrame. A str is used specifies the level name.
numeric_only: This parameter takes bool value, default False
Include only float, int or boolean data.Returns: Return the highest frequency value
Returns: For each column/row the number of non-null entries. If level is specified returns a DataFrame structure.
Code:
Python3
# Calculate Count of 'Ticket' columncount = dataset['Ticket'].count() # Print countprint(count)
Output:
891
Calculates the standard deviation of values by using DataFrame/Series.std() method.
Syntax: DataFrame/Series.std(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)
Parameters:
axis: {index (0), columns (1)}
skipna: This parameters takes bool value, default value is True.
Exclude NA/null values. If an entire row/column has NA values, the result will be NA value.
level: This parameters takes int or level name, default value is None.
If the axis is a MultiIndex, count along a particular level, collapsing into a Series.
ddof: This parameter take int value, default value is 1.
Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N value represents the number of elements.
numeric_only: This parameter takes bool value , default None
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns: Standard Deviation
Code:
Python3
# Calculate Standard Deviation# of 'Fare' columnstd = dataset['Fare'].std() # Print standard deviationprint(std)
Output:
49.693428597180905
Calculates the maximum value using DataFrame/Series.max() method.
Syntax: DataFrame/Series.max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters:
axis: {index (0), columns (1)}
Specify the axis for the function to be applied on.
skipna: bool, default True
It excludes null values when computing the result.
level: int or level name, default None
If the axis is a MultiIndex type, count along a particular level, collapsing into a Series.
numeric_only: bool, default None
Include only float, int, boolean columns. If None value, will attempt to use everything, then use only numeric data.
**kwargs: Additional keyword to be passed to the function.
Returns: Maximum value in Series or DataFrame (if level specified)
Code:
Python3
# Calculate Maximum value in 'Age' columnmaxValue = dataset['Age'].max() # Print maxValueprint(maxValue)
Output:
80.0
Calculates the minimum value using DataFrame/Series.min() method.
Syntax: DataFrame/Series.min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters:
axis: {index (0), columns (1)}
Specify the axis for the function to be applied on.
skipna: bool, default True
It excludes null values when computing the result.
level: int or level name, default None
If the axis is a MultiIndex type, count along a particular level, collapsing into a Series.
numeric_only: bool, default None
Include only float, int, boolean columns. If None value, will attempt to use everything, then use only numeric data.
**kwargs: Additional keyword to be passed to the function.
Returns: Minimum value in Series or DataFrame (if level specified)
Code:
Python3
# Calculate Minimum value in 'Fare' columnminValue = dataset['Fare'].min() # Print minValueprint(minValue)
Output:
0.0000
Summarizes general descriptive statistics using DataFrame/Series.describe() method.
Syntax: DataFrame/Series.describe(self: ~ FrameOrSeries, percentiles=None, include=None, exclude=None)
Parameters:
percentiles: list-like of numbers, optional
include: ‘all’, list-like of dtypes or None values (default), optional
exclude: list-like of dtypes or None values (default), optional,
Returns: Summary statistics of the Series or Dataframe provided.
Python3
# Statistical summarydataset.describe()
Output:
saurabh1990aror
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 340,
"s": 54,
"text": "Performing various complex statistical operations in python can be easily reduced to single line commands using pandas. We will discuss some of the most useful and common statistical operations in this post. We will be using the Titanic survival dataset to demonstrate such operations."
},
{
"code": null,
"e": 348,
"s": 340,
"text": "Python3"
},
{
"code": "# Import Pandas Libraryimport pandas as pd # Load Titanic Dataset as Dataframedataset = pd.read_csv('train.csv') # Show dataset# head() bydefault show# 5 rows of the dataframedataset.head()",
"e": 538,
"s": 348,
"text": null
},
{
"code": null,
"e": 546,
"s": 538,
"text": "Output:"
},
{
"code": null,
"e": 624,
"s": 546,
"text": "Calculates the mean or average value by using DataFrame/Series.mean() method."
},
{
"code": null,
"e": 725,
"s": 624,
"text": "Syntax: DataFrame/Series.mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 737,
"s": 725,
"text": "Parameters:"
},
{
"code": null,
"e": 768,
"s": 737,
"text": "axis: {index (0), columns (1)}"
},
{
"code": null,
"e": 830,
"s": 768,
"text": " Specify the axis for the function to be applied on."
},
{
"code": null,
"e": 894,
"s": 830,
"text": "skipna: This parameter takes bool value, default value is True"
},
{
"code": null,
"e": 956,
"s": 894,
"text": " It excludes null values when computing the result."
},
{
"code": null,
"e": 1032,
"s": 956,
"text": "level: This parameter takes int value or level name, default value is None."
},
{
"code": null,
"e": 1129,
"s": 1032,
"text": " If the axis is a MultiIndex, count along a particular level, collapsing into a Series."
},
{
"code": null,
"e": 1198,
"s": 1129,
"text": "numeric_only: This parameter takes bool value, default value is None"
},
{
"code": null,
"e": 1356,
"s": 1198,
"text": " Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data values. Not implemented for Series."
},
{
"code": null,
"e": 1417,
"s": 1356,
"text": "**kwargs: Additional arguments to be passed to the function."
},
{
"code": null,
"e": 1476,
"s": 1417,
"text": "Returns: Mean of Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 1482,
"s": 1476,
"text": "Code:"
},
{
"code": null,
"e": 1490,
"s": 1482,
"text": "Python3"
},
{
"code": "# Calculate the Mean# of 'Age' columnmean = dataset['Age'].mean() # Print meanprint(mean)",
"e": 1580,
"s": 1490,
"text": null
},
{
"code": null,
"e": 1589,
"s": 1580,
"text": "Output: "
},
{
"code": null,
"e": 1607,
"s": 1589,
"text": "29.69911764705882"
},
{
"code": null,
"e": 1678,
"s": 1607,
"text": "Calculates the median value by using DataFrame/Series.median() method."
},
{
"code": null,
"e": 1781,
"s": 1678,
"text": "Syntax: DataFrame/Series.median(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 1793,
"s": 1781,
"text": "Parameters:"
},
{
"code": null,
"e": 1824,
"s": 1793,
"text": "axis: {index (0), columns (1)}"
},
{
"code": null,
"e": 1886,
"s": 1824,
"text": " Specify the axis for the function to be applied on."
},
{
"code": null,
"e": 1950,
"s": 1886,
"text": "skipna: This parameter takes bool value, default value is True"
},
{
"code": null,
"e": 2011,
"s": 1950,
"text": " It excludes null values when computing the result."
},
{
"code": null,
"e": 2071,
"s": 2011,
"text": "level: This parameter takes int or level name, default None"
},
{
"code": null,
"e": 2168,
"s": 2071,
"text": " If the axis is a MultiIndex, count along a particular level, collapsing into a Series."
},
{
"code": null,
"e": 2238,
"s": 2168,
"text": "numeric_only: This parameter takes bool value, default value is None"
},
{
"code": null,
"e": 2369,
"s": 2238,
"text": " Include only float, int, boolean columns. If value is None, will attempt to use everything, then use only numeric data."
},
{
"code": null,
"e": 2430,
"s": 2369,
"text": "**kwargs: Additional arguments to be passed to the function."
},
{
"code": null,
"e": 2491,
"s": 2430,
"text": "Returns: Median of Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 2497,
"s": 2491,
"text": "Code:"
},
{
"code": null,
"e": 2505,
"s": 2497,
"text": "Python3"
},
{
"code": "# Calculate Median of 'Fare' columnmedian = dataset['Fare'].median() # Print medianprint(median)",
"e": 2602,
"s": 2505,
"text": null
},
{
"code": null,
"e": 2615,
"s": 2606,
"text": "Output: "
},
{
"code": null,
"e": 2625,
"s": 2617,
"text": "14.4542"
},
{
"code": null,
"e": 2704,
"s": 2627,
"text": "Calculates the mode or most frequent value by using DataFrame.mode() method."
},
{
"code": null,
"e": 2783,
"s": 2706,
"text": "Syntax: DataFrame/Series.mode(self, axis=0, numeric_only=False, dropna=True)"
},
{
"code": null,
"e": 2795,
"s": 2783,
"text": "Parameters:"
},
{
"code": null,
"e": 2826,
"s": 2795,
"text": "axis: {index (0), columns (1)}"
},
{
"code": null,
"e": 2897,
"s": 2826,
"text": " The axis to iterate over while searching for the mode value:"
},
{
"code": null,
"e": 2952,
"s": 2897,
"text": " 0 value or ‘index’ : get mode of each column"
},
{
"code": null,
"e": 3007,
"s": 2952,
"text": " 1 value or ‘columns’ : get mode of each row."
},
{
"code": null,
"e": 3079,
"s": 3007,
"text": "numeric_only: This parameter takes bool value, default value is False."
},
{
"code": null,
"e": 3136,
"s": 3079,
"text": " If True, only apply to numeric value columns."
},
{
"code": null,
"e": 3200,
"s": 3136,
"text": "dropna: This parameter takes bool value, default value is True."
},
{
"code": null,
"e": 3252,
"s": 3200,
"text": " Don’t consider counts of NaN/None value."
},
{
"code": null,
"e": 3287,
"s": 3252,
"text": "Returns: Highest frequency value. "
},
{
"code": null,
"e": 3295,
"s": 3289,
"text": "Code:"
},
{
"code": null,
"e": 3305,
"s": 3297,
"text": "Python3"
},
{
"code": "# Calculate Mode of 'Sex' columnmode = dataset['Sex'].mode() # Print modeprint(mode)",
"e": 3390,
"s": 3305,
"text": null
},
{
"code": null,
"e": 3399,
"s": 3390,
"text": "Output: "
},
{
"code": null,
"e": 3423,
"s": 3399,
"text": "0 male\ndtype: object"
},
{
"code": null,
"e": 3518,
"s": 3423,
"text": "Calculates the count or frequency of non-null values by using DataFrame/Series.count() Method."
},
{
"code": null,
"e": 3595,
"s": 3518,
"text": "Syntax: DataFrame/Series.count(self, axis=0, level=None, numeric_only=False)"
},
{
"code": null,
"e": 3607,
"s": 3595,
"text": "Parameters:"
},
{
"code": null,
"e": 3664,
"s": 3607,
"text": "axis: {0 or ‘index’, 1 or ‘columns’}, default value is 0"
},
{
"code": null,
"e": 3823,
"s": 3664,
"text": " If value is 0 or ‘index’ counts are generated for each column. If value is 1 or ‘columns’ counts are generated for each row."
},
{
"code": null,
"e": 3879,
"s": 3823,
"text": "level: (optional)This parameter takes int or str value."
},
{
"code": null,
"e": 4026,
"s": 3879,
"text": " If the axis is a MultiIndex type, count along a particular level, collapsing into a DataFrame. A str is used specifies the level name."
},
{
"code": null,
"e": 4088,
"s": 4026,
"text": "numeric_only: This parameter takes bool value, default False"
},
{
"code": null,
"e": 4183,
"s": 4088,
"text": " Include only float, int or boolean data.Returns: Return the highest frequency value "
},
{
"code": null,
"e": 4326,
"s": 4183,
"text": "Returns: For each column/row the number of non-null entries. If level is specified returns a DataFrame structure."
},
{
"code": null,
"e": 4332,
"s": 4326,
"text": "Code:"
},
{
"code": null,
"e": 4340,
"s": 4332,
"text": "Python3"
},
{
"code": "# Calculate Count of 'Ticket' columncount = dataset['Ticket'].count() # Print countprint(count)",
"e": 4436,
"s": 4340,
"text": null
},
{
"code": null,
"e": 4445,
"s": 4436,
"text": "Output: "
},
{
"code": null,
"e": 4449,
"s": 4445,
"text": "891"
},
{
"code": null,
"e": 4533,
"s": 4449,
"text": "Calculates the standard deviation of values by using DataFrame/Series.std() method."
},
{
"code": null,
"e": 4641,
"s": 4533,
"text": "Syntax: DataFrame/Series.std(self, axis=None, skipna=None, level=None, ddof=1, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 4653,
"s": 4641,
"text": "Parameters:"
},
{
"code": null,
"e": 4684,
"s": 4653,
"text": "axis: {index (0), columns (1)}"
},
{
"code": null,
"e": 4749,
"s": 4684,
"text": "skipna: This parameters takes bool value, default value is True."
},
{
"code": null,
"e": 4851,
"s": 4749,
"text": " Exclude NA/null values. If an entire row/column has NA values, the result will be NA value."
},
{
"code": null,
"e": 4922,
"s": 4851,
"text": "level: This parameters takes int or level name, default value is None."
},
{
"code": null,
"e": 5019,
"s": 4922,
"text": " If the axis is a MultiIndex, count along a particular level, collapsing into a Series."
},
{
"code": null,
"e": 5076,
"s": 5019,
"text": "ddof: This parameter take int value, default value is 1."
},
{
"code": null,
"e": 5208,
"s": 5076,
"text": " Delta Degrees of Freedom. The divisor used in calculations is N – ddof, where N value represents the number of elements."
},
{
"code": null,
"e": 5269,
"s": 5208,
"text": "numeric_only: This parameter takes bool value , default None"
},
{
"code": null,
"e": 5419,
"s": 5269,
"text": " Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series."
},
{
"code": null,
"e": 5448,
"s": 5419,
"text": "Returns: Standard Deviation "
},
{
"code": null,
"e": 5454,
"s": 5448,
"text": "Code:"
},
{
"code": null,
"e": 5462,
"s": 5454,
"text": "Python3"
},
{
"code": "# Calculate Standard Deviation# of 'Fare' columnstd = dataset['Fare'].std() # Print standard deviationprint(std)",
"e": 5575,
"s": 5462,
"text": null
},
{
"code": null,
"e": 5584,
"s": 5575,
"text": "Output: "
},
{
"code": null,
"e": 5603,
"s": 5584,
"text": "49.693428597180905"
},
{
"code": null,
"e": 5669,
"s": 5603,
"text": "Calculates the maximum value using DataFrame/Series.max() method."
},
{
"code": null,
"e": 5769,
"s": 5669,
"text": "Syntax: DataFrame/Series.max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 5781,
"s": 5769,
"text": "Parameters:"
},
{
"code": null,
"e": 5812,
"s": 5781,
"text": "axis: {index (0), columns (1)}"
},
{
"code": null,
"e": 5874,
"s": 5812,
"text": " Specify the axis for the function to be applied on."
},
{
"code": null,
"e": 5901,
"s": 5874,
"text": "skipna: bool, default True"
},
{
"code": null,
"e": 5962,
"s": 5901,
"text": " It excludes null values when computing the result."
},
{
"code": null,
"e": 6001,
"s": 5962,
"text": "level: int or level name, default None"
},
{
"code": null,
"e": 6103,
"s": 6001,
"text": " If the axis is a MultiIndex type, count along a particular level, collapsing into a Series."
},
{
"code": null,
"e": 6136,
"s": 6103,
"text": "numeric_only: bool, default None"
},
{
"code": null,
"e": 6265,
"s": 6136,
"text": " Include only float, int, boolean columns. If None value, will attempt to use everything, then use only numeric data."
},
{
"code": null,
"e": 6324,
"s": 6265,
"text": "**kwargs: Additional keyword to be passed to the function."
},
{
"code": null,
"e": 6391,
"s": 6324,
"text": "Returns: Maximum value in Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 6397,
"s": 6391,
"text": "Code:"
},
{
"code": null,
"e": 6405,
"s": 6397,
"text": "Python3"
},
{
"code": "# Calculate Maximum value in 'Age' columnmaxValue = dataset['Age'].max() # Print maxValueprint(maxValue)",
"e": 6510,
"s": 6405,
"text": null
},
{
"code": null,
"e": 6519,
"s": 6510,
"text": "Output: "
},
{
"code": null,
"e": 6524,
"s": 6519,
"text": "80.0"
},
{
"code": null,
"e": 6590,
"s": 6524,
"text": "Calculates the minimum value using DataFrame/Series.min() method."
},
{
"code": null,
"e": 6690,
"s": 6590,
"text": "Syntax: DataFrame/Series.min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs)"
},
{
"code": null,
"e": 6702,
"s": 6690,
"text": "Parameters:"
},
{
"code": null,
"e": 6733,
"s": 6702,
"text": "axis: {index (0), columns (1)}"
},
{
"code": null,
"e": 6795,
"s": 6733,
"text": " Specify the axis for the function to be applied on."
},
{
"code": null,
"e": 6822,
"s": 6795,
"text": "skipna: bool, default True"
},
{
"code": null,
"e": 6883,
"s": 6822,
"text": " It excludes null values when computing the result."
},
{
"code": null,
"e": 6922,
"s": 6883,
"text": "level: int or level name, default None"
},
{
"code": null,
"e": 7024,
"s": 6922,
"text": " If the axis is a MultiIndex type, count along a particular level, collapsing into a Series."
},
{
"code": null,
"e": 7057,
"s": 7024,
"text": "numeric_only: bool, default None"
},
{
"code": null,
"e": 7186,
"s": 7057,
"text": " Include only float, int, boolean columns. If None value, will attempt to use everything, then use only numeric data."
},
{
"code": null,
"e": 7245,
"s": 7186,
"text": "**kwargs: Additional keyword to be passed to the function."
},
{
"code": null,
"e": 7312,
"s": 7245,
"text": "Returns: Minimum value in Series or DataFrame (if level specified)"
},
{
"code": null,
"e": 7318,
"s": 7312,
"text": "Code:"
},
{
"code": null,
"e": 7326,
"s": 7318,
"text": "Python3"
},
{
"code": "# Calculate Minimum value in 'Fare' columnminValue = dataset['Fare'].min() # Print minValueprint(minValue)",
"e": 7433,
"s": 7326,
"text": null
},
{
"code": null,
"e": 7446,
"s": 7437,
"text": "Output: "
},
{
"code": null,
"e": 7455,
"s": 7448,
"text": "0.0000"
},
{
"code": null,
"e": 7541,
"s": 7457,
"text": "Summarizes general descriptive statistics using DataFrame/Series.describe() method."
},
{
"code": null,
"e": 7647,
"s": 7543,
"text": "Syntax: DataFrame/Series.describe(self: ~ FrameOrSeries, percentiles=None, include=None, exclude=None) "
},
{
"code": null,
"e": 7659,
"s": 7647,
"text": "Parameters:"
},
{
"code": null,
"e": 7703,
"s": 7659,
"text": "percentiles: list-like of numbers, optional"
},
{
"code": null,
"e": 7774,
"s": 7703,
"text": "include: ‘all’, list-like of dtypes or None values (default), optional"
},
{
"code": null,
"e": 7839,
"s": 7774,
"text": "exclude: list-like of dtypes or None values (default), optional,"
},
{
"code": null,
"e": 7904,
"s": 7839,
"text": "Returns: Summary statistics of the Series or Dataframe provided."
},
{
"code": null,
"e": 7914,
"s": 7906,
"text": "Python3"
},
{
"code": "# Statistical summarydataset.describe()",
"e": 7954,
"s": 7914,
"text": null
},
{
"code": null,
"e": 7962,
"s": 7954,
"text": "Output:"
},
{
"code": null,
"e": 7978,
"s": 7962,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 8002,
"s": 7978,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 8016,
"s": 8002,
"text": "Python-pandas"
},
{
"code": null,
"e": 8023,
"s": 8016,
"text": "Python"
}
] |
How to sql insert items from a list or collection in to table using JDBC?
|
To insert the contents of a database to a collection,
Connect to the database and retrieve the contents of the table into a ResultSet object using the SELECT Query.
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from MyPlayers");
Create a Java class to hold the contents of each record, with a variable and, setter and getter methods for each column (with suitable datatype).
For example, if the table sample in the database has two fields with the details −
Column name: ID, datatype: INT(11)
Column name: Name, datatype VARCHAR(255)
Then, the variable declaration and the setter and getter methods in the class would be like −
import java.sql.Date;
public class Sample {
private int ID;
private String Name;
public int getID() {
return ID;
}
public void setID(int id) {
ID = id;
}
public int getName() {
return Name;
}
public void setName(int name) {
Name = name;
}
}
For each record, create and object of the above class (Sample), retrieve the values of each column from the ResultSet object and, set them to this object using its setter methods as −
Player player = new Player();
player.setID(rs.getInt("ID"));
player.setName(rs.getString("Name"));
Add the object to the required collection.
ArrayList<Player> arrayList = new ArrayList<>(); arrayList.add(player);
Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −
CREATE TABLE MyPlayers(
ID INT,
First_Name VARCHAR(255),
Last_Name VARCHAR(255),
Date_Of_Birth date,
Place_Of_Birth VARCHAR(255),
Country VARCHAR(255),
PRIMARY KEY (ID)
);
Now, we will insert 7 records in MyPlayers table using INSERT statements −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');
insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');
insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');
insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');
insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');
insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');
insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
Java class used hold the data of each of this table −
import java.sql.Date;
public class Player {
private int ID;
private String First_Name;
private String Last_Name;
private Date Date_Of_Birth;
private String Place_Of_Birth;
private String Country;
public int getID() {
return ID;
}
public void setID(int id) {
ID = id;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public Date getDate_Of_Birth() {
return Date_Of_Birth;
}
public void setDate_Of_Birth(Date date_Of_Birth) {
Date_Of_Birth = date_Of_Birth;
}
public String getPlace_Of_Birth() {
return Place_Of_Birth;
}
public void setPlace_Of_Birth(String place_Of_Birth) {
Place_Of_Birth = place_Of_Birth;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
Following JDBC program that retrieves the contents of the MyPlayers table, adds them to an ArrayList.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class TableToArrayList {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from MyPlayers");
//Creating an ArrayList object
ArrayList<Player> arrayList = new ArrayList<>();
//Adding the Records of the table to the Array List
while(rs.next()) {
Player player = new Player();
player.setID(rs.getInt("ID"));
player.setFirst_Name(rs.getString("First_Name"));
player.setLast_Name(rs.getString("Last_Name"));
player.setDate_Of_Birth(rs.getDate("Date_Of_Birth"));
player.setPlace_Of_Birth(rs.getString("Place_Of_Birth"));
player.setCountry(rs.getString("Country"));
arrayList.add(player);
}
for (Player obj : arrayList) {
System.out.print("ID: "+obj.getID()+", ");
System.out.print("Name: "+obj.getFirst_Name()+", ");
System.out.print("Age: "+obj.getLast_Name()+", ");
System.out.print("Salary: "+obj.getDate_Of_Birth()+", ");
System.out.print("Country: "+obj.getPlace_Of_Birth()+", ");
System.out.print("Address: "+obj.getCountry());
System.out.println();
}
}
}
Connection established......
Records added to the array list.....
Contents of the array list:
ID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India
ID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica
ID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka
ID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India
ID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India
ID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India
ID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnely, Address: England
|
[
{
"code": null,
"e": 1241,
"s": 1187,
"text": "To insert the contents of a database to a collection,"
},
{
"code": null,
"e": 1352,
"s": 1241,
"text": "Connect to the database and retrieve the contents of the table into a ResultSet object using the SELECT Query."
},
{
"code": null,
"e": 1643,
"s": 1352,
"text": "DriverManager.registerDriver(new com.mysql.jdbc.Driver());\nString mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\nConnection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\nStatement stmt = con.createStatement();\nResultSet rs = stmt.executeQuery(\"select * from MyPlayers\");"
},
{
"code": null,
"e": 1789,
"s": 1643,
"text": "Create a Java class to hold the contents of each record, with a variable and, setter and getter methods for each column (with suitable datatype)."
},
{
"code": null,
"e": 1872,
"s": 1789,
"text": "For example, if the table sample in the database has two fields with the details −"
},
{
"code": null,
"e": 1907,
"s": 1872,
"text": "Column name: ID, datatype: INT(11)"
},
{
"code": null,
"e": 1948,
"s": 1907,
"text": "Column name: Name, datatype VARCHAR(255)"
},
{
"code": null,
"e": 2042,
"s": 1948,
"text": "Then, the variable declaration and the setter and getter methods in the class would be like −"
},
{
"code": null,
"e": 2337,
"s": 2042,
"text": "import java.sql.Date;\npublic class Sample {\n private int ID;\n private String Name;\n public int getID() {\n return ID;\n }\n public void setID(int id) {\n ID = id;\n }\n public int getName() {\n return Name;\n }\n public void setName(int name) {\n Name = name;\n }\n}"
},
{
"code": null,
"e": 2521,
"s": 2337,
"text": "For each record, create and object of the above class (Sample), retrieve the values of each column from the ResultSet object and, set them to this object using its setter methods as −"
},
{
"code": null,
"e": 2620,
"s": 2521,
"text": "Player player = new Player();\nplayer.setID(rs.getInt(\"ID\"));\nplayer.setName(rs.getString(\"Name\"));"
},
{
"code": null,
"e": 2663,
"s": 2620,
"text": "Add the object to the required collection."
},
{
"code": null,
"e": 2735,
"s": 2663,
"text": "ArrayList<Player> arrayList = new ArrayList<>(); arrayList.add(player);"
},
{
"code": null,
"e": 2835,
"s": 2735,
"text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below −"
},
{
"code": null,
"e": 3028,
"s": 2835,
"text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);"
},
{
"code": null,
"e": 3103,
"s": 3028,
"text": "Now, we will insert 7 records in MyPlayers table using INSERT statements −"
},
{
"code": null,
"e": 3765,
"s": 3103,
"text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');"
},
{
"code": null,
"e": 3819,
"s": 3765,
"text": "Java class used hold the data of each of this table −"
},
{
"code": null,
"e": 4901,
"s": 3819,
"text": "import java.sql.Date;\npublic class Player {\n private int ID;\n private String First_Name;\n private String Last_Name;\n private Date Date_Of_Birth;\n private String Place_Of_Birth;\n private String Country;\n public int getID() {\n return ID;\n }\n public void setID(int id) {\n ID = id;\n }\n public String getFirst_Name() {\n return First_Name;\n }\n public void setFirst_Name(String first_Name) {\n First_Name = first_Name;\n }\n public String getLast_Name() {\n return Last_Name;\n }\n public void setLast_Name(String last_Name) {\n Last_Name = last_Name;\n }\n public Date getDate_Of_Birth() {\n return Date_Of_Birth;\n }\n public void setDate_Of_Birth(Date date_Of_Birth) {\n Date_Of_Birth = date_Of_Birth;\n }\n public String getPlace_Of_Birth() {\n return Place_Of_Birth;\n }\n public void setPlace_Of_Birth(String place_Of_Birth) {\n Place_Of_Birth = place_Of_Birth;\n }\n public String getCountry() {\n return Country;\n }\n public void setCountry(String country) {\n Country = country;\n }\n}"
},
{
"code": null,
"e": 5003,
"s": 4901,
"text": "Following JDBC program that retrieves the contents of the MyPlayers table, adds them to an ArrayList."
},
{
"code": null,
"e": 6785,
"s": 5003,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\nimport java.util.ArrayList;\npublic class TableToArrayList {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from MyPlayers\");\n //Creating an ArrayList object\n ArrayList<Player> arrayList = new ArrayList<>();\n //Adding the Records of the table to the Array List\n while(rs.next()) {\n Player player = new Player();\n player.setID(rs.getInt(\"ID\"));\n player.setFirst_Name(rs.getString(\"First_Name\"));\n player.setLast_Name(rs.getString(\"Last_Name\"));\n player.setDate_Of_Birth(rs.getDate(\"Date_Of_Birth\"));\n player.setPlace_Of_Birth(rs.getString(\"Place_Of_Birth\"));\n player.setCountry(rs.getString(\"Country\"));\n arrayList.add(player);\n }\n for (Player obj : arrayList) {\n System.out.print(\"ID: \"+obj.getID()+\", \");\n System.out.print(\"Name: \"+obj.getFirst_Name()+\", \");\n System.out.print(\"Age: \"+obj.getLast_Name()+\", \");\n System.out.print(\"Salary: \"+obj.getDate_Of_Birth()+\", \");\n System.out.print(\"Country: \"+obj.getPlace_Of_Birth()+\", \");\n System.out.print(\"Address: \"+obj.getCountry());\n System.out.println();\n }\n }\n}"
},
{
"code": null,
"e": 7500,
"s": 6785,
"text": "Connection established......\nRecords added to the array list.....\nContents of the array list:\nID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India\nID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica\nID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka\nID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India\nID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India\nID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India\nID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnely, Address: England"
}
] |
How to split a slice of bytes in Golang?
|
26 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you are allowed to split the given slice using a Split() function. This function splits a slice of bytes into all subslices separated by the given separator and returns a slice which contains all these subslices. It is defined under the bytes package so, you have to import bytes package in your program for accessing Split function.
Syntax:
func Split(o_slice, sep []byte) [][]byte
Here, o_slice is the slice of bytes and sep is the separator. If the sep is empty, then it will split after each UTF-8 sequence. Let us discuss this concept with the help of the given examples:
Example 1:
// Go program to illustrate the concept// of splitting a slice of bytespackage main import ( "bytes" "fmt") func main() { // Creating and initializing // the slice of bytes // Using shorthand declaration slice_1 := []byte{'!', '!', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '#', '#'} slice_2 := []byte{'A', 'p', 'p', 'l', 'e'} slice_3 := []byte{'%', 'g', '%', 'e', '%', 'e', '%', 'k', '%', 's', '%'} // Displaying slices fmt.Println("Original Slice:") fmt.Printf("Slice 1: %s", slice_1) fmt.Printf("\nSlice 2: %s", slice_2) fmt.Printf("\nSlice 3: %s", slice_3) // Splitting the slice of bytes // Using Split function res1 := bytes.Split(slice_1, []byte("eek")) res2 := bytes.Split(slice_2, []byte("")) res3 := bytes.Split(slice_3, []byte("%")) // Display the results fmt.Printf("\n\nAfter splitting:") fmt.Printf("\nSlice 1: %s", res1) fmt.Printf("\nSlice 2: %s", res2) fmt.Printf("\nSlice 3: %s", res3) }
Output:
Original Slice:
Slice 1: !!GeeksforGeeks##
Slice 2: Apple
Slice 3: %g%e%e%k%s%
After splitting:
Slice 1: [!!G sforG s##]
Slice 2: [A p p l e]
Slice 3: [ g e e k s ]
Example 2:
// Go program to illustrate the concept// of splitting a slice of bytespackage main import ( "bytes" "fmt") func main() { // Creating and Splitting // the slice of bytes // Using Split function res1 := bytes.Split([]byte("****Welcome, to, GeeksforGeeks****"), []byte(",")) res2 := bytes.Split([]byte("Learning x how x to x trim x a x slice of bytes"), []byte("x")) res3 := bytes.Split([]byte("GeeksforGeeks, Geek"), []byte("")) res4 := bytes.Split([]byte(""), []byte(",")) // Display the results fmt.Printf("Final Value:\n") fmt.Printf("\nSlice 1: %s", res1) fmt.Printf("\nSlice 2: %s", res2) fmt.Printf("\nSlice 3: %s", res3) fmt.Printf("\nSlice 4: %s", res4)}
Output:
Final Value:
Slice 1: [****Welcome to GeeksforGeeks****]
Slice 2: [Learning how to trim a slice of bytes]
Slice 3: [G e e k s f o r G e e k s , G e e k]
Slice 4: []
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 655,
"s": 28,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you are allowed to split the given slice using a Split() function. This function splits a slice of bytes into all subslices separated by the given separator and returns a slice which contains all these subslices. It is defined under the bytes package so, you have to import bytes package in your program for accessing Split function."
},
{
"code": null,
"e": 663,
"s": 655,
"text": "Syntax:"
},
{
"code": null,
"e": 704,
"s": 663,
"text": "func Split(o_slice, sep []byte) [][]byte"
},
{
"code": null,
"e": 898,
"s": 704,
"text": "Here, o_slice is the slice of bytes and sep is the separator. If the sep is empty, then it will split after each UTF-8 sequence. Let us discuss this concept with the help of the given examples:"
},
{
"code": null,
"e": 909,
"s": 898,
"text": "Example 1:"
},
{
"code": "// Go program to illustrate the concept// of splitting a slice of bytespackage main import ( \"bytes\" \"fmt\") func main() { // Creating and initializing // the slice of bytes // Using shorthand declaration slice_1 := []byte{'!', '!', 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', '#', '#'} slice_2 := []byte{'A', 'p', 'p', 'l', 'e'} slice_3 := []byte{'%', 'g', '%', 'e', '%', 'e', '%', 'k', '%', 's', '%'} // Displaying slices fmt.Println(\"Original Slice:\") fmt.Printf(\"Slice 1: %s\", slice_1) fmt.Printf(\"\\nSlice 2: %s\", slice_2) fmt.Printf(\"\\nSlice 3: %s\", slice_3) // Splitting the slice of bytes // Using Split function res1 := bytes.Split(slice_1, []byte(\"eek\")) res2 := bytes.Split(slice_2, []byte(\"\")) res3 := bytes.Split(slice_3, []byte(\"%\")) // Display the results fmt.Printf(\"\\n\\nAfter splitting:\") fmt.Printf(\"\\nSlice 1: %s\", res1) fmt.Printf(\"\\nSlice 2: %s\", res2) fmt.Printf(\"\\nSlice 3: %s\", res3) }",
"e": 1964,
"s": 909,
"text": null
},
{
"code": null,
"e": 1972,
"s": 1964,
"text": "Output:"
},
{
"code": null,
"e": 2139,
"s": 1972,
"text": "Original Slice:\nSlice 1: !!GeeksforGeeks##\nSlice 2: Apple\nSlice 3: %g%e%e%k%s%\n\nAfter splitting:\nSlice 1: [!!G sforG s##]\nSlice 2: [A p p l e]\nSlice 3: [ g e e k s ]\n"
},
{
"code": null,
"e": 2150,
"s": 2139,
"text": "Example 2:"
},
{
"code": "// Go program to illustrate the concept// of splitting a slice of bytespackage main import ( \"bytes\" \"fmt\") func main() { // Creating and Splitting // the slice of bytes // Using Split function res1 := bytes.Split([]byte(\"****Welcome, to, GeeksforGeeks****\"), []byte(\",\")) res2 := bytes.Split([]byte(\"Learning x how x to x trim x a x slice of bytes\"), []byte(\"x\")) res3 := bytes.Split([]byte(\"GeeksforGeeks, Geek\"), []byte(\"\")) res4 := bytes.Split([]byte(\"\"), []byte(\",\")) // Display the results fmt.Printf(\"Final Value:\\n\") fmt.Printf(\"\\nSlice 1: %s\", res1) fmt.Printf(\"\\nSlice 2: %s\", res2) fmt.Printf(\"\\nSlice 3: %s\", res3) fmt.Printf(\"\\nSlice 4: %s\", res4)}",
"e": 3006,
"s": 2150,
"text": null
},
{
"code": null,
"e": 3014,
"s": 3006,
"text": "Output:"
},
{
"code": null,
"e": 3195,
"s": 3014,
"text": "Final Value:\n\nSlice 1: [****Welcome to GeeksforGeeks****]\nSlice 2: [Learning how to trim a slice of bytes]\nSlice 3: [G e e k s f o r G e e k s , G e e k]\nSlice 4: []\n"
},
{
"code": null,
"e": 3202,
"s": 3195,
"text": "Golang"
},
{
"code": null,
"e": 3216,
"s": 3202,
"text": "Golang-Slices"
},
{
"code": null,
"e": 3228,
"s": 3216,
"text": "Go Language"
},
{
"code": null,
"e": 3326,
"s": 3228,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3378,
"s": 3326,
"text": "Different ways to concatenate two strings in Golang"
},
{
"code": null,
"e": 3424,
"s": 3378,
"text": "time.Sleep() Function in Golang With Examples"
},
{
"code": null,
"e": 3474,
"s": 3424,
"text": "strings.Contains Function in Golang with Examples"
},
{
"code": null,
"e": 3525,
"s": 3474,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 3572,
"s": 3525,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 3584,
"s": 3572,
"text": "Golang Maps"
},
{
"code": null,
"e": 3610,
"s": 3584,
"text": "Time Formatting in Golang"
},
{
"code": null,
"e": 3631,
"s": 3610,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 3685,
"s": 3631,
"text": "Different Ways to Find the Type of Variable in Golang"
}
] |
ggplot2 - Scatter Plots & Jitter Plots
|
Scatter Plots are similar to line graphs which are usually used for plotting. The scatter plots show how much one variable is related to another. The relationship between variables is called as correlation which is usually used in statistical methods. We will use the same dataset called “Iris” which includes a lot of variation between each variable. This is famous dataset which gives measurements in centimeters of the variables sepal length and width with petal length and width for 50 flowers from each of 3 species of iris. The species are called Iris setosa, versicolor and virginica.
Following steps are involved for creating scatter plots with “ggplot2” package −
For creating a basic scatter plot following command is executed −
> # Basic Scatter Plot
> ggplot(iris, aes(Sepal.Length, Petal.Length)) +
+ geom_point()
We can change the shape of points with a property called shape in geom_point() function.
> # Change the shape of points
> ggplot(iris, aes(Sepal.Length, Petal.Length)) +
+ geom_point(shape=1)
We can add color to the points which is added in the required scatter plots.
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+ geom_point(shape=1)
In this example, we have created colors as per species which are mentioned in legends. The three species are uniquely distinguished in the mentioned plot.
Now we will focus on establishing relationship between the variables.
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+ geom_point(shape=1) +
+ geom_smooth(method=lm)
geom_smooth function aids the pattern of overlapping and creating the pattern of required variables.
The attribute method “lm” mentions the regression line which needs to be developed.
> # Add a regression line
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+ geom_point(shape=1) +
+ geom_smooth(method=lm)
We can also add a regression line with no shaded confidence region with below mentioned syntax −
># Add a regression line but no shaded confidence region
> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +
+ geom_point(shape=1) +
+ geom_smooth(method=lm, se=FALSE)
Shaded regions represent things other than confidence regions.
Jitter plots include special effects with which scattered plots can be depicted. Jitter is nothing but a random value that is assigned to dots to separate them as mentioned below −
> ggplot(mpg, aes(cyl, hwy)) +
+ geom_point() +
+ geom_jitter(aes(colour = class))
|
[
{
"code": null,
"e": 2748,
"s": 2156,
"text": "Scatter Plots are similar to line graphs which are usually used for plotting. The scatter plots show how much one variable is related to another. The relationship between variables is called as correlation which is usually used in statistical methods. We will use the same dataset called “Iris” which includes a lot of variation between each variable. This is famous dataset which gives measurements in centimeters of the variables sepal length and width with petal length and width for 50 flowers from each of 3 species of iris. The species are called Iris setosa, versicolor and virginica."
},
{
"code": null,
"e": 2829,
"s": 2748,
"text": "Following steps are involved for creating scatter plots with “ggplot2” package −"
},
{
"code": null,
"e": 2895,
"s": 2829,
"text": "For creating a basic scatter plot following command is executed −"
},
{
"code": null,
"e": 2987,
"s": 2895,
"text": "> # Basic Scatter Plot\n> ggplot(iris, aes(Sepal.Length, Petal.Length)) +\n+ geom_point()\n"
},
{
"code": null,
"e": 3076,
"s": 2987,
"text": "We can change the shape of points with a property called shape in geom_point() function."
},
{
"code": null,
"e": 3183,
"s": 3076,
"text": "> # Change the shape of points\n> ggplot(iris, aes(Sepal.Length, Petal.Length)) +\n+ geom_point(shape=1)\n"
},
{
"code": null,
"e": 3260,
"s": 3183,
"text": "We can add color to the points which is added in the required scatter plots."
},
{
"code": null,
"e": 3352,
"s": 3260,
"text": "> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +\n+ geom_point(shape=1)\n"
},
{
"code": null,
"e": 3507,
"s": 3352,
"text": "In this example, we have created colors as per species which are mentioned in legends. The three species are uniquely distinguished in the mentioned plot."
},
{
"code": null,
"e": 3577,
"s": 3507,
"text": "Now we will focus on establishing relationship between the variables."
},
{
"code": null,
"e": 3699,
"s": 3577,
"text": "> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +\n+ geom_point(shape=1) +\n+ geom_smooth(method=lm)\n"
},
{
"code": null,
"e": 3800,
"s": 3699,
"text": "geom_smooth function aids the pattern of overlapping and creating the pattern of required variables."
},
{
"code": null,
"e": 3884,
"s": 3800,
"text": "The attribute method “lm” mentions the regression line which needs to be developed."
},
{
"code": null,
"e": 4032,
"s": 3884,
"text": "> # Add a regression line\n> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +\n+ geom_point(shape=1) +\n+ geom_smooth(method=lm)\n"
},
{
"code": null,
"e": 4129,
"s": 4032,
"text": "We can also add a regression line with no shaded confidence region with below mentioned syntax −"
},
{
"code": null,
"e": 4318,
"s": 4129,
"text": "># Add a regression line but no shaded confidence region\n> ggplot(iris, aes(Sepal.Length, Petal.Length, colour=Species)) +\n+ geom_point(shape=1) +\n+ geom_smooth(method=lm, se=FALSE)\n"
},
{
"code": null,
"e": 4381,
"s": 4318,
"text": "Shaded regions represent things other than confidence regions."
},
{
"code": null,
"e": 4562,
"s": 4381,
"text": "Jitter plots include special effects with which scattered plots can be depicted. Jitter is nothing but a random value that is assigned to dots to separate them as mentioned below −"
}
] |
Gzip Command in Linux
|
20 May, 2019
gzip command compresses files. Each single file is compressed into a single file. The compressed file consists of a GNU zip header and deflated data.If given a file as an argument, gzip compresses the file, adds a “.gz” suffix, and deletes the original file. With no arguments, gzip compresses the standard input and writes the compressed file to standard output.Difference between Gzip and zip command in Unix and when to use which command
ZIP and GZIP are two very popular methods of compressing files, in order to save space, or to reduce the amount of time needed to transmit the files across the network, or internet.
In general, GZIP is much better compared to ZIP, in terms of compression, especially when compressing a huge number of files.
The common practice with GZIP, is to archive all the files into a single tarball before compression. In ZIP files, the individual files are compressed and then added to the archive.
When you want to pull a single file from a ZIP, it is simply extracted, then decompressed. With GZIP, the whole file needs to be decompressed before you can extract the file you want from the archive.
When pulling a 1MB file from a 10GB archive, it is quite clear that it would take a lot longer in GZIP, than in ZIP.
GZIP’s disadvantage in how it operates, is also responsible for GZIP’s advantage. Since the compression algorithm in GZIP compresses one large file instead of multiple smaller ones, it can take advantage of the redundancy in the files to reduce the file size even further.
If you archive and compress 10 identical files with ZIP and GZIP, the ZIP file would be over 10 times bigger than the resulting GZIP file.
Syntax :
gzip [Options] [filenames]
Example:
$ gzip mydoc.txt
This command will create a compressed file of mydoc.txt named as mydoc.txt.gz and delete the original file.
Options :
-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the “gzip” command won’t ordinarily work.To force the “gzip” command to do its stuff simply use -f option: $ gzip -f myfile1.txtThis will forcefully compress a file named myfile.txt even if there already exists a file named as myfile.txt.gz-k option :By default when you compress a file using the “gzip” command you end up with a new file with the extension “.gz”.If you want to compress the file and keep the original file you have to run the gzip command with -k option: $ gzip -k mydoc.txtThe above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”.-L option : This option displays the gzip license.$ gzip -L filename.gzOUTPUT :Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)
Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
All rights reserved.-r option : This option can compress every file in a folder and its subfolders.This option doesn’t create one file called foldername.gz. Instead, it traverses the directory structure and compresses each file in that folder structure.gzip -r testfolderThis will compress all the files present in the testfolder.-[1-9] option : It allows to change the compression level.A file can be compressed in different ways. For instance, you can go for a smaller compression which will work faster or you can go for maximum compression which has the tradeoff of taking longer to run.The speed and compression level can vary by levels using numbers between 1 and 9. $ gzip -1 mydoc.txtThis will get maximum compression at the slowest speed$ gzip -9 mydoc.txtTo get minimum compression at the fastest speed-v option: This option displays the name and percentage reduction for each file compressed or decompressed.$ gzip -v mydoc.txtOUTPUT :new.txt: 18.2% -- replaced with new.txt.gz-d option :This option allows to decompress a file using the “gzip” command.$ gzip -d mydoc.txt.gzThis command will unzip the compressed file named as mydoc.txt.gz.This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the “gzip” command won’t ordinarily work.To force the “gzip” command to do its stuff simply use -f option: $ gzip -f myfile1.txtThis will forcefully compress a file named myfile.txt even if there already exists a file named as myfile.txt.gz
$ gzip -f myfile1.txt
This will forcefully compress a file named myfile.txt even if there already exists a file named as myfile.txt.gz
-k option :By default when you compress a file using the “gzip” command you end up with a new file with the extension “.gz”.If you want to compress the file and keep the original file you have to run the gzip command with -k option: $ gzip -k mydoc.txtThe above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”.
$ gzip -k mydoc.txt
The above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”.
-L option : This option displays the gzip license.$ gzip -L filename.gzOUTPUT :Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)
Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
All rights reserved.
$ gzip -L filename.gz
OUTPUT :
Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)
Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
All rights reserved.
-r option : This option can compress every file in a folder and its subfolders.This option doesn’t create one file called foldername.gz. Instead, it traverses the directory structure and compresses each file in that folder structure.gzip -r testfolderThis will compress all the files present in the testfolder.
gzip -r testfolder
This will compress all the files present in the testfolder.
-[1-9] option : It allows to change the compression level.A file can be compressed in different ways. For instance, you can go for a smaller compression which will work faster or you can go for maximum compression which has the tradeoff of taking longer to run.The speed and compression level can vary by levels using numbers between 1 and 9. $ gzip -1 mydoc.txtThis will get maximum compression at the slowest speed$ gzip -9 mydoc.txtTo get minimum compression at the fastest speed
$ gzip -1 mydoc.txt
This will get maximum compression at the slowest speed
$ gzip -9 mydoc.txt
To get minimum compression at the fastest speed
-v option: This option displays the name and percentage reduction for each file compressed or decompressed.$ gzip -v mydoc.txtOUTPUT :new.txt: 18.2% -- replaced with new.txt.gz
$ gzip -v mydoc.txt
OUTPUT :
new.txt: 18.2% -- replaced with new.txt.gz
-d option :This option allows to decompress a file using the “gzip” command.$ gzip -d mydoc.txt.gzThis command will unzip the compressed file named as mydoc.txt.gz.
$ gzip -d mydoc.txt.gz
This command will unzip the compressed file named as mydoc.txt.gz.
This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
linux-command
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
curl command in Linux with Examples
Tail command in Linux with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
echo command in Linux with Examples
Cat command in Linux with examples
touch command in Linux with Examples
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 495,
"s": 54,
"text": "gzip command compresses files. Each single file is compressed into a single file. The compressed file consists of a GNU zip header and deflated data.If given a file as an argument, gzip compresses the file, adds a “.gz” suffix, and deletes the original file. With no arguments, gzip compresses the standard input and writes the compressed file to standard output.Difference between Gzip and zip command in Unix and when to use which command"
},
{
"code": null,
"e": 677,
"s": 495,
"text": "ZIP and GZIP are two very popular methods of compressing files, in order to save space, or to reduce the amount of time needed to transmit the files across the network, or internet."
},
{
"code": null,
"e": 803,
"s": 677,
"text": "In general, GZIP is much better compared to ZIP, in terms of compression, especially when compressing a huge number of files."
},
{
"code": null,
"e": 985,
"s": 803,
"text": "The common practice with GZIP, is to archive all the files into a single tarball before compression. In ZIP files, the individual files are compressed and then added to the archive."
},
{
"code": null,
"e": 1186,
"s": 985,
"text": "When you want to pull a single file from a ZIP, it is simply extracted, then decompressed. With GZIP, the whole file needs to be decompressed before you can extract the file you want from the archive."
},
{
"code": null,
"e": 1303,
"s": 1186,
"text": "When pulling a 1MB file from a 10GB archive, it is quite clear that it would take a lot longer in GZIP, than in ZIP."
},
{
"code": null,
"e": 1576,
"s": 1303,
"text": "GZIP’s disadvantage in how it operates, is also responsible for GZIP’s advantage. Since the compression algorithm in GZIP compresses one large file instead of multiple smaller ones, it can take advantage of the redundancy in the files to reduce the file size even further."
},
{
"code": null,
"e": 1715,
"s": 1576,
"text": "If you archive and compress 10 identical files with ZIP and GZIP, the ZIP file would be over 10 times bigger than the resulting GZIP file."
},
{
"code": null,
"e": 1724,
"s": 1715,
"text": "Syntax :"
},
{
"code": null,
"e": 1753,
"s": 1724,
"text": " gzip [Options] [filenames]\n"
},
{
"code": null,
"e": 1762,
"s": 1753,
"text": "Example:"
},
{
"code": null,
"e": 1780,
"s": 1762,
"text": "$ gzip mydoc.txt\n"
},
{
"code": null,
"e": 1888,
"s": 1780,
"text": "This command will create a compressed file of mydoc.txt named as mydoc.txt.gz and delete the original file."
},
{
"code": null,
"e": 1898,
"s": 1888,
"text": "Options :"
},
{
"code": null,
"e": 4464,
"s": 1898,
"text": "-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the “gzip” command won’t ordinarily work.To force the “gzip” command to do its stuff simply use -f option: $ gzip -f myfile1.txtThis will forcefully compress a file named myfile.txt even if there already exists a file named as myfile.txt.gz-k option :By default when you compress a file using the “gzip” command you end up with a new file with the extension “.gz”.If you want to compress the file and keep the original file you have to run the gzip command with -k option: $ gzip -k mydoc.txtThe above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”.-L option : This option displays the gzip license.$ gzip -L filename.gzOUTPUT :Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)\nCopyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\nAll rights reserved.-r option : This option can compress every file in a folder and its subfolders.This option doesn’t create one file called foldername.gz. Instead, it traverses the directory structure and compresses each file in that folder structure.gzip -r testfolderThis will compress all the files present in the testfolder.-[1-9] option : It allows to change the compression level.A file can be compressed in different ways. For instance, you can go for a smaller compression which will work faster or you can go for maximum compression which has the tradeoff of taking longer to run.The speed and compression level can vary by levels using numbers between 1 and 9. $ gzip -1 mydoc.txtThis will get maximum compression at the slowest speed$ gzip -9 mydoc.txtTo get minimum compression at the fastest speed-v option: This option displays the name and percentage reduction for each file compressed or decompressed.$ gzip -v mydoc.txtOUTPUT :new.txt: 18.2% -- replaced with new.txt.gz-d option :This option allows to decompress a file using the “gzip” command.$ gzip -d mydoc.txt.gzThis command will unzip the compressed file named as mydoc.txt.gz.This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4882,
"s": 4464,
"text": "-f option : Sometimes a file cannot be compressed. Perhaps you are trying to compress a file called “myfile1” but there is already a file called “myfile1.gz”. In this instance, the “gzip” command won’t ordinarily work.To force the “gzip” command to do its stuff simply use -f option: $ gzip -f myfile1.txtThis will forcefully compress a file named myfile.txt even if there already exists a file named as myfile.txt.gz"
},
{
"code": null,
"e": 4905,
"s": 4882,
"text": " $ gzip -f myfile1.txt"
},
{
"code": null,
"e": 5018,
"s": 4905,
"text": "This will forcefully compress a file named myfile.txt even if there already exists a file named as myfile.txt.gz"
},
{
"code": null,
"e": 5352,
"s": 5018,
"text": "-k option :By default when you compress a file using the “gzip” command you end up with a new file with the extension “.gz”.If you want to compress the file and keep the original file you have to run the gzip command with -k option: $ gzip -k mydoc.txtThe above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”."
},
{
"code": null,
"e": 5373,
"s": 5352,
"text": " $ gzip -k mydoc.txt"
},
{
"code": null,
"e": 5455,
"s": 5373,
"text": "The above command would end up with a file called “mydoc.txt.gz” and “mydoc.txt”."
},
{
"code": null,
"e": 5668,
"s": 5455,
"text": "-L option : This option displays the gzip license.$ gzip -L filename.gzOUTPUT :Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)\nCopyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\nAll rights reserved."
},
{
"code": null,
"e": 5690,
"s": 5668,
"text": "$ gzip -L filename.gz"
},
{
"code": null,
"e": 5699,
"s": 5690,
"text": "OUTPUT :"
},
{
"code": null,
"e": 5833,
"s": 5699,
"text": "Apple gzip 264.50.1 (based on FreeBSD gzip 20111009)\nCopyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\nAll rights reserved."
},
{
"code": null,
"e": 6144,
"s": 5833,
"text": "-r option : This option can compress every file in a folder and its subfolders.This option doesn’t create one file called foldername.gz. Instead, it traverses the directory structure and compresses each file in that folder structure.gzip -r testfolderThis will compress all the files present in the testfolder."
},
{
"code": null,
"e": 6163,
"s": 6144,
"text": "gzip -r testfolder"
},
{
"code": null,
"e": 6223,
"s": 6163,
"text": "This will compress all the files present in the testfolder."
},
{
"code": null,
"e": 6706,
"s": 6223,
"text": "-[1-9] option : It allows to change the compression level.A file can be compressed in different ways. For instance, you can go for a smaller compression which will work faster or you can go for maximum compression which has the tradeoff of taking longer to run.The speed and compression level can vary by levels using numbers between 1 and 9. $ gzip -1 mydoc.txtThis will get maximum compression at the slowest speed$ gzip -9 mydoc.txtTo get minimum compression at the fastest speed"
},
{
"code": null,
"e": 6727,
"s": 6706,
"text": " $ gzip -1 mydoc.txt"
},
{
"code": null,
"e": 6782,
"s": 6727,
"text": "This will get maximum compression at the slowest speed"
},
{
"code": null,
"e": 6802,
"s": 6782,
"text": "$ gzip -9 mydoc.txt"
},
{
"code": null,
"e": 6850,
"s": 6802,
"text": "To get minimum compression at the fastest speed"
},
{
"code": null,
"e": 7033,
"s": 6850,
"text": "-v option: This option displays the name and percentage reduction for each file compressed or decompressed.$ gzip -v mydoc.txtOUTPUT :new.txt: 18.2% -- replaced with new.txt.gz"
},
{
"code": null,
"e": 7053,
"s": 7033,
"text": "$ gzip -v mydoc.txt"
},
{
"code": null,
"e": 7062,
"s": 7053,
"text": "OUTPUT :"
},
{
"code": null,
"e": 7111,
"s": 7062,
"text": "new.txt: 18.2% -- replaced with new.txt.gz"
},
{
"code": null,
"e": 7276,
"s": 7111,
"text": "-d option :This option allows to decompress a file using the “gzip” command.$ gzip -d mydoc.txt.gzThis command will unzip the compressed file named as mydoc.txt.gz."
},
{
"code": null,
"e": 7299,
"s": 7276,
"text": "$ gzip -d mydoc.txt.gz"
},
{
"code": null,
"e": 7366,
"s": 7299,
"text": "This command will unzip the compressed file named as mydoc.txt.gz."
},
{
"code": null,
"e": 7673,
"s": 7366,
"text": "This article is contributed by Shubrodeep Banerjee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7798,
"s": 7673,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 7812,
"s": 7798,
"text": "linux-command"
},
{
"code": null,
"e": 7832,
"s": 7812,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 7843,
"s": 7832,
"text": "Linux-Unix"
},
{
"code": null,
"e": 7941,
"s": 7843,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7977,
"s": 7941,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 8013,
"s": 7977,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 8051,
"s": 8013,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 8089,
"s": 8051,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 8115,
"s": 8089,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 8150,
"s": 8115,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 8188,
"s": 8150,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 8224,
"s": 8188,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 8259,
"s": 8224,
"text": "Cat command in Linux with examples"
}
] |
Py-Facts – 10 interesting facts about Python
|
09 Mar, 2022
Python is one of the most popular programming languages nowadays on account of its code readability and simplicity. All thanks to Guido Van Rossum, its creator.
I’ve compiled a list of 10 interesting Facts in the Python Language. Here they are:1. There is actually a poem written by Tim Peters named as THE ZEN OF PYTHON which can be read by just writing import this in the interpreter.
Python3
# Try to guess the result before you actually run itimport this
Output:
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
2. One can return multiple values in Python. Don’t believe ? See the below code snippet:
Python3
# Multiple Return Values in Python!def func(): return 1, 2, 3, 4, 5 one, two, three, four, five = func() print(one, two, three, four, five)
Output:
(1, 2, 3, 4, 5)
3. One can use an “else” clause with a “for” loop in Python. It’s a special type of syntax that executes only if the for loop exits naturally, without any break statements.
Python3
def func(array): for num in array: if num%2==0: print(num) break # Case1: Break is called, so 'else' wouldn't be executed. else: # Case 2: 'else' executed since break is not called print("No call for Break. Else is executed") print("1st Case:")a = [2]func(a)print("2nd Case:")a = [1]func(a)
Output:
1st Case:
2
2nd Case:
No call for Break. Else is executed
4. In Python, everything is done by reference. It doesn’t support pointers.
5. Function Argument Unpacking is another awesome feature of Python. One can unpack a list or a dictionary as function arguments using * and ** respectively. This is commonly known as the Splat operator. Example here
Python3
def point(x, y): print(x,y) foo_list = (3, 4)bar_dict = {'y': 3, 'x': 2} point(*foo_list) # Unpacking Listspoint(**bar_dict) # Unpacking Dictionaries
Output:
3 4
2 3
6. Want to find the index inside a for loop? Wrap an iterable with ‘enumerate’ and it will yield the item along with its index. See this code snippet
Python3
# Know the index fastervowels=['a','e','i','o','u']for i, letter in enumerate(vowels): print (i, letter)
Output:
(0, 'a')
(1, 'e')
(2, 'i')
(3, 'o')
(4, 'u')
7. One can chain comparison operators in Python answer= 1<x<10 is executable in Python. More examples here
Python3
# Chaining Comparison Operatorsi = 5; ans = 1 < i < 10print(ans) ans = 10 > i <= 9print(ans) ans = 5 == iprint(ans)
Output:
True
True
True
8. We can’t define Infinities right? But wait! Not for Python. See this amazing example
Python3
# Positive Infinityp_infinity = float('Inf') if 99999999999999 > p_infinity: print("The number is greater than Infinity!")else: print("Infinity is greatest") # Negative Infinityn_infinity = float('-Inf')if -99999999999999 < n_infinity: print("The number is lesser than Negative Infinity!")else: print("Negative Infinity is least")
Output:
Infinity is greatest
Negative Infinity is least
9. Instead of building a list with a loop, one can build it more concisely with a list comprehension. See this code for more understanding.
Python3
# Simple List Appenda = []for x in range(0,10): a.append(x)print(a) # List Comprehensionprint([x for x in a])
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10. Finally, Python’s special Slice Operator. It is a way to get items from lists, as well as change them. See this code snippet
Python3
# Slice Operatora = [1,2,3,4,5] print(a[0:2]) # Choose elements [0-2), upper-bound noninclusive print(a[0:-1]) # Choose all but the last print(a[::-1]) # Reverse the list print(a[::2]) # Skip by 2 print(a[::-2]) # Skip by -2 from the back
Output:
[1, 2]
[1, 2, 3, 4]
[5, 4, 3, 2, 1]
[1, 3, 5]
[5, 3, 1]
This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
surinderdawra388
amartyaghoshgfg
interesting-facts
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 213,
"s": 52,
"text": "Python is one of the most popular programming languages nowadays on account of its code readability and simplicity. All thanks to Guido Van Rossum, its creator."
},
{
"code": null,
"e": 439,
"s": 213,
"text": "I’ve compiled a list of 10 interesting Facts in the Python Language. Here they are:1. There is actually a poem written by Tim Peters named as THE ZEN OF PYTHON which can be read by just writing import this in the interpreter."
},
{
"code": null,
"e": 447,
"s": 439,
"text": "Python3"
},
{
"code": "# Try to guess the result before you actually run itimport this",
"e": 511,
"s": 447,
"text": null
},
{
"code": null,
"e": 521,
"s": 511,
"text": "Output: "
},
{
"code": null,
"e": 1395,
"s": 521,
"text": "The Zen of Python, by Tim Peters\nBeautiful is better than ugly.\n\nExplicit is better than implicit.\n\nSimple is better than complex.\n\nComplex is better than complicated.\n\nFlat is better than nested.\n\nSparse is better than dense.\n\nReadability counts.\n\nSpecial cases aren't special enough to break the rules.\n\nAlthough practicality beats purity.\n\nErrors should never pass silently.\n\nUnless explicitly silenced.\n\nIn the face of ambiguity, refuse the temptation to guess.\n\nThere should be one-- and preferably only one --obvious way to do it.\n\nAlthough that way may not be obvious at first unless you're Dutch.\n\nNow is better than never.\n\nAlthough never is often better than *right* now.\n\nIf the implementation is hard to explain, it's a bad idea.\n\nIf the implementation is easy to explain, it may be a good idea.\n\nNamespaces are one honking great idea -- let's do more of those!"
},
{
"code": null,
"e": 1485,
"s": 1395,
"text": "2. One can return multiple values in Python. Don’t believe ? See the below code snippet: "
},
{
"code": null,
"e": 1493,
"s": 1485,
"text": "Python3"
},
{
"code": "# Multiple Return Values in Python!def func(): return 1, 2, 3, 4, 5 one, two, three, four, five = func() print(one, two, three, four, five)",
"e": 1635,
"s": 1493,
"text": null
},
{
"code": null,
"e": 1645,
"s": 1635,
"text": "Output: "
},
{
"code": null,
"e": 1661,
"s": 1645,
"text": "(1, 2, 3, 4, 5)"
},
{
"code": null,
"e": 1836,
"s": 1663,
"text": "3. One can use an “else” clause with a “for” loop in Python. It’s a special type of syntax that executes only if the for loop exits naturally, without any break statements."
},
{
"code": null,
"e": 1846,
"s": 1838,
"text": "Python3"
},
{
"code": "def func(array): for num in array: if num%2==0: print(num) break # Case1: Break is called, so 'else' wouldn't be executed. else: # Case 2: 'else' executed since break is not called print(\"No call for Break. Else is executed\") print(\"1st Case:\")a = [2]func(a)print(\"2nd Case:\")a = [1]func(a)",
"e": 2181,
"s": 1846,
"text": null
},
{
"code": null,
"e": 2191,
"s": 2181,
"text": "Output: "
},
{
"code": null,
"e": 2252,
"s": 2191,
"text": "1st Case:\n\n2\n\n2nd Case:\n\nNo call for Break. Else is executed"
},
{
"code": null,
"e": 2330,
"s": 2254,
"text": "4. In Python, everything is done by reference. It doesn’t support pointers."
},
{
"code": null,
"e": 2549,
"s": 2332,
"text": "5. Function Argument Unpacking is another awesome feature of Python. One can unpack a list or a dictionary as function arguments using * and ** respectively. This is commonly known as the Splat operator. Example here"
},
{
"code": null,
"e": 2559,
"s": 2551,
"text": "Python3"
},
{
"code": "def point(x, y): print(x,y) foo_list = (3, 4)bar_dict = {'y': 3, 'x': 2} point(*foo_list) # Unpacking Listspoint(**bar_dict) # Unpacking Dictionaries",
"e": 2712,
"s": 2559,
"text": null
},
{
"code": null,
"e": 2720,
"s": 2712,
"text": "Output:"
},
{
"code": null,
"e": 2729,
"s": 2720,
"text": "3 4\n\n2 3"
},
{
"code": null,
"e": 2879,
"s": 2729,
"text": "6. Want to find the index inside a for loop? Wrap an iterable with ‘enumerate’ and it will yield the item along with its index. See this code snippet"
},
{
"code": null,
"e": 2887,
"s": 2879,
"text": "Python3"
},
{
"code": "# Know the index fastervowels=['a','e','i','o','u']for i, letter in enumerate(vowels): print (i, letter)",
"e": 2995,
"s": 2887,
"text": null
},
{
"code": null,
"e": 3003,
"s": 2995,
"text": "Output:"
},
{
"code": null,
"e": 3052,
"s": 3003,
"text": "(0, 'a')\n\n(1, 'e')\n\n(2, 'i')\n\n(3, 'o')\n\n(4, 'u')"
},
{
"code": null,
"e": 3159,
"s": 3052,
"text": "7. One can chain comparison operators in Python answer= 1<x<10 is executable in Python. More examples here"
},
{
"code": null,
"e": 3167,
"s": 3159,
"text": "Python3"
},
{
"code": "# Chaining Comparison Operatorsi = 5; ans = 1 < i < 10print(ans) ans = 10 > i <= 9print(ans) ans = 5 == iprint(ans)",
"e": 3283,
"s": 3167,
"text": null
},
{
"code": null,
"e": 3293,
"s": 3283,
"text": "Output: "
},
{
"code": null,
"e": 3310,
"s": 3293,
"text": "True\n\nTrue\n\nTrue"
},
{
"code": null,
"e": 3400,
"s": 3312,
"text": "8. We can’t define Infinities right? But wait! Not for Python. See this amazing example"
},
{
"code": null,
"e": 3410,
"s": 3402,
"text": "Python3"
},
{
"code": "# Positive Infinityp_infinity = float('Inf') if 99999999999999 > p_infinity: print(\"The number is greater than Infinity!\")else: print(\"Infinity is greatest\") # Negative Infinityn_infinity = float('-Inf')if -99999999999999 < n_infinity: print(\"The number is lesser than Negative Infinity!\")else: print(\"Negative Infinity is least\")",
"e": 3753,
"s": 3410,
"text": null
},
{
"code": null,
"e": 3761,
"s": 3753,
"text": "Output:"
},
{
"code": null,
"e": 3810,
"s": 3761,
"text": "Infinity is greatest\n\nNegative Infinity is least"
},
{
"code": null,
"e": 3950,
"s": 3810,
"text": "9. Instead of building a list with a loop, one can build it more concisely with a list comprehension. See this code for more understanding."
},
{
"code": null,
"e": 3958,
"s": 3950,
"text": "Python3"
},
{
"code": "# Simple List Appenda = []for x in range(0,10): a.append(x)print(a) # List Comprehensionprint([x for x in a])",
"e": 4071,
"s": 3958,
"text": null
},
{
"code": null,
"e": 4081,
"s": 4071,
"text": "Output: "
},
{
"code": null,
"e": 4144,
"s": 4081,
"text": "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 4275,
"s": 4146,
"text": "10. Finally, Python’s special Slice Operator. It is a way to get items from lists, as well as change them. See this code snippet"
},
{
"code": null,
"e": 4285,
"s": 4277,
"text": "Python3"
},
{
"code": "# Slice Operatora = [1,2,3,4,5] print(a[0:2]) # Choose elements [0-2), upper-bound noninclusive print(a[0:-1]) # Choose all but the last print(a[::-1]) # Reverse the list print(a[::2]) # Skip by 2 print(a[::-2]) # Skip by -2 from the back",
"e": 4524,
"s": 4285,
"text": null
},
{
"code": null,
"e": 4534,
"s": 4524,
"text": "Output: "
},
{
"code": null,
"e": 4594,
"s": 4534,
"text": "[1, 2]\n\n[1, 2, 3, 4]\n\n[5, 4, 3, 2, 1]\n\n[1, 3, 5]\n\n[5, 3, 1]"
},
{
"code": null,
"e": 4986,
"s": 4594,
"text": " This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 5003,
"s": 4986,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5019,
"s": 5003,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 5037,
"s": 5019,
"text": "interesting-facts"
},
{
"code": null,
"e": 5044,
"s": 5037,
"text": "Python"
},
{
"code": null,
"e": 5063,
"s": 5044,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5161,
"s": 5063,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5179,
"s": 5161,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5221,
"s": 5179,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5243,
"s": 5221,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5278,
"s": 5243,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5304,
"s": 5278,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5336,
"s": 5304,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5365,
"s": 5336,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5395,
"s": 5365,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 5422,
"s": 5395,
"text": "Python Classes and Objects"
}
] |
Python NLTK | nltk.tokenize.mwe()
|
07 Jun, 2019
With the help of NLTK nltk.tokenize.mwe() method, we can tokenize the audio stream into multi_word expression token which helps to bind the tokens with underscore by using nltk.tokenize.mwe() method. Remember it is case sensitive.
Syntax : MWETokenizer.tokenize()Return : Return bind tokens as one if declared before.
Example #1 :In this example we are using MWETokenizer.tokenize() method, which used to bind the tokens which is defined before. We can also add the predefined tokens by using tokenizer.add_mwe() method.
# import MWETokenizer() method from nltkfrom nltk.tokenize import MWETokenizer # Create a reference variable for Class MWETokenizertk = MWETokenizer([('g', 'f', 'g'), ('geeks', 'for', 'geeks')]) # Create a string inputgfg = "geeks for geeks g f g" # Use tokenize methodgeek = tk.tokenize(gfg.split()) print(geek)
Output :
[‘geeks_for_geeks’, ‘g_f_g’]
Example #2 :
# import MWETokenizer() method from nltkfrom nltk.tokenize import MWETokenizer # Create a reference variable for Class MWETokenizertk = MWETokenizer([('g', 'f', 'g'), ('geeks', 'for', 'geeks')])tk.add_mwe(('who', 'are', 'you')) # Create a string inputgfg = "who are you at geeks for geeks" # Use tokenize methodgeek = tk.tokenize(gfg.split()) print(geek)
Output :
[‘who_are_you’, ‘at’, ‘geeks_for_geeks’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jun, 2019"
},
{
"code": null,
"e": 259,
"s": 28,
"text": "With the help of NLTK nltk.tokenize.mwe() method, we can tokenize the audio stream into multi_word expression token which helps to bind the tokens with underscore by using nltk.tokenize.mwe() method. Remember it is case sensitive."
},
{
"code": null,
"e": 346,
"s": 259,
"text": "Syntax : MWETokenizer.tokenize()Return : Return bind tokens as one if declared before."
},
{
"code": null,
"e": 549,
"s": 346,
"text": "Example #1 :In this example we are using MWETokenizer.tokenize() method, which used to bind the tokens which is defined before. We can also add the predefined tokens by using tokenizer.add_mwe() method."
},
{
"code": "# import MWETokenizer() method from nltkfrom nltk.tokenize import MWETokenizer # Create a reference variable for Class MWETokenizertk = MWETokenizer([('g', 'f', 'g'), ('geeks', 'for', 'geeks')]) # Create a string inputgfg = \"geeks for geeks g f g\" # Use tokenize methodgeek = tk.tokenize(gfg.split()) print(geek)",
"e": 870,
"s": 549,
"text": null
},
{
"code": null,
"e": 879,
"s": 870,
"text": "Output :"
},
{
"code": null,
"e": 908,
"s": 879,
"text": "[‘geeks_for_geeks’, ‘g_f_g’]"
},
{
"code": null,
"e": 921,
"s": 908,
"text": "Example #2 :"
},
{
"code": "# import MWETokenizer() method from nltkfrom nltk.tokenize import MWETokenizer # Create a reference variable for Class MWETokenizertk = MWETokenizer([('g', 'f', 'g'), ('geeks', 'for', 'geeks')])tk.add_mwe(('who', 'are', 'you')) # Create a string inputgfg = \"who are you at geeks for geeks\" # Use tokenize methodgeek = tk.tokenize(gfg.split()) print(geek)",
"e": 1284,
"s": 921,
"text": null
},
{
"code": null,
"e": 1293,
"s": 1284,
"text": "Output :"
},
{
"code": null,
"e": 1334,
"s": 1293,
"text": "[‘who_are_you’, ‘at’, ‘geeks_for_geeks’]"
},
{
"code": null,
"e": 1346,
"s": 1334,
"text": "Python-nltk"
},
{
"code": null,
"e": 1353,
"s": 1346,
"text": "Python"
},
{
"code": null,
"e": 1451,
"s": 1353,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1483,
"s": 1451,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1510,
"s": 1483,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1531,
"s": 1510,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1554,
"s": 1531,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1610,
"s": 1554,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1641,
"s": 1610,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1683,
"s": 1641,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1725,
"s": 1683,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1764,
"s": 1725,
"text": "Python | Get unique values from a list"
}
] |
Reference Variable in Java
|
13 Oct, 2021
Before We Started with the Reference variable we should know about the following facts.
1. When we create an object (instance) of class then space is reserved in heap memory. Let’s understand with the help of an example.
Demo D1 = new Demo();
Now, The space in the heap Memory is created but the question is how to access that space?.
Then, We create a Pointing element or simply called Reference variable which simply points out the Object(the created space in a Heap Memory).
Understanding Reference variable
1. Reference variable is used to point object/values.
2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.
3. Reference variable can also store null value. By default, if no object is passed to a reference variable then it will store a null value.
4. You can access object members using a reference variable using dot syntax.
<reference variable name >.<instance variable_name / method_name>
Example:
Java
// Java program to demonstrate reference// variable in java import java.io.*; class Demo { int x = 10; int display() { System.out.println("x = " + x); return 0; }} class Main { public static void main(String[] args) { Demo D1 = new Demo(); // point 1 System.out.println(D1); // point 2 System.out.println(D1.display()); // point 3 }}
Demo@214c265e
x = 10
0
Let us see what is actually happening step by step.
1. When we create an object of demo class new DEMO();, the default constructor is called and returns a reference of the object, and simply this reference will be stored to the reference variable D1 (As we know that associativity is Right-hand side to left-hand side).
2. The value of a reference variable is a reference. When we attempt to print the value of a reference variable, the output contains the type of the variable and the hash code created for it by Java: the string Demo@214c265e tells us that the given variable is of type Name and its hexadecimal format of hash code is 214c265e.
3. At this point we will access the methods display() of the class demo using our custom reference variable that we created.
BINDING UP : The constructor call returns a value that is a reference to the newly-created object. The equality sign tells the program that the value of the right-hand side expression is to be copied as the value of the variable on the left-hand side. The reference to the newly-created object, returned by the constructor call, is copied as the value of the variable.
Java
import java.io.*;class Demo { int x = 10; int display() { System.out.println("x = " + x); return 0; }} class Main { public static void main(String[] args) { // create instance Demo D1 = new Demo(); // accessing instance(object) variable System.out.println(D1.x); // point 3 // accessing instance(object) method D1.display(); }}
10
x = 10
Java
// Accessing instance methods import java.io.*;class Demo { int x = 10; int display() { System.out.println("x = " + x); return 0; }}class Main { public static void main(String[] args) { // create instances Demo D1 = new Demo(); Demo M1 = new Demo(); Demo Q1 = new Demo(); }}
Java
// Pointing to same instance memory import java.io.*;class Demo { int x = 10; int display() { System.out.println("x = " + x); return 0; }}class Main { public static void main(String[] args) { // create instance Demo D1 = new Demo(); // point to same reference Demo G1 = D1; Demo M1 = new Demo(); Demo Q1 = M1; // updating the value of x using G! // reference variable G1.x = 25; System.out.println(G1.x); // Point 1 System.out.println(D1.x); // Point 2 }}
25
25
Note:
Here we pass G1 and Q1 reference variable point out the same object respectively. Secondly At Point 1 we try to get the value of the object with G1 reference variable which shows it as 25 and At Point 2 we try to get the value of an object with D1 reference variable which shows it as 25 as well. This will prove that the modification in the object can be done by using any reference variable but the condition is it should hold the same reference.
1. Reference Variable as Method Parameters:
As the value of a primitive variable is directly stored in the variable, whereas the value of a reference variable holds a reference to an object. We also mentioned that assigning a value with the equality sign copies the value (possibly of some variable) on the right-hand side and stores it as the value of the left-hand-side variable. A similar kind of copying occurs during a method call. Regardless of whether the variable is primitive or reference type, a copy of the value is passed to the method’s argument and copied to that argument.
Note: Java only supports pass by value.
But we know that the reference variable holds the reference of an instance(OBJECT) so a copy of the reference is passed to the method’s argument.
Example:
Java
// Pass by reference and value import java.io.*;class Demo { int x = 10; int y = 20; int display(Demo A, Demo B) { // Updating value using argument A.x = 95; System.out.println("x = " + x); System.out.println("y = " + y); return 0; }}class Main { public static void main(String[] args) { Demo C = new Demo(); Demo D = new Demo(); // updating value using primary reference // variable D.y = 55; C.display(C, D); // POINT 1 D.display(C, D); // POINT 2 }}
x = 95
y = 20
x = 10
y = 55
SCENE 1 :
SCENE 2:
Now, What is going on here, when we pass the reference to the method it will copy to the reference variable defined in the method signature and After that, they also have access to the object members. Here, We defined two instances named C and D. Afterwards we pass C and D to the method which further gives reference to A and B
At Point 1: A will update the value of x from 10 to 95, hence C.display() will show 95 20 but in another object D we update the value of x through D only from y =20 to 55, hence D, display() will show 10 and 55.
Note: Any Object Updation will not affect the other object’s member.
2. What if we swap the reference variables with the help of the Swap Method?
The fact is if we try to swap the reference variable, then they just swap their Pointing element there is no effect on the address of reference variable and object(Instance) Space. Let’s Understand It with the help of an example:
Java
// Swapping object references import java.io.*;class Demo { // Swapping Method int Swap(Demo A, Demo B) { Demo temp = A; A = B; B = temp; return 0; }}class Main { public static void main(String[] args) { Demo C = new Demo(); Demo D = new Demo(); // Passing C and reference variables // to Swap method C.Swap(C, D); }}
Here we created, two instances of demo class and passes it to swap method, further those C and D will copy their references to A and B respectively.Before swapping A point to C’s(Object) and B point to D’s(Object). After we perform swapping on A and B, A will now point D’s(Object) and B will Point C’s Object. As described in the figure.
Note: There is no swapping between Variables, They only change their References.
3. What if we pass arrays to the method will it be able to update the Actual Array’s values, even we know that a copy of the array is a pass to the formal Array?
The answer is YES, the values will be updated by Formal parameter, The Fact is, When we create an Array, a memory is assigned to the array of the desired size, and it returns the reference of the first array’s element that is the base address that will store to the Formal Array(Method argument). As we learned earlier every pointing reference variable can change or update the object.
Example:
Java
import java.io.*;class Demo { int arrayUpdate(int[] formalArray) { formalArray[2] = 99; formalArray[4] = 77; return 0; }}class Main { public static void main(String[] args) { Demo d1 = new Demo(); int[] actualArray = { 1, 2, 3, 4, 5 }; for (int items : actualArray) System.out.print(items + " , "); // printing array System.out.println(); d1.arrayUpdate(actualArray); System.out.println(); for (int items : actualArray) System.out.print(items + " , "); // printing array }}
1 , 2 , 3 , 4 , 5 ,
1 , 2 , 99 , 4 , 77 ,
4. this and super keywords are also Pointing Elements.
this keyword. In java, this is a reference variable that refers to the current object.
super is used to refer immediate parent class instance variable. We can use the super keyword to access the data member or field of the parent class. It is used if parent class and child class have the same fields.
5. null value of a reference variable.
Demo obj = null ;
A. The null reference can be set as the value of any reference type variable.
B. The object whose name is obj is referred to by nobody. In other words, the object has become garbage. In the Java programming language, the programmer need not worry about the program’s memory use. From time to time, the automatic garbage collector of the Java language cleans up the objects that have become garbage. If the garbage collection did not happen, the garbage objects would reserve a memory location until the end of the program execution.
Java
// null in java import java.io.*;class Demo { int x = 10; int display() { System.out.println("x = " + x); return 0; }}class Main { public static void main(String[] args) { Demo obj = null; // accessing instance(object) method Kuchbhi.display(); }}
Output
Exception in thread "main" java.lang.NullPointerException
at Main.main(File.java:17)
Java Result: 1
Here, we try to access objects’ members by a reference variable that is pointing nothing(null), and hence it shows NullPointerException. Now if you get the error, the first step is to look for variables whose value could be null. Fortunately, the error message is useful: it tells which row caused the error. Just try it out yourself!
sooda367
akki_23
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 142,
"s": 54,
"text": "Before We Started with the Reference variable we should know about the following facts."
},
{
"code": null,
"e": 275,
"s": 142,
"text": "1. When we create an object (instance) of class then space is reserved in heap memory. Let’s understand with the help of an example."
},
{
"code": null,
"e": 297,
"s": 275,
"text": "Demo D1 = new Demo();"
},
{
"code": null,
"e": 391,
"s": 297,
"text": "Now, The space in the heap Memory is created but the question is how to access that space?. "
},
{
"code": null,
"e": 536,
"s": 391,
"text": "Then, We create a Pointing element or simply called Reference variable which simply points out the Object(the created space in a Heap Memory). "
},
{
"code": null,
"e": 570,
"s": 536,
"text": "Understanding Reference variable "
},
{
"code": null,
"e": 624,
"s": 570,
"text": "1. Reference variable is used to point object/values."
},
{
"code": null,
"e": 788,
"s": 624,
"text": "2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java."
},
{
"code": null,
"e": 929,
"s": 788,
"text": "3. Reference variable can also store null value. By default, if no object is passed to a reference variable then it will store a null value."
},
{
"code": null,
"e": 1007,
"s": 929,
"text": "4. You can access object members using a reference variable using dot syntax."
},
{
"code": null,
"e": 1074,
"s": 1007,
"text": "<reference variable name >.<instance variable_name / method_name>"
},
{
"code": null,
"e": 1083,
"s": 1074,
"text": "Example:"
},
{
"code": null,
"e": 1088,
"s": 1083,
"text": "Java"
},
{
"code": "// Java program to demonstrate reference// variable in java import java.io.*; class Demo { int x = 10; int display() { System.out.println(\"x = \" + x); return 0; }} class Main { public static void main(String[] args) { Demo D1 = new Demo(); // point 1 System.out.println(D1); // point 2 System.out.println(D1.display()); // point 3 }}",
"e": 1480,
"s": 1088,
"text": null
},
{
"code": null,
"e": 1506,
"s": 1483,
"text": "Demo@214c265e\nx = 10\n0"
},
{
"code": null,
"e": 1560,
"s": 1508,
"text": "Let us see what is actually happening step by step."
},
{
"code": null,
"e": 1830,
"s": 1562,
"text": "1. When we create an object of demo class new DEMO();, the default constructor is called and returns a reference of the object, and simply this reference will be stored to the reference variable D1 (As we know that associativity is Right-hand side to left-hand side)."
},
{
"code": null,
"e": 2159,
"s": 1832,
"text": "2. The value of a reference variable is a reference. When we attempt to print the value of a reference variable, the output contains the type of the variable and the hash code created for it by Java: the string Demo@214c265e tells us that the given variable is of type Name and its hexadecimal format of hash code is 214c265e."
},
{
"code": null,
"e": 2286,
"s": 2161,
"text": "3. At this point we will access the methods display() of the class demo using our custom reference variable that we created."
},
{
"code": null,
"e": 2657,
"s": 2288,
"text": "BINDING UP : The constructor call returns a value that is a reference to the newly-created object. The equality sign tells the program that the value of the right-hand side expression is to be copied as the value of the variable on the left-hand side. The reference to the newly-created object, returned by the constructor call, is copied as the value of the variable."
},
{
"code": null,
"e": 2664,
"s": 2659,
"text": "Java"
},
{
"code": "import java.io.*;class Demo { int x = 10; int display() { System.out.println(\"x = \" + x); return 0; }} class Main { public static void main(String[] args) { // create instance Demo D1 = new Demo(); // accessing instance(object) variable System.out.println(D1.x); // point 3 // accessing instance(object) method D1.display(); }}",
"e": 3081,
"s": 2664,
"text": null
},
{
"code": null,
"e": 3094,
"s": 3084,
"text": "10\nx = 10"
},
{
"code": null,
"e": 3103,
"s": 3098,
"text": "Java"
},
{
"code": "// Accessing instance methods import java.io.*;class Demo { int x = 10; int display() { System.out.println(\"x = \" + x); return 0; }}class Main { public static void main(String[] args) { // create instances Demo D1 = new Demo(); Demo M1 = new Demo(); Demo Q1 = new Demo(); }}",
"e": 3448,
"s": 3103,
"text": null
},
{
"code": null,
"e": 3453,
"s": 3448,
"text": "Java"
},
{
"code": "// Pointing to same instance memory import java.io.*;class Demo { int x = 10; int display() { System.out.println(\"x = \" + x); return 0; }}class Main { public static void main(String[] args) { // create instance Demo D1 = new Demo(); // point to same reference Demo G1 = D1; Demo M1 = new Demo(); Demo Q1 = M1; // updating the value of x using G! // reference variable G1.x = 25; System.out.println(G1.x); // Point 1 System.out.println(D1.x); // Point 2 }}",
"e": 4027,
"s": 3453,
"text": null
},
{
"code": null,
"e": 4036,
"s": 4030,
"text": "25\n25"
},
{
"code": null,
"e": 4044,
"s": 4038,
"text": "Note:"
},
{
"code": null,
"e": 4495,
"s": 4044,
"text": "Here we pass G1 and Q1 reference variable point out the same object respectively. Secondly At Point 1 we try to get the value of the object with G1 reference variable which shows it as 25 and At Point 2 we try to get the value of an object with D1 reference variable which shows it as 25 as well. This will prove that the modification in the object can be done by using any reference variable but the condition is it should hold the same reference. "
},
{
"code": null,
"e": 4539,
"s": 4495,
"text": "1. Reference Variable as Method Parameters:"
},
{
"code": null,
"e": 5085,
"s": 4541,
"text": "As the value of a primitive variable is directly stored in the variable, whereas the value of a reference variable holds a reference to an object. We also mentioned that assigning a value with the equality sign copies the value (possibly of some variable) on the right-hand side and stores it as the value of the left-hand-side variable. A similar kind of copying occurs during a method call. Regardless of whether the variable is primitive or reference type, a copy of the value is passed to the method’s argument and copied to that argument."
},
{
"code": null,
"e": 5127,
"s": 5087,
"text": "Note: Java only supports pass by value."
},
{
"code": null,
"e": 5275,
"s": 5127,
"text": "But we know that the reference variable holds the reference of an instance(OBJECT) so a copy of the reference is passed to the method’s argument. "
},
{
"code": null,
"e": 5286,
"s": 5277,
"text": "Example:"
},
{
"code": null,
"e": 5293,
"s": 5288,
"text": "Java"
},
{
"code": "// Pass by reference and value import java.io.*;class Demo { int x = 10; int y = 20; int display(Demo A, Demo B) { // Updating value using argument A.x = 95; System.out.println(\"x = \" + x); System.out.println(\"y = \" + y); return 0; }}class Main { public static void main(String[] args) { Demo C = new Demo(); Demo D = new Demo(); // updating value using primary reference // variable D.y = 55; C.display(C, D); // POINT 1 D.display(C, D); // POINT 2 }}",
"e": 5863,
"s": 5293,
"text": null
},
{
"code": null,
"e": 5894,
"s": 5866,
"text": "x = 95\ny = 20\nx = 10\ny = 55"
},
{
"code": null,
"e": 5906,
"s": 5896,
"text": "SCENE 1 :"
},
{
"code": null,
"e": 5917,
"s": 5908,
"text": "SCENE 2:"
},
{
"code": null,
"e": 6248,
"s": 5919,
"text": "Now, What is going on here, when we pass the reference to the method it will copy to the reference variable defined in the method signature and After that, they also have access to the object members. Here, We defined two instances named C and D. Afterwards we pass C and D to the method which further gives reference to A and B"
},
{
"code": null,
"e": 6462,
"s": 6250,
"text": "At Point 1: A will update the value of x from 10 to 95, hence C.display() will show 95 20 but in another object D we update the value of x through D only from y =20 to 55, hence D, display() will show 10 and 55."
},
{
"code": null,
"e": 6533,
"s": 6464,
"text": "Note: Any Object Updation will not affect the other object’s member."
},
{
"code": null,
"e": 6610,
"s": 6533,
"text": "2. What if we swap the reference variables with the help of the Swap Method?"
},
{
"code": null,
"e": 6843,
"s": 6612,
"text": "The fact is if we try to swap the reference variable, then they just swap their Pointing element there is no effect on the address of reference variable and object(Instance) Space. Let’s Understand It with the help of an example: "
},
{
"code": null,
"e": 6850,
"s": 6845,
"text": "Java"
},
{
"code": "// Swapping object references import java.io.*;class Demo { // Swapping Method int Swap(Demo A, Demo B) { Demo temp = A; A = B; B = temp; return 0; }}class Main { public static void main(String[] args) { Demo C = new Demo(); Demo D = new Demo(); // Passing C and reference variables // to Swap method C.Swap(C, D); }}",
"e": 7255,
"s": 6850,
"text": null
},
{
"code": null,
"e": 7594,
"s": 7255,
"text": "Here we created, two instances of demo class and passes it to swap method, further those C and D will copy their references to A and B respectively.Before swapping A point to C’s(Object) and B point to D’s(Object). After we perform swapping on A and B, A will now point D’s(Object) and B will Point C’s Object. As described in the figure."
},
{
"code": null,
"e": 7676,
"s": 7594,
"text": " Note: There is no swapping between Variables, They only change their References."
},
{
"code": null,
"e": 7838,
"s": 7676,
"text": "3. What if we pass arrays to the method will it be able to update the Actual Array’s values, even we know that a copy of the array is a pass to the formal Array?"
},
{
"code": null,
"e": 8224,
"s": 7838,
"text": "The answer is YES, the values will be updated by Formal parameter, The Fact is, When we create an Array, a memory is assigned to the array of the desired size, and it returns the reference of the first array’s element that is the base address that will store to the Formal Array(Method argument). As we learned earlier every pointing reference variable can change or update the object."
},
{
"code": null,
"e": 8233,
"s": 8224,
"text": "Example:"
},
{
"code": null,
"e": 8238,
"s": 8233,
"text": "Java"
},
{
"code": "import java.io.*;class Demo { int arrayUpdate(int[] formalArray) { formalArray[2] = 99; formalArray[4] = 77; return 0; }}class Main { public static void main(String[] args) { Demo d1 = new Demo(); int[] actualArray = { 1, 2, 3, 4, 5 }; for (int items : actualArray) System.out.print(items + \" , \"); // printing array System.out.println(); d1.arrayUpdate(actualArray); System.out.println(); for (int items : actualArray) System.out.print(items + \" , \"); // printing array }}",
"e": 8881,
"s": 8238,
"text": null
},
{
"code": null,
"e": 8929,
"s": 8884,
"text": "1 , 2 , 3 , 4 , 5 , \n\n1 , 2 , 99 , 4 , 77 , "
},
{
"code": null,
"e": 8986,
"s": 8931,
"text": "4. this and super keywords are also Pointing Elements."
},
{
"code": null,
"e": 9075,
"s": 8988,
"text": "this keyword. In java, this is a reference variable that refers to the current object."
},
{
"code": null,
"e": 9292,
"s": 9077,
"text": "super is used to refer immediate parent class instance variable. We can use the super keyword to access the data member or field of the parent class. It is used if parent class and child class have the same fields."
},
{
"code": null,
"e": 9334,
"s": 9294,
"text": " 5. null value of a reference variable."
},
{
"code": null,
"e": 9356,
"s": 9336,
"text": "Demo obj = null ; "
},
{
"code": null,
"e": 9434,
"s": 9356,
"text": "A. The null reference can be set as the value of any reference type variable."
},
{
"code": null,
"e": 9891,
"s": 9436,
"text": "B. The object whose name is obj is referred to by nobody. In other words, the object has become garbage. In the Java programming language, the programmer need not worry about the program’s memory use. From time to time, the automatic garbage collector of the Java language cleans up the objects that have become garbage. If the garbage collection did not happen, the garbage objects would reserve a memory location until the end of the program execution."
},
{
"code": null,
"e": 9898,
"s": 9893,
"text": "Java"
},
{
"code": "// null in java import java.io.*;class Demo { int x = 10; int display() { System.out.println(\"x = \" + x); return 0; }}class Main { public static void main(String[] args) { Demo obj = null; // accessing instance(object) method Kuchbhi.display(); }}",
"e": 10203,
"s": 9898,
"text": null
},
{
"code": null,
"e": 10213,
"s": 10206,
"text": "Output"
},
{
"code": null,
"e": 10315,
"s": 10215,
"text": "Exception in thread \"main\" java.lang.NullPointerException\nat Main.main(File.java:17)\nJava Result: 1"
},
{
"code": null,
"e": 10652,
"s": 10317,
"text": "Here, we try to access objects’ members by a reference variable that is pointing nothing(null), and hence it shows NullPointerException. Now if you get the error, the first step is to look for variables whose value could be null. Fortunately, the error message is useful: it tells which row caused the error. Just try it out yourself!"
},
{
"code": null,
"e": 10663,
"s": 10654,
"text": "sooda367"
},
{
"code": null,
"e": 10671,
"s": 10663,
"text": "akki_23"
},
{
"code": null,
"e": 10676,
"s": 10671,
"text": "Java"
},
{
"code": null,
"e": 10681,
"s": 10676,
"text": "Java"
},
{
"code": null,
"e": 10779,
"s": 10681,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10794,
"s": 10779,
"text": "Stream In Java"
},
{
"code": null,
"e": 10815,
"s": 10794,
"text": "Introduction to Java"
},
{
"code": null,
"e": 10836,
"s": 10815,
"text": "Constructors in Java"
},
{
"code": null,
"e": 10855,
"s": 10836,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 10872,
"s": 10855,
"text": "Generics in Java"
},
{
"code": null,
"e": 10902,
"s": 10872,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 10928,
"s": 10902,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 10944,
"s": 10928,
"text": "Strings in Java"
},
{
"code": null,
"e": 10981,
"s": 10944,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to set the Visibility of the Label in C#?
|
30 Jun, 2019
In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the visibility of the Label control using the Visible Property in the windows form. The label is visible when the value of this property is set to be true.If the value of this property is set to be false, then the Label does not visible in the form. The default value of this property is true. You can set this property using two different methods:
1. Design-Time: It is the easiest method to set the Visible property of the Label control using the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need.
Step 3: After drag and drop you will go to the properties of the Label control to set the Visible property of the Label.Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the visibility of the Label control in the windows forms programmatically with the help of given syntax:
public bool Visible { get; set; }
Here, the value of this property is of System.Boolean type. Following steps are used to set the Visible property of the Label:
Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class
Label mylab = new Label();
// Creating label using Label class
Label mylab = new Label();
Step 2: After creating Label, set the Visible property of the Label provided by the Label class.// Set Visible property of the label
mylab.Visible = true;
// Set Visible property of the label
mylab.Visible = true;
Step 3: And last add this Label control to form using Add() method.// Add this label to the form
this.Controls.Add(mylab);
Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.ForeColor = Color.Green; mylab.Visible = true; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = "Welcome To GeeksforGeeks"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.Font = new Font("Calibri", 18); mylab1.Visible = false; // Adding this control to the form this.Controls.Add(mylab1); }}}Output:When the value of Visible Property is set to be true:When the value of Visible Property is set to be false:
// Add this label to the form
this.Controls.Add(mylab);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = "GeeksforGeeks"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font("Calibri", 18); mylab.ForeColor = Color.Green; mylab.Visible = true; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = "Welcome To GeeksforGeeks"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.Font = new Font("Calibri", 18); mylab1.Visible = false; // Adding this control to the form this.Controls.Add(mylab1); }}}
Output:
When the value of Visible Property is set to be true:
When the value of Visible Property is set to be false:
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2019"
},
{
"code": null,
"e": 540,
"s": 28,
"text": "In Windows Forms, Label control is used to display text on the form and it does not take part in user input or in mouse or keyboard events. You are allowed to set the visibility of the Label control using the Visible Property in the windows form. The label is visible when the value of this property is set to be true.If the value of this property is set to be false, then the Label does not visible in the form. The default value of this property is true. You can set this property using two different methods:"
},
{
"code": null,
"e": 657,
"s": 540,
"text": "1. Design-Time: It is the easiest method to set the Visible property of the Label control using the following steps:"
},
{
"code": null,
"e": 773,
"s": 657,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 948,
"s": 773,
"text": "Step 2: Drag the Label control from the ToolBox and drop it on the windows form. You are allowed to place a Label control anywhere on the windows form according to your need."
},
{
"code": null,
"e": 1076,
"s": 948,
"text": "Step 3: After drag and drop you will go to the properties of the Label control to set the Visible property of the Label.Output:"
},
{
"code": null,
"e": 1084,
"s": 1076,
"text": "Output:"
},
{
"code": null,
"e": 1281,
"s": 1084,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the visibility of the Label control in the windows forms programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1315,
"s": 1281,
"text": "public bool Visible { get; set; }"
},
{
"code": null,
"e": 1442,
"s": 1315,
"text": "Here, the value of this property is of System.Boolean type. Following steps are used to set the Visible property of the Label:"
},
{
"code": null,
"e": 1590,
"s": 1442,
"text": "Step 1: Create a label using the Label() constructor is provided by the Label class.// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 1654,
"s": 1590,
"text": "// Creating label using Label class\nLabel mylab = new Label();\n"
},
{
"code": null,
"e": 1810,
"s": 1654,
"text": "Step 2: After creating Label, set the Visible property of the Label provided by the Label class.// Set Visible property of the label\nmylab.Visible = true;\n"
},
{
"code": null,
"e": 1870,
"s": 1810,
"text": "// Set Visible property of the label\nmylab.Visible = true;\n"
},
{
"code": null,
"e": 3252,
"s": 1870,
"text": "Step 3: And last add this Label control to form using Add() method.// Add this label to the form\nthis.Controls.Add(mylab);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.ForeColor = Color.Green; mylab.Visible = true; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = \"Welcome To GeeksforGeeks\"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.Font = new Font(\"Calibri\", 18); mylab1.Visible = false; // Adding this control to the form this.Controls.Add(mylab1); }}}Output:When the value of Visible Property is set to be true:When the value of Visible Property is set to be false:"
},
{
"code": null,
"e": 3309,
"s": 3252,
"text": "// Add this label to the form\nthis.Controls.Add(mylab);\n"
},
{
"code": null,
"e": 3318,
"s": 3309,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the label Label mylab = new Label(); mylab.Text = \"GeeksforGeeks\"; mylab.Location = new Point(222, 90); mylab.AutoSize = true; mylab.Font = new Font(\"Calibri\", 18); mylab.ForeColor = Color.Green; mylab.Visible = true; // Adding this control to the form this.Controls.Add(mylab); // Creating and setting the label Label mylab1 = new Label(); mylab1.Text = \"Welcome To GeeksforGeeks\"; mylab1.Location = new Point(155, 170); mylab1.AutoSize = true; mylab1.Font = new Font(\"Calibri\", 18); mylab1.Visible = false; // Adding this control to the form this.Controls.Add(mylab1); }}}",
"e": 4455,
"s": 3318,
"text": null
},
{
"code": null,
"e": 4463,
"s": 4455,
"text": "Output:"
},
{
"code": null,
"e": 4517,
"s": 4463,
"text": "When the value of Visible Property is set to be true:"
},
{
"code": null,
"e": 4572,
"s": 4517,
"text": "When the value of Visible Property is set to be false:"
},
{
"code": null,
"e": 4575,
"s": 4572,
"text": "C#"
}
] |
Properties keySet() method in Java with Examples
|
23 May, 2019
The keySet() method of Properties class is used to create a set out of the key elements contained in the Properties. It basically returns a set view of the keys or we can create a new set and store the key elements in them.
Syntax:
public Set keySet()
Parameters: This method accepts no parameters
Returns: This method returns a Set view of the keys contained in this Properties object.
Below programs show the implementation of int keySet() method.
Program 1:
// Java code to show the implementation of// keySet() method import java.util.*;public class GfG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put("Pen", 10); properties.put("Book", 500); properties.put("Clothes", 400); properties.put("Mobile", 5000); // Print Properties details System.out.println("Properties: " + properties.toString()); System.out.println("keySet: " + properties.keySet()); }}
Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
keySet: [Book, Mobile, Pen, Clothes]
Program 2:
// Java program to demonstrate// keySet() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); // Inserting elements into the properties properties.put("Geeks", 10); properties.put("4", 15); properties.put("Geeks", 20); properties.put("Welcomes", 25); properties.put("You", 30); // Print Properties details System.out.println("Current Properties: " + properties.toString()); System.out.println("keySet: " + properties.keySet()); }}
Current Properties: {You=30, Welcomes=25, 4=15, Geeks=20}
keySet: [You, Welcomes, 4, Geeks]
References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#keySet–
nidhi_biet
Java - util package
Java-Functions
Java-Properties
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 252,
"s": 28,
"text": "The keySet() method of Properties class is used to create a set out of the key elements contained in the Properties. It basically returns a set view of the keys or we can create a new set and store the key elements in them."
},
{
"code": null,
"e": 260,
"s": 252,
"text": "Syntax:"
},
{
"code": null,
"e": 280,
"s": 260,
"text": "public Set keySet()"
},
{
"code": null,
"e": 326,
"s": 280,
"text": "Parameters: This method accepts no parameters"
},
{
"code": null,
"e": 415,
"s": 326,
"text": "Returns: This method returns a Set view of the keys contained in this Properties object."
},
{
"code": null,
"e": 478,
"s": 415,
"text": "Below programs show the implementation of int keySet() method."
},
{
"code": null,
"e": 489,
"s": 478,
"text": "Program 1:"
},
{
"code": "// Java code to show the implementation of// keySet() method import java.util.*;public class GfG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); properties.put(\"Pen\", 10); properties.put(\"Book\", 500); properties.put(\"Clothes\", 400); properties.put(\"Mobile\", 5000); // Print Properties details System.out.println(\"Properties: \" + properties.toString()); System.out.println(\"keySet: \" + properties.keySet()); }}",
"e": 1130,
"s": 489,
"text": null
},
{
"code": null,
"e": 1225,
"s": 1130,
"text": "Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}\nkeySet: [Book, Mobile, Pen, Clothes]\n"
},
{
"code": null,
"e": 1236,
"s": 1225,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// keySet() method. import java.util.*; public class GFG { // Main method public static void main(String[] args) { // Create a properties and add some values Properties properties = new Properties(); // Inserting elements into the properties properties.put(\"Geeks\", 10); properties.put(\"4\", 15); properties.put(\"Geeks\", 20); properties.put(\"Welcomes\", 25); properties.put(\"You\", 30); // Print Properties details System.out.println(\"Current Properties: \" + properties.toString()); System.out.println(\"keySet: \" + properties.keySet()); }}",
"e": 1956,
"s": 1236,
"text": null
},
{
"code": null,
"e": 2049,
"s": 1956,
"text": "Current Properties: {You=30, Welcomes=25, 4=15, Geeks=20}\nkeySet: [You, Welcomes, 4, Geeks]\n"
},
{
"code": null,
"e": 2137,
"s": 2049,
"text": "References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#keySet–"
},
{
"code": null,
"e": 2148,
"s": 2137,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2168,
"s": 2148,
"text": "Java - util package"
},
{
"code": null,
"e": 2183,
"s": 2168,
"text": "Java-Functions"
},
{
"code": null,
"e": 2199,
"s": 2183,
"text": "Java-Properties"
},
{
"code": null,
"e": 2204,
"s": 2199,
"text": "Java"
},
{
"code": null,
"e": 2209,
"s": 2204,
"text": "Java"
},
{
"code": null,
"e": 2307,
"s": 2209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2322,
"s": 2307,
"text": "Stream In Java"
},
{
"code": null,
"e": 2343,
"s": 2322,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2364,
"s": 2343,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2383,
"s": 2364,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2400,
"s": 2383,
"text": "Generics in Java"
},
{
"code": null,
"e": 2430,
"s": 2400,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2456,
"s": 2430,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2472,
"s": 2456,
"text": "Strings in Java"
},
{
"code": null,
"e": 2509,
"s": 2472,
"text": "Differences between JDK, JRE and JVM"
}
] |
Numbers that are not divisible by any number in the range [2, 10]
|
22 Jun, 2022
Given an integer N, The task is to find the count of all the numbers from 1 to N which are not divisible by any number in the range [2, 10].
Examples:
Input: N = 12 Output: 2 1, 11 are the only numbers in range [1, 12] which are not divisible by any number from 2 to 10
Input: N = 20 Output: 5
Approach: Total numbers from 1 to n which are not divisible by any number from 2 to 10 are equal to n minus the numbers which are divisible by some numbers from 2 to 10.
The set of numbers that are divisible by some numbers from 2 to 10 can be found as union of the set of numbers from 1 to n divisible by 2, the set of numbers divisible by 3, and so on till 10.
Note that sets of numbers divisible by 4 or 6 or 8 are subsets of the set of numbers divisible by 2, and sets of numbers divisible by 6 or 9 are subsets of the set of numbers divisible by 3. So there is no need to unite 9 sets, it is enough to unite sets for 2, 3, 5, and 7 only.
The size of the set of numbers from 1 to n divisible by 2, 3, 5, and 7 can be calculated using an inclusion-exclusion principle that says that the size of every single set should be added, the size of pairwise intersections should be subtracted, the size of all intersections of three sets should be added and so on.
The size of the set of numbers from 1 to n divisible by 2 is equal to ⌊n / 2⌋, the size of the set of numbers from 1 to n divisible by 2 and 3 is equal to ⌊n / (2 * 3)⌋ and so on.
So, the formula is n – ⌊n / 2⌋ – ⌊n / 3⌋ – ⌊n / 5⌋ – ⌊n / 7⌋ + ⌊n / (2 * 3)] + ⌊n / (2 * 5)] + ⌊n / (2 * 7)] + ⌊n / (3 * 5)] + ⌊n / (3 * 7)] + ⌊n / (5 * 7)] – ⌊n / (2 * 3 * 5)] – ⌊n / (2 * 3 * 7)] – ⌊n / (2 * 5 * 7)] – ⌊n / (3 * 5 * 7)]+ ⌊n / (2 * 3 * 5 * 7)]
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]int countNumbers(int n){ return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210;} // Driver codeint main(){ int n = 20; cout << countNumbers(n); return 0;}
// Java implementation of the approachclass GFG{ // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]static int countNumbers(int n){ return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210;} // Driver codepublic static void main (String[] args){ int n = 20; System.out.println(countNumbers(n));}} // This code is contributed by mits
# Python3 implementation of the approach # Function to return the count of numbers# from 1 to N which are not divisible by# any number in the range [2, 10]def countNumbers(n): return (n - n // 2 - n // 3 - n // 5 - n // 7 + n // 6 + n // 10 + n // 14 + n // 15 + n // 21 + n // 35 - n // 30 - n // 42 - n // 70 - n // 105 + n // 210) # Driver codeif __name__ == '__main__': n = 20 print(countNumbers(n)) # This code contributed by Rajput-Ji
// C# implementation of the approachusing System; class GFG{ // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]static int countNumbers(int n){ return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210;} // Driver codestatic void Main(){ int n = 20; Console.WriteLine(countNumbers(n));}} // This code is contributed by mits
<?php// PHP implementation of the approach // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]function countNumbers($n){ return (int)($n - $n / 2) - (int)($n / 3 ) - (int)($n / 5 ) - (int)($n / 7) + (int)($n / 6 ) + (int)($n / 10) + (int)($n / 14) + (int)($n / 15) + (int)($n / 21) + (int)($n / 35) - (int)($n / 30) - (int)($n / 42) - (int)($n / 70) - (int)($n / 105) + (int)($n / 210);} // Driver code$n = 20;echo(countNumbers($n)); // This code is contributed by Code_Mech.?>
<script> // Javascript implementation of the approach // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]function countNumbers(n){ return n - parseInt(n / 2, 10) - parseInt(n / 3, 10) - parseInt(n / 5, 10) - parseInt(n / 7, 10) + parseInt(n / 6, 10) + parseInt(n / 10, 10) + parseInt(n / 14, 10) + parseInt(n / 15, 10) + parseInt(n / 21, 10) + parseInt(n / 35, 10) - parseInt(n / 30, 10) - parseInt(n / 42, 10) - parseInt(n / 70, 10) - parseInt(n / 105, 10) + parseInt(n / 210, 10);} // Driver codelet n = 20; document.write(countNumbers(n)); // This code is contributed by mukesh07 </script>
5
Time Complexity: O(1)Auxiliary Space: O(1)
Mithun Kumar
rrlinus
Rajput-Ji
Code_Mech
mukesh07
subham348
divisibility
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 193,
"s": 52,
"text": "Given an integer N, The task is to find the count of all the numbers from 1 to N which are not divisible by any number in the range [2, 10]."
},
{
"code": null,
"e": 204,
"s": 193,
"text": "Examples: "
},
{
"code": null,
"e": 323,
"s": 204,
"text": "Input: N = 12 Output: 2 1, 11 are the only numbers in range [1, 12] which are not divisible by any number from 2 to 10"
},
{
"code": null,
"e": 348,
"s": 323,
"text": "Input: N = 20 Output: 5 "
},
{
"code": null,
"e": 518,
"s": 348,
"text": "Approach: Total numbers from 1 to n which are not divisible by any number from 2 to 10 are equal to n minus the numbers which are divisible by some numbers from 2 to 10."
},
{
"code": null,
"e": 711,
"s": 518,
"text": "The set of numbers that are divisible by some numbers from 2 to 10 can be found as union of the set of numbers from 1 to n divisible by 2, the set of numbers divisible by 3, and so on till 10."
},
{
"code": null,
"e": 991,
"s": 711,
"text": "Note that sets of numbers divisible by 4 or 6 or 8 are subsets of the set of numbers divisible by 2, and sets of numbers divisible by 6 or 9 are subsets of the set of numbers divisible by 3. So there is no need to unite 9 sets, it is enough to unite sets for 2, 3, 5, and 7 only."
},
{
"code": null,
"e": 1308,
"s": 991,
"text": "The size of the set of numbers from 1 to n divisible by 2, 3, 5, and 7 can be calculated using an inclusion-exclusion principle that says that the size of every single set should be added, the size of pairwise intersections should be subtracted, the size of all intersections of three sets should be added and so on."
},
{
"code": null,
"e": 1488,
"s": 1308,
"text": "The size of the set of numbers from 1 to n divisible by 2 is equal to ⌊n / 2⌋, the size of the set of numbers from 1 to n divisible by 2 and 3 is equal to ⌊n / (2 * 3)⌋ and so on."
},
{
"code": null,
"e": 1748,
"s": 1488,
"text": "So, the formula is n – ⌊n / 2⌋ – ⌊n / 3⌋ – ⌊n / 5⌋ – ⌊n / 7⌋ + ⌊n / (2 * 3)] + ⌊n / (2 * 5)] + ⌊n / (2 * 7)] + ⌊n / (3 * 5)] + ⌊n / (3 * 7)] + ⌊n / (5 * 7)] – ⌊n / (2 * 3 * 5)] – ⌊n / (2 * 3 * 7)] – ⌊n / (2 * 5 * 7)] – ⌊n / (3 * 5 * 7)]+ ⌊n / (2 * 3 * 5 * 7)]"
},
{
"code": null,
"e": 1801,
"s": 1748,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1805,
"s": 1801,
"text": "C++"
},
{
"code": null,
"e": 1810,
"s": 1805,
"text": "Java"
},
{
"code": null,
"e": 1818,
"s": 1810,
"text": "Python3"
},
{
"code": null,
"e": 1821,
"s": 1818,
"text": "C#"
},
{
"code": null,
"e": 1825,
"s": 1821,
"text": "PHP"
},
{
"code": null,
"e": 1836,
"s": 1825,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]int countNumbers(int n){ return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210;} // Driver codeint main(){ int n = 20; cout << countNumbers(n); return 0;}",
"e": 2310,
"s": 1836,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]static int countNumbers(int n){ return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210;} // Driver codepublic static void main (String[] args){ int n = 20; System.out.println(countNumbers(n));}} // This code is contributed by mits",
"e": 2820,
"s": 2310,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of numbers# from 1 to N which are not divisible by# any number in the range [2, 10]def countNumbers(n): return (n - n // 2 - n // 3 - n // 5 - n // 7 + n // 6 + n // 10 + n // 14 + n // 15 + n // 21 + n // 35 - n // 30 - n // 42 - n // 70 - n // 105 + n // 210) # Driver codeif __name__ == '__main__': n = 20 print(countNumbers(n)) # This code contributed by Rajput-Ji",
"e": 3306,
"s": 2820,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]static int countNumbers(int n){ return n - n / 2 - n / 3 - n / 5 - n / 7 + n / 6 + n / 10 + n / 14 + n / 15 + n / 21 + n / 35 - n / 30 - n / 42 - n / 70 - n / 105 + n / 210;} // Driver codestatic void Main(){ int n = 20; Console.WriteLine(countNumbers(n));}} // This code is contributed by mits",
"e": 3806,
"s": 3306,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]function countNumbers($n){ return (int)($n - $n / 2) - (int)($n / 3 ) - (int)($n / 5 ) - (int)($n / 7) + (int)($n / 6 ) + (int)($n / 10) + (int)($n / 14) + (int)($n / 15) + (int)($n / 21) + (int)($n / 35) - (int)($n / 30) - (int)($n / 42) - (int)($n / 70) - (int)($n / 105) + (int)($n / 210);} // Driver code$n = 20;echo(countNumbers($n)); // This code is contributed by Code_Mech.?>",
"e": 4423,
"s": 3806,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of numbers// from 1 to N which are not divisible by// any number in the range [2, 10]function countNumbers(n){ return n - parseInt(n / 2, 10) - parseInt(n / 3, 10) - parseInt(n / 5, 10) - parseInt(n / 7, 10) + parseInt(n / 6, 10) + parseInt(n / 10, 10) + parseInt(n / 14, 10) + parseInt(n / 15, 10) + parseInt(n / 21, 10) + parseInt(n / 35, 10) - parseInt(n / 30, 10) - parseInt(n / 42, 10) - parseInt(n / 70, 10) - parseInt(n / 105, 10) + parseInt(n / 210, 10);} // Driver codelet n = 20; document.write(countNumbers(n)); // This code is contributed by mukesh07 </script>",
"e": 5183,
"s": 4423,
"text": null
},
{
"code": null,
"e": 5185,
"s": 5183,
"text": "5"
},
{
"code": null,
"e": 5230,
"s": 5187,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 5243,
"s": 5230,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5251,
"s": 5243,
"text": "rrlinus"
},
{
"code": null,
"e": 5261,
"s": 5251,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 5271,
"s": 5261,
"text": "Code_Mech"
},
{
"code": null,
"e": 5280,
"s": 5271,
"text": "mukesh07"
},
{
"code": null,
"e": 5290,
"s": 5280,
"text": "subham348"
},
{
"code": null,
"e": 5303,
"s": 5290,
"text": "divisibility"
},
{
"code": null,
"e": 5327,
"s": 5303,
"text": "Competitive Programming"
},
{
"code": null,
"e": 5340,
"s": 5327,
"text": "Mathematical"
},
{
"code": null,
"e": 5353,
"s": 5340,
"text": "Mathematical"
}
] |
How to get a substring between two strings in PHP?
|
21 Feb, 2022
To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples:
Input:$string="hey, How are you?"
If we need to extract the substring between
"How" and "you" then the output should be are
Output:"Are"
Input:Hey, Welcome to GeeksforGeeks
If we need to get the substring between Welcome and
for then it should be to geeks as for lies within GeeksforGeeks.
Output:" to geeks"
Method 1: Firstly you have to find the ending position of the start word. Then find the starting position of the ending word after that return the substring between those indexes. Below program illustrate the approach:Program:
PHP
<?php function string_between_two_string($str, $starting_word, $ending_word){ $subtring_start = strpos($str, $starting_word); //Adding the starting index of the starting word to //its length would give its ending index $subtring_start += strlen($starting_word); //Length of our required sub string $size = strpos($str, $ending_word, $subtring_start) - $subtring_start; // Return the substring from the index substring_start of length size return substr($str, $subtring_start, $size); } $str = 'Hey, Welcome to geeksforgeeks';$substring = string_between_two_string($str, 'Welcome', 'for'); echo $substring; ?>
Output:
to geeks
Method 2: Using the explode() function. The explode function splits the given string on the basis of the parameter provided i.e. the separator. Syntax:
$arr=explode(separator, string).
This will return an array which will contain the string split on the basis of the separator.
Split the list on the basis of the starting word.
In the returned array the 2nd index will contain the words after the start word.
In the string provided by step 2 if we again split it on the basis of the ending word then the value at first index will be the string between the starting and the ending word.
Below program illustrate the approach Program:
PHP
<?php function string_between_two_string($str, $starting_word, $ending_word){ $arr = explode($starting_word, $str); if (isset($arr[1])){ $arr = explode($ending_word, $arr[1]); return $arr[0]; } return ''; } $str = "Hey, how are you?"; $start = "Hey"; $end = "you"; $substring = string_between_two_string($str, $start, $end); echo $substring;?>
Output:
, how are
nidhi_biet
varshagumber28
PHP-string
Picked
PHP
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Remove elements from a JavaScript Array
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "To get a substring between two strings there are few popular ways to do so. Below the procedures are explained with the example.Examples: "
},
{
"code": null,
"e": 483,
"s": 168,
"text": "Input:$string=\"hey, How are you?\"\nIf we need to extract the substring between \n\"How\" and \"you\" then the output should be are\n \nOutput:\"Are\"\n\nInput:Hey, Welcome to GeeksforGeeks\nIf we need to get the substring between Welcome and \nfor then it should be to geeks as for lies within GeeksforGeeks.\n\nOutput:\" to geeks\""
},
{
"code": null,
"e": 712,
"s": 483,
"text": "Method 1: Firstly you have to find the ending position of the start word. Then find the starting position of the ending word after that return the substring between those indexes. Below program illustrate the approach:Program: "
},
{
"code": null,
"e": 716,
"s": 712,
"text": "PHP"
},
{
"code": "<?php function string_between_two_string($str, $starting_word, $ending_word){ $subtring_start = strpos($str, $starting_word); //Adding the starting index of the starting word to //its length would give its ending index $subtring_start += strlen($starting_word); //Length of our required sub string $size = strpos($str, $ending_word, $subtring_start) - $subtring_start; // Return the substring from the index substring_start of length size return substr($str, $subtring_start, $size); } $str = 'Hey, Welcome to geeksforgeeks';$substring = string_between_two_string($str, 'Welcome', 'for'); echo $substring; ?>",
"e": 1358,
"s": 716,
"text": null
},
{
"code": null,
"e": 1368,
"s": 1358,
"text": "Output: "
},
{
"code": null,
"e": 1378,
"s": 1368,
"text": " to geeks"
},
{
"code": null,
"e": 1532,
"s": 1378,
"text": "Method 2: Using the explode() function. The explode function splits the given string on the basis of the parameter provided i.e. the separator. Syntax: "
},
{
"code": null,
"e": 1566,
"s": 1532,
"text": " $arr=explode(separator, string)."
},
{
"code": null,
"e": 1661,
"s": 1566,
"text": "This will return an array which will contain the string split on the basis of the separator. "
},
{
"code": null,
"e": 1711,
"s": 1661,
"text": "Split the list on the basis of the starting word."
},
{
"code": null,
"e": 1792,
"s": 1711,
"text": "In the returned array the 2nd index will contain the words after the start word."
},
{
"code": null,
"e": 1969,
"s": 1792,
"text": "In the string provided by step 2 if we again split it on the basis of the ending word then the value at first index will be the string between the starting and the ending word."
},
{
"code": null,
"e": 2018,
"s": 1969,
"text": "Below program illustrate the approach Program: "
},
{
"code": null,
"e": 2022,
"s": 2018,
"text": "PHP"
},
{
"code": "<?php function string_between_two_string($str, $starting_word, $ending_word){ $arr = explode($starting_word, $str); if (isset($arr[1])){ $arr = explode($ending_word, $arr[1]); return $arr[0]; } return ''; } $str = \"Hey, how are you?\"; $start = \"Hey\"; $end = \"you\"; $substring = string_between_two_string($str, $start, $end); echo $substring;?>",
"e": 2400,
"s": 2022,
"text": null
},
{
"code": null,
"e": 2410,
"s": 2400,
"text": "Output: "
},
{
"code": null,
"e": 2421,
"s": 2410,
"text": ", how are "
},
{
"code": null,
"e": 2434,
"s": 2423,
"text": "nidhi_biet"
},
{
"code": null,
"e": 2449,
"s": 2434,
"text": "varshagumber28"
},
{
"code": null,
"e": 2460,
"s": 2449,
"text": "PHP-string"
},
{
"code": null,
"e": 2467,
"s": 2460,
"text": "Picked"
},
{
"code": null,
"e": 2471,
"s": 2467,
"text": "PHP"
},
{
"code": null,
"e": 2498,
"s": 2471,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2502,
"s": 2498,
"text": "PHP"
},
{
"code": null,
"e": 2600,
"s": 2502,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2650,
"s": 2600,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2690,
"s": 2650,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2751,
"s": 2690,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2801,
"s": 2751,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 2846,
"s": 2801,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 2879,
"s": 2846,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2929,
"s": 2879,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2969,
"s": 2929,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3029,
"s": 2969,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
How to Remove a Column using Dplyr package in R
|
21 Jul, 2021
In this article, we are going to remove a column(s) in the R programming language using dplyr library.
Dataset in use:
Here we will use select() method to select and remove column by its name.
Syntax:
select(dataframe,-column_name)
Here, dataframe is the input dataframe and column_name is the column in the dataframe to be removed
To remove multiple columns:
Syntax:
select(dataframe,-c(column1,column2,.,column n))
Here, dataframe is the input dataframe and columns are the columns in the dataframe to be removed.
Example: R program to remove column by its name
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove id and nameprint(select(data1,-c(name,id)))
Output:
Here we will remove column(s) using column index or position. We will use the select() method to select a column by removing its position
Note: Index starts with 1
Syntax:
select(dataframe,-index)
Here, dataframe is the input dataframe and index is the column position in the dataframe to be removed.
To remove multiple columns:
Syntax:
select(dataframe,-c(index1,index2,.,index n))
Here, dataframe is the input dataframe and indexes are the column positions in the dataframe to be removed.
Example: R program to remove column by index
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove id print(select(data1,-id)) # remove multiple columns- name,idprint(select(data1,-c(name,id)))
Output:
Let’s discuss how to remove the column that contains the character or string.
contains() removes the column that contains the given substring.
Syntax:
select(dataframe,-contains(‘sub_string’))
Here, dataframe is the input dataframe and sub_string is the string present in the column name will be removed.
matches() removes the column that contains the given substring.
Syntax:
select(dataframe,-matches(‘sub_string’))
Here, dataframe is the input dataframe and sub_string is the string present in the column name will be removed.
Example: R program that removes column using contains() method
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove column that contains naprint(select(data1,-contains('na'))) # remove column that contains reprint(select(data1,-contains('re')))
Output:
Here we can also select columns based on starting and ending characters.
starts_with() is used to return the column that starts with the given character.
Syntax:
select(dataframe,-starts_with(‘substring’))
Where, dataframe is the input dataframe and substring is the character/string that starts with it.
ends_with() is used to return the column that ends with the given character.
Syntax:
select(dataframe,-ends_with(‘substring’))
Where, dataframe is the input dataframe and substring is the character/string that ends with it.
Example: R program to remove a column that starts with a character/substring
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove column that starts with naprint(select(data1,-starts_with('na'))) # remove column that starts with adprint(select(data1,-starts_with('ad')))
Output:
Example: R program to remove a column that ends with character/substring
R
# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove column that ends with dprint(select(data1,-ends_with('d'))) # remove column that starts with ssprint(select(data1,-ends_with('ss')))
Output:
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "In this article, we are going to remove a column(s) in the R programming language using dplyr library."
},
{
"code": null,
"e": 147,
"s": 131,
"text": "Dataset in use:"
},
{
"code": null,
"e": 221,
"s": 147,
"text": "Here we will use select() method to select and remove column by its name."
},
{
"code": null,
"e": 229,
"s": 221,
"text": "Syntax:"
},
{
"code": null,
"e": 260,
"s": 229,
"text": "select(dataframe,-column_name)"
},
{
"code": null,
"e": 360,
"s": 260,
"text": "Here, dataframe is the input dataframe and column_name is the column in the dataframe to be removed"
},
{
"code": null,
"e": 388,
"s": 360,
"text": "To remove multiple columns:"
},
{
"code": null,
"e": 396,
"s": 388,
"text": "Syntax:"
},
{
"code": null,
"e": 445,
"s": 396,
"text": "select(dataframe,-c(column1,column2,.,column n))"
},
{
"code": null,
"e": 544,
"s": 445,
"text": "Here, dataframe is the input dataframe and columns are the columns in the dataframe to be removed."
},
{
"code": null,
"e": 592,
"s": 544,
"text": "Example: R program to remove column by its name"
},
{
"code": null,
"e": 594,
"s": 592,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove id and nameprint(select(data1,-c(name,id)))",
"e": 1175,
"s": 594,
"text": null
},
{
"code": null,
"e": 1183,
"s": 1175,
"text": "Output:"
},
{
"code": null,
"e": 1321,
"s": 1183,
"text": "Here we will remove column(s) using column index or position. We will use the select() method to select a column by removing its position"
},
{
"code": null,
"e": 1347,
"s": 1321,
"text": "Note: Index starts with 1"
},
{
"code": null,
"e": 1355,
"s": 1347,
"text": "Syntax:"
},
{
"code": null,
"e": 1380,
"s": 1355,
"text": "select(dataframe,-index)"
},
{
"code": null,
"e": 1484,
"s": 1380,
"text": "Here, dataframe is the input dataframe and index is the column position in the dataframe to be removed."
},
{
"code": null,
"e": 1512,
"s": 1484,
"text": "To remove multiple columns:"
},
{
"code": null,
"e": 1520,
"s": 1512,
"text": "Syntax:"
},
{
"code": null,
"e": 1566,
"s": 1520,
"text": "select(dataframe,-c(index1,index2,.,index n))"
},
{
"code": null,
"e": 1674,
"s": 1566,
"text": "Here, dataframe is the input dataframe and indexes are the column positions in the dataframe to be removed."
},
{
"code": null,
"e": 1719,
"s": 1674,
"text": "Example: R program to remove column by index"
},
{
"code": null,
"e": 1721,
"s": 1719,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove id print(select(data1,-id)) # remove multiple columns- name,idprint(select(data1,-c(name,id)))",
"e": 2354,
"s": 1721,
"text": null
},
{
"code": null,
"e": 2362,
"s": 2354,
"text": "Output:"
},
{
"code": null,
"e": 2440,
"s": 2362,
"text": "Let’s discuss how to remove the column that contains the character or string."
},
{
"code": null,
"e": 2505,
"s": 2440,
"text": "contains() removes the column that contains the given substring."
},
{
"code": null,
"e": 2513,
"s": 2505,
"text": "Syntax:"
},
{
"code": null,
"e": 2555,
"s": 2513,
"text": "select(dataframe,-contains(‘sub_string’))"
},
{
"code": null,
"e": 2667,
"s": 2555,
"text": "Here, dataframe is the input dataframe and sub_string is the string present in the column name will be removed."
},
{
"code": null,
"e": 2731,
"s": 2667,
"text": "matches() removes the column that contains the given substring."
},
{
"code": null,
"e": 2739,
"s": 2731,
"text": "Syntax:"
},
{
"code": null,
"e": 2780,
"s": 2739,
"text": "select(dataframe,-matches(‘sub_string’))"
},
{
"code": null,
"e": 2892,
"s": 2780,
"text": "Here, dataframe is the input dataframe and sub_string is the string present in the column name will be removed."
},
{
"code": null,
"e": 2955,
"s": 2892,
"text": "Example: R program that removes column using contains() method"
},
{
"code": null,
"e": 2957,
"s": 2955,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove column that contains naprint(select(data1,-contains('na'))) # remove column that contains reprint(select(data1,-contains('re')))",
"e": 3628,
"s": 2957,
"text": null
},
{
"code": null,
"e": 3636,
"s": 3628,
"text": "Output:"
},
{
"code": null,
"e": 3709,
"s": 3636,
"text": "Here we can also select columns based on starting and ending characters."
},
{
"code": null,
"e": 3790,
"s": 3709,
"text": "starts_with() is used to return the column that starts with the given character."
},
{
"code": null,
"e": 3798,
"s": 3790,
"text": "Syntax:"
},
{
"code": null,
"e": 3842,
"s": 3798,
"text": "select(dataframe,-starts_with(‘substring’))"
},
{
"code": null,
"e": 3941,
"s": 3842,
"text": "Where, dataframe is the input dataframe and substring is the character/string that starts with it."
},
{
"code": null,
"e": 4019,
"s": 3941,
"text": " ends_with() is used to return the column that ends with the given character."
},
{
"code": null,
"e": 4027,
"s": 4019,
"text": "Syntax:"
},
{
"code": null,
"e": 4069,
"s": 4027,
"text": "select(dataframe,-ends_with(‘substring’))"
},
{
"code": null,
"e": 4166,
"s": 4069,
"text": "Where, dataframe is the input dataframe and substring is the character/string that ends with it."
},
{
"code": null,
"e": 4243,
"s": 4166,
"text": "Example: R program to remove a column that starts with a character/substring"
},
{
"code": null,
"e": 4245,
"s": 4243,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns# id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove column that starts with naprint(select(data1,-starts_with('na'))) # remove column that starts with adprint(select(data1,-starts_with('ad')))",
"e": 4928,
"s": 4245,
"text": null
},
{
"code": null,
"e": 4936,
"s": 4928,
"text": "Output:"
},
{
"code": null,
"e": 5009,
"s": 4936,
"text": "Example: R program to remove a column that ends with character/substring"
},
{
"code": null,
"e": 5011,
"s": 5009,
"text": "R"
},
{
"code": "# load the librarylibrary(dplyr) # create dataframe with 3 columns # id,name and addressdata1=data.frame(id=c(1,2,3,4,5,6,7,1,4,2), name=c('sravan','ojaswi','bobby', 'gnanesh','rohith','pinkey', 'dhanush','sravan','gnanesh', 'ojaswi'), address=c('hyd','hyd','ponnur','tenali', 'vijayawada','vijayawada','guntur', 'hyd','tenali','hyd')) # remove column that ends with dprint(select(data1,-ends_with('d'))) # remove column that starts with ssprint(select(data1,-ends_with('ss')))",
"e": 5687,
"s": 5011,
"text": null
},
{
"code": null,
"e": 5695,
"s": 5687,
"text": "Output:"
},
{
"code": null,
"e": 5702,
"s": 5695,
"text": "Picked"
},
{
"code": null,
"e": 5710,
"s": 5702,
"text": "R Dplyr"
},
{
"code": null,
"e": 5721,
"s": 5710,
"text": "R Language"
}
] |
How to make a carousel using CSS ?
|
01 Apr, 2022
In this article, we will be going to learn how to make a carousel using plain CSS without using any other library or framework. A carousel is a slideshow that contains a collection of rotating banners/images. Usually, you can see carousels on the home page of a website. It makes your website more attractive.
We are going to make a 4 image carousel that can be controlled by buttons places at bottom of the carousel. There is a text at the center of the carousel which is fixed and can’t move with movement in the image. The images are moving after a fixed interval of time in the background.
We are using HTML as a basic structure for our carousel and CSS to decorate it. Below is the step-by-step procedure that we will be going to follow.
Step 1: Firstly, we add HTML code. It contains the main container and inside a container, there are two things:
the main heading of the web page
is a div with class content containing the whole carousel structure.
Step 2: Now, we will add the following two parts in the content div:
The first part is a div with class carousel-content. The content (heading and subheading) is placed in the center of the carousel. This will remain static in the carousel.
The second part is a div with a class slideshow. All the moving parts of the carousel will be inside this div.
Step 3: The slideshow div contains the following elements:
Four carousel control buttons
a slideshow wrapper that wraps all 4 carousel images.
Then, we add CSS for styling our carousel and to make the carousel responsive for all screen sizes.
NOTE: We will use "rem" and "%" units
as much as possible to achieve responsiveness
easily.
Below is the implementation of the above approach.
Example:
index.html
<!DOCTYPE html><html lang="en"><head> <style> /* default stylings */ * { box-sizing: border-box; margin: 0; padding: 0; } /* provides background color to body */ body { background-color: rgb(255, 235, 235); } /* ----- container stylings: -> centers the whole content of the page -> defines width and height for container ----- */ .container { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: auto; width: 800px; height: 600px; } /* ----- end of container stylings ----- */ /* provides padding to main heading */ .main-heading { padding: 2rem 0 2rem 0; } .content { position: relative; } /* ----- carousel content stylings ----- */ /* places the carousel content on center of the carousel */ .carousel-content { position: absolute; /*to center the content horizontally and vertically*/ top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 50; } .carousel-heading { font-size: 3rem; color: #308d46; margin-bottom: 1rem; } /*----- end of carousel content stylings ----- */ /* ----- slideshow stylings ----- */ .slideshow { height: 100%; overflow: hidden; /* to hide slides in x-direction */ position: relative; } /* wrapper which wraps all the slideshow images stylings */ .slideshow-wrapper { display: flex; /* We give it width as 400% because we are making a 4 image carousel. If you want to make for example, 5 images carousel, then give width as 500%. */ width: 400%; height: 100%; position: relative; /* you can change the animation settings from below */ animation: slideshow 20s infinite; } /* define width and height for images*/ .slide { width: 100%; height: 100%; } .slide-img { width: 100%; height: 100%; object-fit: cover; } /* @keyframes are used to provide animations We make these settings for 4 image carousel. Make modification according to your needs. */ @keyframes slideshow { 0% { left: 0; } 10% { left: 0; } 15% { left: -100%; } 25% { left: -100%; } 30% { left: -200%; } 40% { left: -200%; } 45% { left: -300%; } 55% { left: -300%; } 60% { left: -200%; } 70% { left: -200%; } 75% { left: -100%; } 85% { left: -100%; } 90% { left: 0%; } } /* ----- end of slideshow stylings ----- */ /* ----- carousel control buttons stylings ----- */ .slide-btn { background-color: #bbb; border-radius: 50%; border: .2rem solid #d38800; width: 1.2rem; height: 1.2rem; outline: none; cursor: pointer; /* stylings for positioning the buttons at the bottom of the carousel */ position: absolute; bottom: 3%; left: 50%; transform: translateX(-50%); z-index: 70; } /* As we provide position as absolute, the buttons places one over the other. So, we have to place them individually at their correct positions. */ .slide-btn-1 { left: 45%; } .slide-btn-2 { left: 50%; } .slide-btn-3 { left: 55%; } .slide-btn-4 { left: 60%; } /* When we focus on the particular button, the animation stops to that particular image to which the button is associated. */ .slide-btn-1:focus~.slideshow-wrapper { animation: none; left: 0; } .slide-btn-2:focus~.slideshow-wrapper { animation: none; left: -100%; } .slide-btn-3:focus~.slideshow-wrapper { animation: none; left: -200%; } .slide-btn-4:focus~.slideshow-wrapper { animation: none; left: -300%; } /* when we focus on the button, the background color changes */ .slide-btn:focus { background-color: #308d46; } /* ----- end of carousel control buttons stylings ----- */ </style> <title>Geeks For Geeks</title></head><body> <div class="container"> <h1 class="main-heading">Responsive Carousel using CSS</h1> <div class="content"> <!-- The content which is placed at the center of the carousel --> <div class="carousel-content"> <h1 class="carousel-heading"> GeeksforGeeks </h1> <h3>A computer science portal for geeks</h3> </div> <div class="slideshow"> <!-- carousel control buttons --> <button class="slide-btn slide-btn-1"></button> <button class="slide-btn slide-btn-2"></button> <button class="slide-btn slide-btn-3"></button> <button class="slide-btn slide-btn-4"></button> <!-- carousel wrapper which contains all images --> <div class="slideshow-wrapper"> <div class="slide"> <img class="slide-img" src="https://media.geeksforgeeks.org/wp-content/uploads/20210818140124/image1-300x169.png"> </div> <div class="slide"> <img class="slide-img" src="https://media.geeksforgeeks.org/wp-content/uploads/20210818140126/image2-300x169.png"> </div> <div class="slide"> <img class="slide-img" src="https://media.geeksforgeeks.org/wp-content/uploads/20210818190339/image5-300x185.png"> </div> <div class="slide"> <img class="slide-img" src="https://media.geeksforgeeks.org/wp-content/uploads/20210818141837/image4-300x168.png"> </div> </div> </div> </div> </div></body></html>
Output: From this, we can see that the carousel is looking beautiful for all screen sizes i.e. mobile, tablet, and laptop screens. Do modifications to the above code according to your choice, include it in your project, and have fun building awesome projects.
surinderdawra388
simmytarika5
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
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 ?
HTTP headers | Content-Type
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Apr, 2022"
},
{
"code": null,
"e": 362,
"s": 52,
"text": "In this article, we will be going to learn how to make a carousel using plain CSS without using any other library or framework. A carousel is a slideshow that contains a collection of rotating banners/images. Usually, you can see carousels on the home page of a website. It makes your website more attractive."
},
{
"code": null,
"e": 647,
"s": 362,
"text": "We are going to make a 4 image carousel that can be controlled by buttons places at bottom of the carousel. There is a text at the center of the carousel which is fixed and can’t move with movement in the image. The images are moving after a fixed interval of time in the background. "
},
{
"code": null,
"e": 796,
"s": 647,
"text": "We are using HTML as a basic structure for our carousel and CSS to decorate it. Below is the step-by-step procedure that we will be going to follow."
},
{
"code": null,
"e": 908,
"s": 796,
"text": "Step 1: Firstly, we add HTML code. It contains the main container and inside a container, there are two things:"
},
{
"code": null,
"e": 941,
"s": 908,
"text": "the main heading of the web page"
},
{
"code": null,
"e": 1010,
"s": 941,
"text": "is a div with class content containing the whole carousel structure."
},
{
"code": null,
"e": 1079,
"s": 1010,
"text": "Step 2: Now, we will add the following two parts in the content div:"
},
{
"code": null,
"e": 1251,
"s": 1079,
"text": "The first part is a div with class carousel-content. The content (heading and subheading) is placed in the center of the carousel. This will remain static in the carousel."
},
{
"code": null,
"e": 1362,
"s": 1251,
"text": "The second part is a div with a class slideshow. All the moving parts of the carousel will be inside this div."
},
{
"code": null,
"e": 1421,
"s": 1362,
"text": "Step 3: The slideshow div contains the following elements:"
},
{
"code": null,
"e": 1451,
"s": 1421,
"text": "Four carousel control buttons"
},
{
"code": null,
"e": 1505,
"s": 1451,
"text": "a slideshow wrapper that wraps all 4 carousel images."
},
{
"code": null,
"e": 1605,
"s": 1505,
"text": "Then, we add CSS for styling our carousel and to make the carousel responsive for all screen sizes."
},
{
"code": null,
"e": 1699,
"s": 1605,
"text": "NOTE: We will use \"rem\" and \"%\" units \nas much as possible to achieve responsiveness \neasily."
},
{
"code": null,
"e": 1750,
"s": 1699,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1759,
"s": 1750,
"text": "Example:"
},
{
"code": null,
"e": 1770,
"s": 1759,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <style> /* default stylings */ * { box-sizing: border-box; margin: 0; padding: 0; } /* provides background color to body */ body { background-color: rgb(255, 235, 235); } /* ----- container stylings: -> centers the whole content of the page -> defines width and height for container ----- */ .container { display: flex; flex-direction: column; justify-content: center; align-items: center; margin: auto; width: 800px; height: 600px; } /* ----- end of container stylings ----- */ /* provides padding to main heading */ .main-heading { padding: 2rem 0 2rem 0; } .content { position: relative; } /* ----- carousel content stylings ----- */ /* places the carousel content on center of the carousel */ .carousel-content { position: absolute; /*to center the content horizontally and vertically*/ top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 50; } .carousel-heading { font-size: 3rem; color: #308d46; margin-bottom: 1rem; } /*----- end of carousel content stylings ----- */ /* ----- slideshow stylings ----- */ .slideshow { height: 100%; overflow: hidden; /* to hide slides in x-direction */ position: relative; } /* wrapper which wraps all the slideshow images stylings */ .slideshow-wrapper { display: flex; /* We give it width as 400% because we are making a 4 image carousel. If you want to make for example, 5 images carousel, then give width as 500%. */ width: 400%; height: 100%; position: relative; /* you can change the animation settings from below */ animation: slideshow 20s infinite; } /* define width and height for images*/ .slide { width: 100%; height: 100%; } .slide-img { width: 100%; height: 100%; object-fit: cover; } /* @keyframes are used to provide animations We make these settings for 4 image carousel. Make modification according to your needs. */ @keyframes slideshow { 0% { left: 0; } 10% { left: 0; } 15% { left: -100%; } 25% { left: -100%; } 30% { left: -200%; } 40% { left: -200%; } 45% { left: -300%; } 55% { left: -300%; } 60% { left: -200%; } 70% { left: -200%; } 75% { left: -100%; } 85% { left: -100%; } 90% { left: 0%; } } /* ----- end of slideshow stylings ----- */ /* ----- carousel control buttons stylings ----- */ .slide-btn { background-color: #bbb; border-radius: 50%; border: .2rem solid #d38800; width: 1.2rem; height: 1.2rem; outline: none; cursor: pointer; /* stylings for positioning the buttons at the bottom of the carousel */ position: absolute; bottom: 3%; left: 50%; transform: translateX(-50%); z-index: 70; } /* As we provide position as absolute, the buttons places one over the other. So, we have to place them individually at their correct positions. */ .slide-btn-1 { left: 45%; } .slide-btn-2 { left: 50%; } .slide-btn-3 { left: 55%; } .slide-btn-4 { left: 60%; } /* When we focus on the particular button, the animation stops to that particular image to which the button is associated. */ .slide-btn-1:focus~.slideshow-wrapper { animation: none; left: 0; } .slide-btn-2:focus~.slideshow-wrapper { animation: none; left: -100%; } .slide-btn-3:focus~.slideshow-wrapper { animation: none; left: -200%; } .slide-btn-4:focus~.slideshow-wrapper { animation: none; left: -300%; } /* when we focus on the button, the background color changes */ .slide-btn:focus { background-color: #308d46; } /* ----- end of carousel control buttons stylings ----- */ </style> <title>Geeks For Geeks</title></head><body> <div class=\"container\"> <h1 class=\"main-heading\">Responsive Carousel using CSS</h1> <div class=\"content\"> <!-- The content which is placed at the center of the carousel --> <div class=\"carousel-content\"> <h1 class=\"carousel-heading\"> GeeksforGeeks </h1> <h3>A computer science portal for geeks</h3> </div> <div class=\"slideshow\"> <!-- carousel control buttons --> <button class=\"slide-btn slide-btn-1\"></button> <button class=\"slide-btn slide-btn-2\"></button> <button class=\"slide-btn slide-btn-3\"></button> <button class=\"slide-btn slide-btn-4\"></button> <!-- carousel wrapper which contains all images --> <div class=\"slideshow-wrapper\"> <div class=\"slide\"> <img class=\"slide-img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210818140124/image1-300x169.png\"> </div> <div class=\"slide\"> <img class=\"slide-img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210818140126/image2-300x169.png\"> </div> <div class=\"slide\"> <img class=\"slide-img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210818190339/image5-300x185.png\"> </div> <div class=\"slide\"> <img class=\"slide-img\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20210818141837/image4-300x168.png\"> </div> </div> </div> </div> </div></body></html>",
"e": 8440,
"s": 1770,
"text": null
},
{
"code": null,
"e": 8700,
"s": 8440,
"text": "Output: From this, we can see that the carousel is looking beautiful for all screen sizes i.e. mobile, tablet, and laptop screens. Do modifications to the above code according to your choice, include it in your project, and have fun building awesome projects."
},
{
"code": null,
"e": 8717,
"s": 8700,
"text": "surinderdawra388"
},
{
"code": null,
"e": 8730,
"s": 8717,
"text": "simmytarika5"
},
{
"code": null,
"e": 8745,
"s": 8730,
"text": "CSS-Properties"
},
{
"code": null,
"e": 8759,
"s": 8745,
"text": "CSS-Questions"
},
{
"code": null,
"e": 8774,
"s": 8759,
"text": "HTML-Questions"
},
{
"code": null,
"e": 8781,
"s": 8774,
"text": "Picked"
},
{
"code": null,
"e": 8785,
"s": 8781,
"text": "CSS"
},
{
"code": null,
"e": 8790,
"s": 8785,
"text": "HTML"
},
{
"code": null,
"e": 8807,
"s": 8790,
"text": "Web Technologies"
},
{
"code": null,
"e": 8812,
"s": 8807,
"text": "HTML"
},
{
"code": null,
"e": 8910,
"s": 8812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8949,
"s": 8910,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 8988,
"s": 8949,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 9027,
"s": 8988,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 9056,
"s": 9027,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 9093,
"s": 9056,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 9117,
"s": 9093,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 9170,
"s": 9117,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 9230,
"s": 9170,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 9291,
"s": 9230,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
How to create a register form with CSS?
|
Following is the code to create a register form with CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
h1{
text-align: center;
}
* {
box-sizing: border-box;
}
form {
padding: 16px;
max-width: 800px;
margin-left: 20%;
background-color: rgb(255, 254, 195);
}
input[type=text], input[type=password] {
width: 100%;
padding: 15px;
margin: 5px 0 22px 0;
display: inline-block;
border: none;
background: #f1f1f1;
}
input[type=text]:focus, input[type=password]:focus {
background-color: #ddd;
outline: none;
}
hr {
border: 1px solid #f1f1f1;
margin-bottom: 25px;
}
.registerbtn {
background-color: #4CAF50;
color: white;
padding: 16px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
opacity: 0.9;
}
.registerbtn:hover {
opacity: 1;
}
a {
color: dodgerblue;
text-decoration: none;
}
.signin {
background-color: #f1f1f1;
text-align: center;
}
@media (max-width: 800px) {
form {
width: 100%;
margin-left: 0px;
}
}
</style>
</head>
<body>
<h1>Registeration Form Example</h1>
<form>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<hr>
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="signin">
<p>Already have an account? <a href="#">Sign in</a>.</p>
</div>
</form>
</body>
</html>
This will produce the following output −
|
[
{
"code": null,
"e": 1121,
"s": 1062,
"text": "Following is the code to create a register form with CSS −"
},
{
"code": null,
"e": 1132,
"s": 1121,
"text": " Live Demo"
},
{
"code": null,
"e": 2902,
"s": 1132,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<style>\nbody {\n font-family: Arial, Helvetica, sans-serif;\n}\nh1{\n text-align: center;\n}\n* {\n box-sizing: border-box;\n}\nform {\n padding: 16px;\n max-width: 800px;\n margin-left: 20%;\n background-color: rgb(255, 254, 195);\n}\ninput[type=text], input[type=password] {\n width: 100%;\n padding: 15px;\n margin: 5px 0 22px 0;\n display: inline-block;\n border: none;\n background: #f1f1f1;\n}\ninput[type=text]:focus, input[type=password]:focus {\n background-color: #ddd;\n outline: none;\n}\nhr {\n border: 1px solid #f1f1f1;\n margin-bottom: 25px;\n}\n.registerbtn {\n background-color: #4CAF50;\n color: white;\n padding: 16px 20px;\n margin: 8px 0;\n border: none;\n cursor: pointer;\n width: 100%;\n opacity: 0.9;\n}\n.registerbtn:hover {\n opacity: 1;\n}\na {\n color: dodgerblue;\n text-decoration: none;\n}\n.signin {\n background-color: #f1f1f1;\n text-align: center;\n}\n@media (max-width: 800px) {\n form {\n width: 100%;\n margin-left: 0px;\n }\n}\n</style>\n</head>\n<body>\n<h1>Registeration Form Example</h1>\n<form>\n<label for=\"email\"><b>Email</b></label>\n<input type=\"text\" placeholder=\"Enter Email\" name=\"email\" required>\n<label for=\"psw\"><b>Password</b></label>\n<input type=\"password\" placeholder=\"Enter Password\" name=\"psw\" required>\n<label for=\"psw-repeat\"><b>Repeat Password</b></label>\n<input type=\"password\" placeholder=\"Repeat Password\" name=\"psw-repeat\" required>\n<hr>\n<p>By creating an account you agree to our <a href=\"#\">Terms & Privacy</a>.</p>\n<button type=\"submit\" class=\"registerbtn\">Register</button>\n</div>\n<div class=\"signin\">\n<p>Already have an account? <a href=\"#\">Sign in</a>.</p>\n</div>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 2943,
"s": 2902,
"text": "This will produce the following output −"
}
] |
AtomicInteger accumulateAndGet() method in Java with Examples - GeeksforGeeks
|
04 Feb, 2021
The Java.AtomicInteger.accumulateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value and value passed as a parameter. It takes an integer as its parameter and an object of IntBinaryOperator interface and applies the operation specified in the object to the values. It returns the updated value.
Syntax:
public final int accumulateAndGet(int y,
IntBinaryOperator function)
Parameters: This method accepts as parameter an integer value y and an IntBinaryOperator function. It applies the given function to the current value of the object and the value y.
Return Value: The function returns the updated value of the current object.
Example to demonstrate the function.
Java
// Java program to demonstrate// AtomicInteger accumulateAndGet() method import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntBinaryOperator; public class Demo { public static void main(String[] args) { new UserThread("Thread A"); new UserThread("Thread B"); }} class Shared { static AtomicInteger ai = new AtomicInteger(0);} class UserThread implements Runnable { String name; UserThread(String name) { this.name = name; new Thread(this).start(); } IntBinaryOperator ibo = (x, y) -> (x + y); int value = 5; @Override public void run() { for (int i = 0; i < 3; i++) { int ans = Shared.ai .accumulateAndGet(value, ibo); System.out.println(name + " " + ans); } }}
Thread A 5
Thread A 10
Thread A 15
Thread B 20
Thread B 25
Thread B 30
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
arorakashish0911
Java-AtomicInteger
Java-Functions
Java-util-concurrent-atomic package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
|
[
{
"code": null,
"e": 24129,
"s": 24101,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 24513,
"s": 24129,
"text": "The Java.AtomicInteger.accumulateAndGet() method is an inbuilt method, which updates the current value of the object by applying the specified operation on the current value and value passed as a parameter. It takes an integer as its parameter and an object of IntBinaryOperator interface and applies the operation specified in the object to the values. It returns the updated value."
},
{
"code": null,
"e": 24522,
"s": 24513,
"text": "Syntax: "
},
{
"code": null,
"e": 24605,
"s": 24522,
"text": "public final int accumulateAndGet(int y, \n IntBinaryOperator function)"
},
{
"code": null,
"e": 24786,
"s": 24605,
"text": "Parameters: This method accepts as parameter an integer value y and an IntBinaryOperator function. It applies the given function to the current value of the object and the value y."
},
{
"code": null,
"e": 24862,
"s": 24786,
"text": "Return Value: The function returns the updated value of the current object."
},
{
"code": null,
"e": 24900,
"s": 24862,
"text": "Example to demonstrate the function. "
},
{
"code": null,
"e": 24905,
"s": 24900,
"text": "Java"
},
{
"code": "// Java program to demonstrate// AtomicInteger accumulateAndGet() method import java.util.concurrent.atomic.AtomicInteger;import java.util.function.IntBinaryOperator; public class Demo { public static void main(String[] args) { new UserThread(\"Thread A\"); new UserThread(\"Thread B\"); }} class Shared { static AtomicInteger ai = new AtomicInteger(0);} class UserThread implements Runnable { String name; UserThread(String name) { this.name = name; new Thread(this).start(); } IntBinaryOperator ibo = (x, y) -> (x + y); int value = 5; @Override public void run() { for (int i = 0; i < 3; i++) { int ans = Shared.ai .accumulateAndGet(value, ibo); System.out.println(name + \" \" + ans); } }}",
"e": 25723,
"s": 24905,
"text": null
},
{
"code": null,
"e": 25794,
"s": 25723,
"text": "Thread A 5\nThread A 10\nThread A 15\nThread B 20\nThread B 25\nThread B 30"
},
{
"code": null,
"e": 25897,
"s": 25796,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html "
},
{
"code": null,
"e": 25914,
"s": 25897,
"text": "arorakashish0911"
},
{
"code": null,
"e": 25933,
"s": 25914,
"text": "Java-AtomicInteger"
},
{
"code": null,
"e": 25948,
"s": 25933,
"text": "Java-Functions"
},
{
"code": null,
"e": 25984,
"s": 25948,
"text": "Java-util-concurrent-atomic package"
},
{
"code": null,
"e": 25989,
"s": 25984,
"text": "Java"
},
{
"code": null,
"e": 25994,
"s": 25989,
"text": "Java"
},
{
"code": null,
"e": 26092,
"s": 25994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26101,
"s": 26092,
"text": "Comments"
},
{
"code": null,
"e": 26114,
"s": 26101,
"text": "Old Comments"
},
{
"code": null,
"e": 26165,
"s": 26114,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26195,
"s": 26165,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26226,
"s": 26195,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26258,
"s": 26226,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26277,
"s": 26258,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26295,
"s": 26277,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26327,
"s": 26295,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26347,
"s": 26327,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 26371,
"s": 26347,
"text": "Singleton Class in Java"
}
] |
C# | Clone() Method - GeeksforGeeks
|
31 Jan, 2019
In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data.In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance. This method will not take any parameters.
Syntax:
public object Clone()
Return Value Type: System.Object or we can say this instance of String.
Below program illustrate the use of Clone() Method:
// C# program to illustrate // Clone() methodusing System;class Geeks { // Main Method public static void Main(string[] args) { string s1 = "GeeksForgeeks"; // Cannot implicitly convert // type object to the string. // So explicit conversion // using Clone() method string s2 = (String)s1.Clone(); // Displaying both the string Console.WriteLine("String : {0}", s1); Console.WriteLine("Clone String : {0}", s2); }}
String : GeeksForgeeks
Clone String : GeeksForgeeks
Reference: https://msdn.microsoft.com/en-us/library/system.string.clone
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
Destructors in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
C# | List Class
C# | Inheritance
Partial Classes in C#
Lambda Expressions in C#
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 24328,
"s": 24300,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 24669,
"s": 24328,
"text": "In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data.In other words, it returns a reference to this instance of String. The return value will be only another view of the same data. Clone method called directly on current String instance. This method will not take any parameters."
},
{
"code": null,
"e": 24677,
"s": 24669,
"text": "Syntax:"
},
{
"code": null,
"e": 24700,
"s": 24677,
"text": "public object Clone()\n"
},
{
"code": null,
"e": 24772,
"s": 24700,
"text": "Return Value Type: System.Object or we can say this instance of String."
},
{
"code": null,
"e": 24824,
"s": 24772,
"text": "Below program illustrate the use of Clone() Method:"
},
{
"code": "// C# program to illustrate // Clone() methodusing System;class Geeks { // Main Method public static void Main(string[] args) { string s1 = \"GeeksForgeeks\"; // Cannot implicitly convert // type object to the string. // So explicit conversion // using Clone() method string s2 = (String)s1.Clone(); // Displaying both the string Console.WriteLine(\"String : {0}\", s1); Console.WriteLine(\"Clone String : {0}\", s2); }}",
"e": 25329,
"s": 24824,
"text": null
},
{
"code": null,
"e": 25382,
"s": 25329,
"text": "String : GeeksForgeeks\nClone String : GeeksForgeeks\n"
},
{
"code": null,
"e": 25454,
"s": 25382,
"text": "Reference: https://msdn.microsoft.com/en-us/library/system.string.clone"
},
{
"code": null,
"e": 25468,
"s": 25454,
"text": "CSharp-method"
},
{
"code": null,
"e": 25482,
"s": 25468,
"text": "CSharp-string"
},
{
"code": null,
"e": 25485,
"s": 25482,
"text": "C#"
},
{
"code": null,
"e": 25583,
"s": 25485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25606,
"s": 25583,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 25624,
"s": 25606,
"text": "Destructors in C#"
},
{
"code": null,
"e": 25652,
"s": 25624,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 25692,
"s": 25652,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 25735,
"s": 25692,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 25751,
"s": 25735,
"text": "C# | List Class"
},
{
"code": null,
"e": 25768,
"s": 25751,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 25790,
"s": 25768,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 25815,
"s": 25790,
"text": "Lambda Expressions in C#"
}
] |
Remove Consecutive Characters | Practice | GeeksforGeeks
|
Given a string S delete the characters which are appearing more than once consecutively.
Example 1:
Input:
S = aabb
Output: ab
Explanation: 'a' at 2nd position is
appearing 2nd time consecutively.
Similiar explanation for b at
4th position.
Example 2:
Input:
S = aabaa
Output: aba
Explanation: 'a' at 2nd position is
appearing 2nd time consecutively.
'a' at fifth position is appearing
2nd time consecutively.
Your Task:
You dont need to read input or print anything. Complete the function removeConsecutiveCharacter() which accepts a string as input parameter and returns modified string.
Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(|S|).
Constraints:
1<=|S|<=105
All characters are lowercase alphabets.
0
manavkanjiyanijobupdate2 weeks ago
JAVA SOLUTION ALL TEST CASE PASS
class Solution{ public String removeConsecutiveCharacter(String S){ char ch = S.charAt(0); String s = String.valueOf(S.charAt(0)); for(int i = 1 ; i < S.length(); i++) { if(S.charAt(i) == ch) { ch = S.charAt(i); } else { ch = S.charAt(i); s = s + S.charAt(i); } } return s; }}
+3
sarthakgupta102 weeks ago
class Solution{
public:
string removeConsecutiveCharacter(string S)
{
// code here.
string ans;
for(int i=0;i<S.length();i++)
{
if(S[i]!=S[i+1])
{
ans+=S[i];
}
}
return ans;
}
};
simplest solution
+1
mishra07adi3 weeks ago
JAVA Simple Approach:
Total Time Taken: 0.79/3.21
class Solution
{
public String removeConsecutiveCharacter(String S)
{
String ans="";
int n = S.length();
char c = S.charAt(0);
ans+=c;
for(int i=1;i<n;i++)
{
if(c!=S.charAt(i))
ans = ans + S.charAt(i);
c = S.charAt(i);
}
return ans;
}
}
+2
mishra07adi3 weeks ago
Fastest and Simplest method
class Solution
{
public:
string removeConsecutiveCharacter(string S)
{
// code here.
string ans;
int n = S.length();
char c = S[0];
ans+=c;
for(int i=1;i<n;i++)
{
if(c!=S[i])
ans=ans+S[i];
c=S[i];
}
return ans;
}
};
0
dhanushkorrapati55434 weeks ago
JAVA SOLUTION:
class Solution{ public String removeConsecutiveCharacter(String S){ ArrayList<Character>set=new ArrayList<>(); String ans=""; for(int i=0;i<S.length()-1;i++){ if(S.charAt(i)!=S.charAt(i+1)){ ans=ans+S.charAt(i); } } ans=ans+S.charAt(S.length()-1); return ans; }}
+4
amarrajsmart1971 month ago
string removeConsecutiveCharacter(string S) { // code here. string ans=""; ans+=S[0]; for(int i=1;i<S.length();i++) { if(S[i]!=S[i-1]) ans+=S[i]; } return ans; }
+1
ashutos17sharma89891 month ago
Recursion in java
class Solution{
public String removeConsecutiveCharacter(String S){
String ans="";
if(S.length()==0||S.length()==1){
return S;
}
int i=0;
if(S.charAt(i)!=S.charAt(i+1) && i<S.length()-1){
ans+=S.charAt(0);
}
ans+=removeConsecutiveCharacter(S.substring(1));
return ans;
}
}
0
blackwolf1431 month ago
string t; stack<char>st; st.push(s[0]); for(int i=1;i<s.size();++i){ if(st.top()!=s[i]) st.push(s[i]); } while(!st.empty()){ t.push_back(st.top()); st.pop(); } reverse(t.begin(),t.end()); return t;
0
vc1825711 month ago
Java Easy Solution
int len=S.length(); String str=""; int i=0; for(i=0;i<len-1;i++){ if(S.charAt(i)!=S.charAt(i+1)){ str+=S.charAt(i); } } str+=S.charAt(i); return str;
+1
prashr11 month ago
Solution with O(1) auxillary space and O(|S|) Time complexity:
class Solution{
public:
string removeConsecutiveCharacter(string S)
{
// code here.
if(!S.length())
return S;
char x=S[0];
for(int i=1;i<S.length();i++)
{
if(S[i]==x)
{
S.erase(S.begin()+i);
i--;
continue;
}
x=S[i];
}
return S;
}
};
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": 327,
"s": 238,
"text": "Given a string S delete the characters which are appearing more than once consecutively."
},
{
"code": null,
"e": 338,
"s": 327,
"text": "Example 1:"
},
{
"code": null,
"e": 483,
"s": 338,
"text": "Input:\nS = aabb\nOutput: ab \nExplanation: 'a' at 2nd position is\nappearing 2nd time consecutively.\nSimiliar explanation for b at\n4th position.\n\n"
},
{
"code": null,
"e": 494,
"s": 483,
"text": "Example 2:"
},
{
"code": null,
"e": 653,
"s": 494,
"text": "Input:\nS = aabaa\nOutput: aba\nExplanation: 'a' at 2nd position is\nappearing 2nd time consecutively.\n'a' at fifth position is appearing\n2nd time consecutively."
},
{
"code": null,
"e": 838,
"s": 655,
"text": "Your Task:\nYou dont need to read input or print anything. Complete the function removeConsecutiveCharacter() which accepts a string as input parameter and returns modified string. \n "
},
{
"code": null,
"e": 908,
"s": 838,
"text": "Expected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(|S|).\n "
},
{
"code": null,
"e": 975,
"s": 908,
"text": "Constraints:\n1<=|S|<=105\nAll characters are lowercase alphabets.\n "
},
{
"code": null,
"e": 977,
"s": 975,
"text": "0"
},
{
"code": null,
"e": 1012,
"s": 977,
"text": "manavkanjiyanijobupdate2 weeks ago"
},
{
"code": null,
"e": 1045,
"s": 1012,
"text": "JAVA SOLUTION ALL TEST CASE PASS"
},
{
"code": null,
"e": 1479,
"s": 1045,
"text": "class Solution{ public String removeConsecutiveCharacter(String S){ char ch = S.charAt(0); String s = String.valueOf(S.charAt(0)); for(int i = 1 ; i < S.length(); i++) { if(S.charAt(i) == ch) { ch = S.charAt(i); } else { ch = S.charAt(i); s = s + S.charAt(i); } } return s; }}"
},
{
"code": null,
"e": 1482,
"s": 1479,
"text": "+3"
},
{
"code": null,
"e": 1508,
"s": 1482,
"text": "sarthakgupta102 weeks ago"
},
{
"code": null,
"e": 1821,
"s": 1508,
"text": "class Solution{\n public:\n string removeConsecutiveCharacter(string S)\n {\n // code here.\n string ans;\n for(int i=0;i<S.length();i++)\n {\n if(S[i]!=S[i+1])\n {\n ans+=S[i];\n }\n }\n return ans;\n }\n};\nsimplest solution"
},
{
"code": null,
"e": 1824,
"s": 1821,
"text": "+1"
},
{
"code": null,
"e": 1847,
"s": 1824,
"text": "mishra07adi3 weeks ago"
},
{
"code": null,
"e": 1869,
"s": 1847,
"text": "JAVA Simple Approach:"
},
{
"code": null,
"e": 1897,
"s": 1869,
"text": "Total Time Taken: 0.79/3.21"
},
{
"code": null,
"e": 2265,
"s": 1899,
"text": "class Solution\n{\n public String removeConsecutiveCharacter(String S)\n {\n String ans=\"\";\n int n = S.length();\n char c = S.charAt(0);\n ans+=c;\n for(int i=1;i<n;i++)\n {\n if(c!=S.charAt(i))\n ans = ans + S.charAt(i);\n \n c = S.charAt(i);\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 2268,
"s": 2265,
"text": "+2"
},
{
"code": null,
"e": 2291,
"s": 2268,
"text": "mishra07adi3 weeks ago"
},
{
"code": null,
"e": 2319,
"s": 2291,
"text": "Fastest and Simplest method"
},
{
"code": null,
"e": 2677,
"s": 2319,
"text": "class Solution\n{\n public:\n string removeConsecutiveCharacter(string S)\n {\n // code here.\n string ans;\n int n = S.length();\n char c = S[0];\n ans+=c;\n for(int i=1;i<n;i++)\n {\n if(c!=S[i])\n ans=ans+S[i];\n \n c=S[i];\n }\n return ans;\n }\n}; "
},
{
"code": null,
"e": 2679,
"s": 2677,
"text": "0"
},
{
"code": null,
"e": 2711,
"s": 2679,
"text": "dhanushkorrapati55434 weeks ago"
},
{
"code": null,
"e": 2726,
"s": 2711,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 3063,
"s": 2726,
"text": "class Solution{ public String removeConsecutiveCharacter(String S){ ArrayList<Character>set=new ArrayList<>(); String ans=\"\"; for(int i=0;i<S.length()-1;i++){ if(S.charAt(i)!=S.charAt(i+1)){ ans=ans+S.charAt(i); } } ans=ans+S.charAt(S.length()-1); return ans; }}"
},
{
"code": null,
"e": 3066,
"s": 3063,
"text": "+4"
},
{
"code": null,
"e": 3093,
"s": 3066,
"text": "amarrajsmart1971 month ago"
},
{
"code": null,
"e": 3330,
"s": 3093,
"text": " string removeConsecutiveCharacter(string S) { // code here. string ans=\"\"; ans+=S[0]; for(int i=1;i<S.length();i++) { if(S[i]!=S[i-1]) ans+=S[i]; } return ans; }"
},
{
"code": null,
"e": 3333,
"s": 3330,
"text": "+1"
},
{
"code": null,
"e": 3364,
"s": 3333,
"text": "ashutos17sharma89891 month ago"
},
{
"code": null,
"e": 3382,
"s": 3364,
"text": "Recursion in java"
},
{
"code": null,
"e": 3751,
"s": 3382,
"text": "class Solution{\n public String removeConsecutiveCharacter(String S){\n String ans=\"\";\n if(S.length()==0||S.length()==1){\n return S;\n }\n int i=0;\n if(S.charAt(i)!=S.charAt(i+1) && i<S.length()-1){\n ans+=S.charAt(0);\n }\n ans+=removeConsecutiveCharacter(S.substring(1));\n return ans;\n }\n}"
},
{
"code": null,
"e": 3753,
"s": 3751,
"text": "0"
},
{
"code": null,
"e": 3777,
"s": 3753,
"text": "blackwolf1431 month ago"
},
{
"code": null,
"e": 4053,
"s": 3777,
"text": " string t; stack<char>st; st.push(s[0]); for(int i=1;i<s.size();++i){ if(st.top()!=s[i]) st.push(s[i]); } while(!st.empty()){ t.push_back(st.top()); st.pop(); } reverse(t.begin(),t.end()); return t;"
},
{
"code": null,
"e": 4055,
"s": 4053,
"text": "0"
},
{
"code": null,
"e": 4075,
"s": 4055,
"text": "vc1825711 month ago"
},
{
"code": null,
"e": 4095,
"s": 4075,
"text": "Java Easy Solution "
},
{
"code": null,
"e": 4318,
"s": 4095,
"text": " int len=S.length(); String str=\"\"; int i=0; for(i=0;i<len-1;i++){ if(S.charAt(i)!=S.charAt(i+1)){ str+=S.charAt(i); } } str+=S.charAt(i); return str;"
},
{
"code": null,
"e": 4321,
"s": 4318,
"text": "+1"
},
{
"code": null,
"e": 4340,
"s": 4321,
"text": "prashr11 month ago"
},
{
"code": null,
"e": 4403,
"s": 4340,
"text": "Solution with O(1) auxillary space and O(|S|) Time complexity:"
},
{
"code": null,
"e": 4816,
"s": 4403,
"text": "class Solution{\n public:\n string removeConsecutiveCharacter(string S)\n {\n // code here.\n if(!S.length())\n return S;\n char x=S[0];\n for(int i=1;i<S.length();i++)\n {\n if(S[i]==x)\n {\n S.erase(S.begin()+i);\n i--;\n continue;\n }\n x=S[i];\n }\n return S;\n }\n};"
},
{
"code": null,
"e": 4962,
"s": 4816,
"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": 4998,
"s": 4962,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5008,
"s": 4998,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5018,
"s": 5008,
"text": "\nContest\n"
},
{
"code": null,
"e": 5081,
"s": 5018,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5229,
"s": 5081,
"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": 5437,
"s": 5229,
"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": 5543,
"s": 5437,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Python 3 - CGI Programming
|
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA.
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
The current version is CGI/1.1 and CGI/1.2 is under progress.
To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e., filename.
Your browser contacts the HTTP web server and demands for the URL, i.e., filename.
Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.
Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.
Web browser takes response from web server and displays either the received file or error message.
Web browser takes response from web server and displays either the received file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc.
Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well.
By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file −
<Directory "/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
<Directory "/var/www/cgi-bin">
Options All
</Directory>
Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc.
Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.
#!/usr/bin/python
print ("Content-type:text/html\r\n\r\n")
print ('<html>')
print ('<head>')
print ('<title>Hello Word - First CGI Program</title>')
print ('</head>')
print ('<body>')
print ('<h2>Hello Word! This is my first CGI program</h2>')
print ('</body>')
print ('</html>')
Note − First line in the script must be path to Python executable. In Linux it should be #!/usr/bin/python3
Enter following URL in yor browser
http://localhost:8080/cgi-bin/hello.py
Hello Word! This is my first CGI program
This hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen.
By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS.
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form −
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in your CGI Programming.
Content-type:
A MIME string defining the format of the file being returned. Example is Content-type:text/html
Expires: Date
The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.
Location: URL
The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.
Last-modified: Date
The date of last modification of the resource.
Content-length: N
The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.
Set-Cookie: String
Set the cookie passed through the string
All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program.
CONTENT_TYPE
The data type of the content. Used when the client is sending attached content to the server. For example, file upload.
CONTENT_LENGTH
The length of the query information. It is available only for POST requests.
HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser.
PATH_INFO
The path for the CGI script.
QUERY_STRING
The URL-encoded information that is sent with GET method request.
REMOTE_ADDR
The IP address of the remote host making the request. This is useful logging or for authentication.
REMOTE_HOST
The fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address.
REQUEST_METHOD
The method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAME
The full path to the CGI script.
SCRIPT_NAME
The name of the CGI script.
SERVER_NAME
The server's hostname or IP Address
SERVER_SOFTWARE
The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment
#!/usr/bin/python
import os
print ("Content-type: text/html\r\n\r\n");
print ("<font size=+1>Environment</font><\br>");
for param in os.environ.keys():
print ("<b>%20s</b>: %s<\br>" % (param, os.environ[param]))
You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
The GET method is the default method to pass information from the browser to the web server and it produces a long string that appears in your browser's Location:box.
The GET method is the default method to pass information from the browser to the web server and it produces a long string that appears in your browser's Location:box.
Never use GET method if you have password or other sensitive information to pass to the server.
Never use GET method if you have password or other sensitive information to pass to the server.
The GET method has size limtation: only 1024 characters can be sent in a request string.
The GET method has size limtation: only 1024 characters can be sent in a request string.
The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.
The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method.
Here is a simple URL, which passes two values to hello_get.py program using GET method.
Below is hello_get.py script to handle input given by web browser. We are going to use cgi module, which makes it very easy to access passed information −
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print ("Content-type:text/html\r\n\r\n")
print ("<html>")
print ("<head>")
print ("<title>Hello - Second CGI Program</title>")
print ("</head>")
print ("<body>")
print ("<h2>Hello %s %s</h2>" % (first_name, last_name))
print ("</body>")
print ("</html>")
This would generate the following result −
Hello ZARA ALI
This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "get">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form, you enter First and Last Name and then click submit button to see the result.
A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input.
Below is same hello_get.py script which handles GET as well as POST method.
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
Let us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code for a form with two checkboxes −
<form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Maths
<input type = "checkbox" name = "physics" value = "on" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
The result of this code is the following form −
Below is checkbox.cgi script to handle input given by web browser for checkbox button.
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('maths'):
math_flag = "ON"
else:
math_flag = "OFF"
if form.getvalue('physics'):
physics_flag = "ON"
else:
physics_flag = "OFF"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % math_flag
print "<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"
Radio Buttons are used when only one option is required to be selected.
Here is example HTML code for a form with two radio buttons −
<form action = "/cgi-bin/radiobutton.py" method = "post" target = "_blank">
<input type = "radio" name = "subject" value = "maths" /> Maths
<input type = "radio" name = "subject" value = "physics" /> Physics
<input type = "submit" value = "Select Subject" />
</form>
The result of this code is the following form −
Below is radiobutton.py script to handle input given by web browser for radio button −
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('subject'):
subject = form.getvalue('subject')
else:
subject = "Not set"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
TEXTAREA element is used when multiline text has to be passed to the CGI Program.
Here is example HTML code for a form with a TEXTAREA box −
<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>
The result of this code is the following form −
Below is textarea.cgi script to handle input given by web browser −
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('textcontent'):
text_content = form.getvalue('textcontent')
else:
text_content = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"
Drop Down Box is used when we have many options available but only one or two will be selected.
Here is example HTML code for a form with one drop down box −
<form action = "/cgi-bin/dropdown.py" method = "post" target = "_blank">
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
<input type = "submit" value = "Submit"/>
</form>
The result of this code is the following form −
Below is dropdown.py script to handle input given by web browser.
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
if form.getvalue('dropdown'):
subject = form.getvalue('dropdown')
else:
subject = "Not entered"
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"
HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. How to maintain user's session information across all the web pages?
In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics.
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser.
Domain − The domain name of your site.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists.
Name = Value − Cookies are set and retrieved in the form of key and value pairs.
Name = Value − Cookies are set and retrieved in the form of key and value pairs.
It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows −
#!/usr/bin/python
print "Set-Cookie:UserID = XYZ;\r\n"
print "Set-Cookie:Password = XYZ123;\r\n"
print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT;\r\n"
print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n"
print "Set-Cookie:Path = /perl;\n"
print "Content-type:text/html\r\n\r\n"
...........Rest of the HTML Content....
From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form −
key1 = value1;key2 = value2;key3 = value3....
Here is an example of how to retrieve cookies.
#!/usr/bin/python
# Import modules for CGI handling
from os import environ
import cgi, cgitb
if environ.has_key('HTTP_COOKIE'):
for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):
(key, value ) = split(cookie, '=');
if key == "UserID":
user_id = value
if key == "Password":
password = value
print "User ID = %s" % user_id
print "Password = %s" % password
This produces the following result for the cookies set by above script −
User ID = XYZ
Password = XYZ123
To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a "Browse" button.
<html>
<body>
<form enctype = "multipart/form-data" action = "save_file.py" method = "post">
<p>File: <input type = "file" name = "filename" /></p>
<p><input type = "submit" value = "Upload" /></p>
</form>
</body>
</html>
The result of this code is the following form −
File:
Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server.
Here is the script save_file.py to handle file upload −
#!/usr/bin/python
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# Get filename here.
fileitem = form['filename']
# Test if the file was uploaded
if fileitem.filename:
# strip leading path from file name to avoid
# directory traversal attacks
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = 'The file "' + fn + '" was uploaded successfully'
else:
message = 'No file was uploaded'
print """\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
""" % (message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
Sometimes, it is desired that you want to give option where a user can click a link and it will pop up a "File Download" dialogue box to the user instead of displaying actual content. This is very easy and can be achieved through HTTP header. This HTTP header is be different from the header mentioned in previous section.
For example, if you want make a FileName file downloadable from a given link, then its syntax is as follows −
#!/usr/bin/python
# HTTP Header
print "Content-Type:application/octet-stream; name = \"FileName\"\r\n";
print "Content-Disposition: attachment; filename = \"FileName\"\r\n\n";
# Actual File Content will go here.
fo = open("foo.txt", "rb")
str = fo.read();
print str
# Close opend file
fo.close()
Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2537,
"s": 2340,
"text": "The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script. The CGI specs are currently maintained by the NCSA."
},
{
"code": null,
"e": 2679,
"s": 2537,
"text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers."
},
{
"code": null,
"e": 2821,
"s": 2679,
"text": "The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers."
},
{
"code": null,
"e": 2883,
"s": 2821,
"text": "The current version is CGI/1.1 and CGI/1.2 is under progress."
},
{
"code": null,
"e": 2945,
"s": 2883,
"text": "The current version is CGI/1.1 and CGI/1.2 is under progress."
},
{
"code": null,
"e": 3070,
"s": 2945,
"text": "To understand the concept of CGI, let us see what happens when we click a hyper link to browse a particular web page or URL."
},
{
"code": null,
"e": 3153,
"s": 3070,
"text": "Your browser contacts the HTTP web server and demands for the URL, i.e., filename."
},
{
"code": null,
"e": 3236,
"s": 3153,
"text": "Your browser contacts the HTTP web server and demands for the URL, i.e., filename."
},
{
"code": null,
"e": 3424,
"s": 3236,
"text": "Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file."
},
{
"code": null,
"e": 3612,
"s": 3424,
"text": "Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file."
},
{
"code": null,
"e": 3711,
"s": 3612,
"text": "Web browser takes response from web server and displays either the received file or error message."
},
{
"code": null,
"e": 3810,
"s": 3711,
"text": "Web browser takes response from web server and displays either the received file or error message."
},
{
"code": null,
"e": 4255,
"s": 3810,
"text": "However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. This function is called the Common Gateway Interface or CGI and the programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc."
},
{
"code": null,
"e": 4682,
"s": 4255,
"text": "Before you proceed with CGI Programming, make sure that your Web Server supports CGI and it is configured to handle CGI Programs. All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin. By convention, CGI files have extension as. cgi, but you can keep your files with python extension .py as well."
},
{
"code": null,
"e": 4908,
"s": 4682,
"text": "By default, the Linux server is configured to run only the scripts in the cgi-bin directory in /var/www. If you want to specify any other directory to run your CGI scripts, comment the following lines in the httpd.conf file −"
},
{
"code": null,
"e": 5088,
"s": 4908,
"text": "<Directory \"/var/www/cgi-bin\">\n AllowOverride None\n Options ExecCGI\n Order allow,deny\n Allow from all\n</Directory>\n\n<Directory \"/var/www/cgi-bin\">\nOptions All\n</Directory>"
},
{
"code": null,
"e": 5228,
"s": 5088,
"text": "Here, we assume that you have Web Server up and running successfully and you are able to run any other CGI program like Perl or Shell, etc."
},
{
"code": null,
"e": 5513,
"s": 5228,
"text": "Here is a simple link, which is linked to a CGI script called hello.py. This file is kept in /var/www/cgi-bin directory and it has following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable."
},
{
"code": null,
"e": 5794,
"s": 5513,
"text": "#!/usr/bin/python\n\nprint (\"Content-type:text/html\\r\\n\\r\\n\")\nprint ('<html>')\nprint ('<head>')\nprint ('<title>Hello Word - First CGI Program</title>')\nprint ('</head>')\nprint ('<body>')\nprint ('<h2>Hello Word! This is my first CGI program</h2>')\nprint ('</body>')\nprint ('</html>')"
},
{
"code": null,
"e": 5902,
"s": 5794,
"text": "Note − First line in the script must be path to Python executable. In Linux it should be #!/usr/bin/python3"
},
{
"code": null,
"e": 5937,
"s": 5902,
"text": "Enter following URL in yor browser"
},
{
"code": null,
"e": 5977,
"s": 5937,
"text": "http://localhost:8080/cgi-bin/hello.py\n"
},
{
"code": null,
"e": 6019,
"s": 5977,
"text": "Hello Word! This is my first CGI program\n"
},
{
"code": null,
"e": 6349,
"s": 6019,
"text": "This hello.py script is a simple Python script, which writes its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\\r\\n\\r\\n. This line is sent back to the browser and it specifies the content type to be displayed on the browser screen."
},
{
"code": null,
"e": 6564,
"s": 6349,
"text": "By now you must have understood basic concept of CGI and you can write many complicated CGI programs using Python. This script can interact with any other external system also to exchange information such as RDBMS."
},
{
"code": null,
"e": 6735,
"s": 6564,
"text": "The line Content-type:text/html\\r\\n\\r\\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form −"
},
{
"code": null,
"e": 6812,
"s": 6735,
"text": "HTTP Field Name: Field Content\n\nFor Example\nContent-type: text/html\\r\\n\\r\\n\n"
},
{
"code": null,
"e": 6911,
"s": 6812,
"text": "There are few other important HTTP headers, which you will use frequently in your CGI Programming."
},
{
"code": null,
"e": 6925,
"s": 6911,
"text": "Content-type:"
},
{
"code": null,
"e": 7021,
"s": 6925,
"text": "A MIME string defining the format of the file being returned. Example is Content-type:text/html"
},
{
"code": null,
"e": 7035,
"s": 7021,
"text": "Expires: Date"
},
{
"code": null,
"e": 7211,
"s": 7035,
"text": "The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT."
},
{
"code": null,
"e": 7225,
"s": 7211,
"text": "Location: URL"
},
{
"code": null,
"e": 7338,
"s": 7225,
"text": "The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file."
},
{
"code": null,
"e": 7358,
"s": 7338,
"text": "Last-modified: Date"
},
{
"code": null,
"e": 7405,
"s": 7358,
"text": "The date of last modification of the resource."
},
{
"code": null,
"e": 7423,
"s": 7405,
"text": "Content-length: N"
},
{
"code": null,
"e": 7551,
"s": 7423,
"text": "The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file."
},
{
"code": null,
"e": 7570,
"s": 7551,
"text": "Set-Cookie: String"
},
{
"code": null,
"e": 7611,
"s": 7570,
"text": "Set the cookie passed through the string"
},
{
"code": null,
"e": 7754,
"s": 7611,
"text": "All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program."
},
{
"code": null,
"e": 7767,
"s": 7754,
"text": "CONTENT_TYPE"
},
{
"code": null,
"e": 7887,
"s": 7767,
"text": "The data type of the content. Used when the client is sending attached content to the server. For example, file upload."
},
{
"code": null,
"e": 7902,
"s": 7887,
"text": "CONTENT_LENGTH"
},
{
"code": null,
"e": 7979,
"s": 7902,
"text": "The length of the query information. It is available only for POST requests."
},
{
"code": null,
"e": 7991,
"s": 7979,
"text": "HTTP_COOKIE"
},
{
"code": null,
"e": 8048,
"s": 7991,
"text": "Returns the set cookies in the form of key & value pair."
},
{
"code": null,
"e": 8064,
"s": 8048,
"text": "HTTP_USER_AGENT"
},
{
"code": null,
"e": 8198,
"s": 8064,
"text": "The User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser."
},
{
"code": null,
"e": 8208,
"s": 8198,
"text": "PATH_INFO"
},
{
"code": null,
"e": 8237,
"s": 8208,
"text": "The path for the CGI script."
},
{
"code": null,
"e": 8250,
"s": 8237,
"text": "QUERY_STRING"
},
{
"code": null,
"e": 8316,
"s": 8250,
"text": "The URL-encoded information that is sent with GET method request."
},
{
"code": null,
"e": 8328,
"s": 8316,
"text": "REMOTE_ADDR"
},
{
"code": null,
"e": 8428,
"s": 8328,
"text": "The IP address of the remote host making the request. This is useful logging or for authentication."
},
{
"code": null,
"e": 8440,
"s": 8428,
"text": "REMOTE_HOST"
},
{
"code": null,
"e": 8583,
"s": 8440,
"text": "The fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address."
},
{
"code": null,
"e": 8598,
"s": 8583,
"text": "REQUEST_METHOD"
},
{
"code": null,
"e": 8677,
"s": 8598,
"text": "The method used to make the request. The most common methods are GET and POST."
},
{
"code": null,
"e": 8693,
"s": 8677,
"text": "SCRIPT_FILENAME"
},
{
"code": null,
"e": 8726,
"s": 8693,
"text": "The full path to the CGI script."
},
{
"code": null,
"e": 8738,
"s": 8726,
"text": "SCRIPT_NAME"
},
{
"code": null,
"e": 8766,
"s": 8738,
"text": "The name of the CGI script."
},
{
"code": null,
"e": 8778,
"s": 8766,
"text": "SERVER_NAME"
},
{
"code": null,
"e": 8814,
"s": 8778,
"text": "The server's hostname or IP Address"
},
{
"code": null,
"e": 8830,
"s": 8814,
"text": "SERVER_SOFTWARE"
},
{
"code": null,
"e": 8890,
"s": 8830,
"text": "The name and version of the software the server is running."
},
{
"code": null,
"e": 9001,
"s": 8890,
"text": "Here is small CGI program to list out all the CGI variables. Click this link to see the result Get Environment"
},
{
"code": null,
"e": 9218,
"s": 9001,
"text": "#!/usr/bin/python\n\nimport os\n\nprint (\"Content-type: text/html\\r\\n\\r\\n\");\nprint (\"<font size=+1>Environment</font><\\br>\");\nfor param in os.environ.keys():\n print (\"<b>%20s</b>: %s<\\br>\" % (param, os.environ[param]))"
},
{
"code": null,
"e": 9496,
"s": 9218,
"text": "You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your CGI Program. Most frequently, browser uses two methods two pass this information to web server. These methods are GET Method and POST Method."
},
{
"code": null,
"e": 9659,
"s": 9496,
"text": "The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows −"
},
{
"code": null,
"e": 9721,
"s": 9659,
"text": "http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2\n"
},
{
"code": null,
"e": 9888,
"s": 9721,
"text": "The GET method is the default method to pass information from the browser to the web server and it produces a long string that appears in your browser's Location:box."
},
{
"code": null,
"e": 10055,
"s": 9888,
"text": "The GET method is the default method to pass information from the browser to the web server and it produces a long string that appears in your browser's Location:box."
},
{
"code": null,
"e": 10151,
"s": 10055,
"text": "Never use GET method if you have password or other sensitive information to pass to the server."
},
{
"code": null,
"e": 10247,
"s": 10151,
"text": "Never use GET method if you have password or other sensitive information to pass to the server."
},
{
"code": null,
"e": 10336,
"s": 10247,
"text": "The GET method has size limtation: only 1024 characters can be sent in a request string."
},
{
"code": null,
"e": 10425,
"s": 10336,
"text": "The GET method has size limtation: only 1024 characters can be sent in a request string."
},
{
"code": null,
"e": 10570,
"s": 10425,
"text": "The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable."
},
{
"code": null,
"e": 10715,
"s": 10570,
"text": "The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable."
},
{
"code": null,
"e": 10873,
"s": 10715,
"text": "You can pass information by simply concatenating key and value pairs along with any URL or you can use HTML <FORM> tags to pass information using GET method."
},
{
"code": null,
"e": 10961,
"s": 10873,
"text": "Here is a simple URL, which passes two values to hello_get.py program using GET method."
},
{
"code": null,
"e": 11116,
"s": 10961,
"text": "Below is hello_get.py script to handle input given by web browser. We are going to use cgi module, which makes it very easy to access passed information −"
},
{
"code": null,
"e": 11613,
"s": 11116,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint (\"Content-type:text/html\\r\\n\\r\\n\")\nprint (\"<html>\")\nprint (\"<head>\")\nprint (\"<title>Hello - Second CGI Program</title>\")\nprint (\"</head>\")\nprint (\"<body>\")\nprint (\"<h2>Hello %s %s</h2>\" % (first_name, last_name))\nprint (\"</body>\")\nprint (\"</html>\")"
},
{
"code": null,
"e": 11656,
"s": 11613,
"text": "This would generate the following result −"
},
{
"code": null,
"e": 11672,
"s": 11656,
"text": "Hello ZARA ALI\n"
},
{
"code": null,
"e": 11796,
"s": 11672,
"text": "This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input."
},
{
"code": null,
"e": 12028,
"s": 11796,
"text": "<form action = \"/cgi-bin/hello_get.py\" method = \"get\">\n First Name: <input type = \"text\" name = \"first_name\"> <br />\n\n Last Name: <input type = \"text\" name = \"last_name\" />\n <input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 12151,
"s": 12028,
"text": "Here is the actual output of the above form, you enter First and Last Name and then click submit button to see the result."
},
{
"code": null,
"e": 12487,
"s": 12151,
"text": "A generally more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes into the CGI script in the form of the standard input."
},
{
"code": null,
"e": 12563,
"s": 12487,
"text": "Below is same hello_get.py script which handles GET as well as POST method."
},
{
"code": null,
"e": 13042,
"s": 12563,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nfirst_name = form.getvalue('first_name')\nlast_name = form.getvalue('last_name')\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Hello - Second CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2>Hello %s %s</h2>\" % (first_name, last_name)\nprint \"</body>\"\nprint \"</html>\""
},
{
"code": null,
"e": 13199,
"s": 13042,
"text": "Let us take again same example as above which passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input."
},
{
"code": null,
"e": 13421,
"s": 13199,
"text": "<form action = \"/cgi-bin/hello_get.py\" method = \"post\">\nFirst Name: <input type = \"text\" name = \"first_name\"><br />\nLast Name: <input type = \"text\" name = \"last_name\" />\n\n<input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 13544,
"s": 13421,
"text": "Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result."
},
{
"code": null,
"e": 13618,
"s": 13544,
"text": "Checkboxes are used when more than one option is required to be selected."
},
{
"code": null,
"e": 13677,
"s": 13618,
"text": "Here is example HTML code for a form with two checkboxes −"
},
{
"code": null,
"e": 13947,
"s": 13677,
"text": "<form action = \"/cgi-bin/checkbox.cgi\" method = \"POST\" target = \"_blank\">\n <input type = \"checkbox\" name = \"maths\" value = \"on\" /> Maths\n <input type = \"checkbox\" name = \"physics\" value = \"on\" /> Physics\n <input type = \"submit\" value = \"Select Subject\" />\n</form>"
},
{
"code": null,
"e": 13995,
"s": 13947,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 14082,
"s": 13995,
"text": "Below is checkbox.cgi script to handle input given by web browser for checkbox button."
},
{
"code": null,
"e": 14695,
"s": 14082,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('maths'):\n math_flag = \"ON\"\nelse:\n math_flag = \"OFF\"\n\nif form.getvalue('physics'):\n physics_flag = \"ON\"\nelse:\n physics_flag = \"OFF\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Checkbox - Third CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> CheckBox Maths is : %s</h2>\" % math_flag\nprint \"<h2> CheckBox Physics is : %s</h2>\" % physics_flag\nprint \"</body>\"\nprint \"</html>\""
},
{
"code": null,
"e": 14767,
"s": 14695,
"text": "Radio Buttons are used when only one option is required to be selected."
},
{
"code": null,
"e": 14829,
"s": 14767,
"text": "Here is example HTML code for a form with two radio buttons −"
},
{
"code": null,
"e": 15105,
"s": 14829,
"text": "<form action = \"/cgi-bin/radiobutton.py\" method = \"post\" target = \"_blank\">\n <input type = \"radio\" name = \"subject\" value = \"maths\" /> Maths\n <input type = \"radio\" name = \"subject\" value = \"physics\" /> Physics\n <input type = \"submit\" value = \"Select Subject\" />\n</form>"
},
{
"code": null,
"e": 15153,
"s": 15105,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 15240,
"s": 15153,
"text": "Below is radiobutton.py script to handle input given by web browser for radio button −"
},
{
"code": null,
"e": 15730,
"s": 15240,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('subject'):\n subject = form.getvalue('subject')\nelse:\n subject = \"Not set\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Radio - Fourth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\""
},
{
"code": null,
"e": 15812,
"s": 15730,
"text": "TEXTAREA element is used when multiline text has to be passed to the CGI Program."
},
{
"code": null,
"e": 15871,
"s": 15812,
"text": "Here is example HTML code for a form with a TEXTAREA box −"
},
{
"code": null,
"e": 16100,
"s": 15871,
"text": "<form action = \"/cgi-bin/textarea.py\" method = \"post\" target = \"_blank\">\n <textarea name = \"textcontent\" cols = \"40\" rows = \"4\">\n Type your text here...\n </textarea>\n <input type = \"submit\" value = \"Submit\" />\n</form>"
},
{
"code": null,
"e": 16148,
"s": 16100,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 16216,
"s": 16148,
"text": "Below is textarea.cgi script to handle input given by web browser −"
},
{
"code": null,
"e": 16725,
"s": 16216,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('textcontent'):\n text_content = form.getvalue('textcontent')\nelse:\n text_content = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\";\nprint \"<title>Text Area - Fifth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Entered Text Content is %s</h2>\" % text_content\nprint \"</body>\""
},
{
"code": null,
"e": 16821,
"s": 16725,
"text": "Drop Down Box is used when we have many options available but only one or two will be selected."
},
{
"code": null,
"e": 16883,
"s": 16821,
"text": "Here is example HTML code for a form with one drop down box −"
},
{
"code": null,
"e": 17155,
"s": 16883,
"text": "<form action = \"/cgi-bin/dropdown.py\" method = \"post\" target = \"_blank\">\n <select name = \"dropdown\">\n <option value = \"Maths\" selected>Maths</option>\n <option value = \"Physics\">Physics</option>\n </select>\n <input type = \"submit\" value = \"Submit\"/>\n</form>"
},
{
"code": null,
"e": 17203,
"s": 17155,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 17269,
"s": 17203,
"text": "Below is dropdown.py script to handle input given by web browser."
},
{
"code": null,
"e": 17771,
"s": 17269,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nimport cgi, cgitb \n\n# Create instance of FieldStorage \nform = cgi.FieldStorage() \n\n# Get data from fields\nif form.getvalue('dropdown'):\n subject = form.getvalue('dropdown')\nelse:\n subject = \"Not entered\"\n\nprint \"Content-type:text/html\\r\\n\\r\\n\"\nprint \"<html>\"\nprint \"<head>\"\nprint \"<title>Dropdown Box - Sixth CGI Program</title>\"\nprint \"</head>\"\nprint \"<body>\"\nprint \"<h2> Selected Subject is %s</h2>\" % subject\nprint \"</body>\"\nprint \"</html>\""
},
{
"code": null,
"e": 18045,
"s": 17771,
"text": "HTTP protocol is a stateless protocol. For a commercial website, it is required to maintain session information among different pages. For example, one user registration ends after completing many pages. How to maintain user's session information across all the web pages?"
},
{
"code": null,
"e": 18254,
"s": 18045,
"text": "In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics."
},
{
"code": null,
"e": 18604,
"s": 18254,
"text": "Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored."
},
{
"code": null,
"e": 18671,
"s": 18604,
"text": "Cookies are a plain text data record of 5 variable-length fields −"
},
{
"code": null,
"e": 18791,
"s": 18671,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 18911,
"s": 18791,
"text": "Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 18950,
"s": 18911,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 18989,
"s": 18950,
"text": "Domain − The domain name of your site."
},
{
"code": null,
"e": 19137,
"s": 18989,
"text": "Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 19285,
"s": 19137,
"text": "Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the cookie from any directory or page."
},
{
"code": null,
"e": 19448,
"s": 19285,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 19611,
"s": 19448,
"text": "Secure − If this field contains the word \"secure\", then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists."
},
{
"code": null,
"e": 19692,
"s": 19611,
"text": "Name = Value − Cookies are set and retrieved in the form of key and value pairs."
},
{
"code": null,
"e": 19773,
"s": 19692,
"text": "Name = Value − Cookies are set and retrieved in the form of key and value pairs."
},
{
"code": null,
"e": 19991,
"s": 19773,
"text": "It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows −"
},
{
"code": null,
"e": 20326,
"s": 19991,
"text": "#!/usr/bin/python\nprint \"Set-Cookie:UserID = XYZ;\\r\\n\"\nprint \"Set-Cookie:Password = XYZ123;\\r\\n\"\nprint \"Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT;\\r\\n\"\nprint \"Set-Cookie:Domain = www.tutorialspoint.com;\\r\\n\"\nprint \"Set-Cookie:Path = /perl;\\n\"\nprint \"Content-type:text/html\\r\\n\\r\\n\"\n...........Rest of the HTML Content...."
},
{
"code": null,
"e": 20436,
"s": 20326,
"text": "From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies."
},
{
"code": null,
"e": 20603,
"s": 20436,
"text": "It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line \"Content-type:text/html\\r\\n\\r\\n."
},
{
"code": null,
"e": 20747,
"s": 20603,
"text": "It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form −"
},
{
"code": null,
"e": 20794,
"s": 20747,
"text": "key1 = value1;key2 = value2;key3 = value3....\n"
},
{
"code": null,
"e": 20841,
"s": 20794,
"text": "Here is an example of how to retrieve cookies."
},
{
"code": null,
"e": 21251,
"s": 20841,
"text": "#!/usr/bin/python\n\n# Import modules for CGI handling \nfrom os import environ\nimport cgi, cgitb\n\nif environ.has_key('HTTP_COOKIE'):\n for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):\n (key, value ) = split(cookie, '=');\n if key == \"UserID\":\n user_id = value\n\n if key == \"Password\":\n password = value\n\nprint \"User ID = %s\" % user_id\nprint \"Password = %s\" % password"
},
{
"code": null,
"e": 21324,
"s": 21251,
"text": "This produces the following result for the cookies set by above script −"
},
{
"code": null,
"e": 21357,
"s": 21324,
"text": "User ID = XYZ\nPassword = XYZ123\n"
},
{
"code": null,
"e": 21509,
"s": 21357,
"text": "To upload a file, the HTML form must have the enctype attribute set to multipart/form-data. The input tag with the file type creates a \"Browse\" button."
},
{
"code": null,
"e": 21761,
"s": 21509,
"text": "<html>\n <body>\n <form enctype = \"multipart/form-data\" action = \"save_file.py\" method = \"post\">\n <p>File: <input type = \"file\" name = \"filename\" /></p>\n <p><input type = \"submit\" value = \"Upload\" /></p>\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 21809,
"s": 21761,
"text": "The result of this code is the following form −"
},
{
"code": null,
"e": 21816,
"s": 21809,
"text": "File: "
},
{
"code": null,
"e": 21952,
"s": 21816,
"text": "Above example has been disabled intentionally to save people uploading file on our server, but you can try above code with your server."
},
{
"code": null,
"e": 22008,
"s": 21952,
"text": "Here is the script save_file.py to handle file upload −"
},
{
"code": null,
"e": 22605,
"s": 22008,
"text": "#!/usr/bin/python\n\nimport cgi, os\nimport cgitb; cgitb.enable()\n\nform = cgi.FieldStorage()\n\n# Get filename here.\nfileitem = form['filename']\n\n# Test if the file was uploaded\nif fileitem.filename:\n # strip leading path from file name to avoid \n # directory traversal attacks\n fn = os.path.basename(fileitem.filename)\n open('/tmp/' + fn, 'wb').write(fileitem.file.read())\n\n message = 'The file \"' + fn + '\" was uploaded successfully'\n \nelse:\n message = 'No file was uploaded'\n \nprint \"\"\"\\\nContent-Type: text/html\\n\n<html>\n <body>\n <p>%s</p>\n </body>\n</html>\n\"\"\" % (message,)"
},
{
"code": null,
"e": 22791,
"s": 22605,
"text": "If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows, otherwise on your windows machine above open() statement should work fine."
},
{
"code": null,
"e": 22853,
"s": 22791,
"text": "fn = os.path.basename(fileitem.filename.replace(\"\\\\\", \"/\" ))\n"
},
{
"code": null,
"e": 23176,
"s": 22853,
"text": "Sometimes, it is desired that you want to give option where a user can click a link and it will pop up a \"File Download\" dialogue box to the user instead of displaying actual content. This is very easy and can be achieved through HTTP header. This HTTP header is be different from the header mentioned in previous section."
},
{
"code": null,
"e": 23286,
"s": 23176,
"text": "For example, if you want make a FileName file downloadable from a given link, then its syntax is as follows −"
},
{
"code": null,
"e": 23586,
"s": 23286,
"text": "#!/usr/bin/python\n\n# HTTP Header\nprint \"Content-Type:application/octet-stream; name = \\\"FileName\\\"\\r\\n\";\nprint \"Content-Disposition: attachment; filename = \\\"FileName\\\"\\r\\n\\n\";\n\n# Actual File Content will go here.\nfo = open(\"foo.txt\", \"rb\")\n\nstr = fo.read();\nprint str\n\n# Close opend file\nfo.close()"
},
{
"code": null,
"e": 23670,
"s": 23586,
"text": "Hope you enjoyed this tutorial. If yes, please send me your feedback at: Contact Us"
},
{
"code": null,
"e": 23707,
"s": 23670,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 23723,
"s": 23707,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 23756,
"s": 23723,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 23775,
"s": 23756,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 23810,
"s": 23775,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 23832,
"s": 23810,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 23866,
"s": 23832,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 23894,
"s": 23866,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 23929,
"s": 23894,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 23943,
"s": 23929,
"text": " Lets Kode It"
},
{
"code": null,
"e": 23976,
"s": 23943,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 23993,
"s": 23976,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 24000,
"s": 23993,
"text": " Print"
},
{
"code": null,
"e": 24011,
"s": 24000,
"text": " Add Notes"
}
] |
Plotting Geospatial Data with Cartopy | by Andrew Udell | Towards Data Science
|
With the age of big data comes the age of big geospatial data. Researchers increasingly have access to geographic information which can do anything from track the migration patterns of endangered species to map every donut shop in the country.
To help visualize this information, the python library Cartopy can create professional and publishable maps with only a few lines of code. Built with Matplotlib in mind, its syntax is familiar and easy to understand.
To start, we’ll create the simplest possible world map. Before writing any heavy code, the Cartopy and Matplotlib libraries in python should be installed.
import cartopy.crs as crsimport cartopy.feature as cfeatureimport matplotlib.pyplot as plt
Above, the prerequisite libraries are imported and ready to use.
# Initialize the figurefigure = plt.figure(figsize=(8,6))# use the Mercator projectionax = figure.add_subplot(1,1,1, projection=crs.Mercator(())# Add feature to the mapax.stock_img()plt.show()
The next few lines of code go through the basic process of creating a map:
Initialize the map and specify the size of the figure with the figsize argumentAdd a subplot which specifies the projection usedAdd features to the subplot
Initialize the map and specify the size of the figure with the figsize argument
Add a subplot which specifies the projection used
Add features to the subplot
With only a few lines of codes, the bare minimum for a map is created. Unfortunately, this map is rather bland, so we’ll add some extra features to it.
figure = plt.figure(figsize=(8,6))ax = figure.add_subplot(1,1,1, projection=crs.Mercator())# adds a stock image as a backgroundax.stock_img()# adds national bordersax.add_feature(cfeature.BORDERS)# add coastlinesax.add_feature(cfeature.COASTLINE)plt.show()
By modifying the variable ax, more information is added to the map. In this case, national borders and coastlines are drawn. Additional features, such as major rivers and lakes map also be included with the same method. A full list of features can be found here.
The above maps use the famous Mercator projection. While perfectly sufficient in most cases, Mercator map distorts land sizes because it stretches a sphere onto a square. Luckily, Cartopy supports other projections.
figure = plt.figure(figsize=(8,6))# set the projection to Mollweideax = figure.add_subplot(1,1,1, projection=crs.Mollweide())ax.stock_img()plt.show()
By changing the projection argument from crs.Mercator() to crs.Molleweide(), a different, more elliptical (and accurate) projection is created.
figure = plt.figure(figsize=(8,6))# Set the projection to Interrupted Goode Homolosineax = figure.add_subplot(1,1,1, projection=crs.InterruptedGoodeHomolosine())ax.stock_img()plt.show()
An even more accurate projection can be produced by using InterruptedGoodeHomolosine() in the projection argument.
These are by no means the only projections Cartopy can map. A full list can be found here.
While world maps are useful in many contexts, oftentimes data needs to be represented in a local area, such as a continent or a country.
figure = plt.figure(figsize=(8,6))ax = figure.add_subplot(1,1,1, projection=crs.Mercator())ax.add_feature(cfeature.COASTLINE)ax.add_feature(cfeature.STATES)# Zoom in on the US by setting longitude/latitude parametersax.set_extent( [ -135, # minimum latitude -60, # min longitude 20, # max latitude 55 # max longitude ], crs=crs.PlateCarree())plt.show()
After the map is initialized and the usual features are added, the ax variable is additionally modified with the set_extent() method, which specifies the ranges of longitude and latitude to set the focus on the map.
Note the argument crs, which specifies which coordinate system to use. The general convention is to use the coordinates of the Plate Carrée projection even if it disagrees with the projection of the map, because it produces more predictable results.
So far, we’ve only talked about producing generic maps, but now we’ll discussing plotting data onto those maps. The only requirement is that each observation have a valid latitude and longitude. To demonstrate, a source file of 341 airports from the US is taken from Kaggle and will be plotted on a scatter map.
import pandas as pd# Read the datadf = pd.read_csv("airports.csv")
Before any mapping is done, the Pandas library is imported to structure data and the CSV file is read into a DataFrame.
figure = plt.figure(figsize=(8,6))ax = figure.add_subplot(1,1,1, projection=crs.PlateCarree())ax.add_feature(cfeature.COASTLINE)ax.add_feature(cfeature.STATES)ax.set_extent( [-135, -60, 20, 55], crs=crs.PlateCarree())# modify the plot by adding a scatterplot over the mapplt.scatter( x=df["LONGITUDE"], y=df["LATITUDE"], color="red", s=4, alpha=1, transform=crs.PlateCarree())plt.show()
Essentially, after creating a map, Matplotlib adds a scatterplot on top of the image. To those familiar with the popular graphing library, the syntax should look very familiar. To those who aren’t, the breakdown of the arguments are:
x: the data on the x-axis. In this case, longitude
y: the data on the y-axis. In this case, latitude
color: the color of the markers
s: the size of the markers
alpha: the transparency of the markers, from 0 to 1
Additional arguments may be passed on the scatterplot to customize it further. A full list may be found here.
Also note the transform argument, which, by convention, uses the Plate Carrée projection for a similar reason as set_extent().
Cartopy is a diverse map library. Allowing for various projections and coordinate systems, it supports a wide range of possible use cases from ecological tracking to business intelligence.
Its integration with Matplotlib, however, stands out as an incredible data analysis tool. While only a simple scatter map was demonstrated, its broad and flexible use of Matplotlib means a diverse number of plots and graphs may be projected onto a map.
|
[
{
"code": null,
"e": 416,
"s": 172,
"text": "With the age of big data comes the age of big geospatial data. Researchers increasingly have access to geographic information which can do anything from track the migration patterns of endangered species to map every donut shop in the country."
},
{
"code": null,
"e": 633,
"s": 416,
"text": "To help visualize this information, the python library Cartopy can create professional and publishable maps with only a few lines of code. Built with Matplotlib in mind, its syntax is familiar and easy to understand."
},
{
"code": null,
"e": 788,
"s": 633,
"text": "To start, we’ll create the simplest possible world map. Before writing any heavy code, the Cartopy and Matplotlib libraries in python should be installed."
},
{
"code": null,
"e": 879,
"s": 788,
"text": "import cartopy.crs as crsimport cartopy.feature as cfeatureimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 944,
"s": 879,
"text": "Above, the prerequisite libraries are imported and ready to use."
},
{
"code": null,
"e": 1137,
"s": 944,
"text": "# Initialize the figurefigure = plt.figure(figsize=(8,6))# use the Mercator projectionax = figure.add_subplot(1,1,1, projection=crs.Mercator(())# Add feature to the mapax.stock_img()plt.show()"
},
{
"code": null,
"e": 1212,
"s": 1137,
"text": "The next few lines of code go through the basic process of creating a map:"
},
{
"code": null,
"e": 1368,
"s": 1212,
"text": "Initialize the map and specify the size of the figure with the figsize argumentAdd a subplot which specifies the projection usedAdd features to the subplot"
},
{
"code": null,
"e": 1448,
"s": 1368,
"text": "Initialize the map and specify the size of the figure with the figsize argument"
},
{
"code": null,
"e": 1498,
"s": 1448,
"text": "Add a subplot which specifies the projection used"
},
{
"code": null,
"e": 1526,
"s": 1498,
"text": "Add features to the subplot"
},
{
"code": null,
"e": 1678,
"s": 1526,
"text": "With only a few lines of codes, the bare minimum for a map is created. Unfortunately, this map is rather bland, so we’ll add some extra features to it."
},
{
"code": null,
"e": 1935,
"s": 1678,
"text": "figure = plt.figure(figsize=(8,6))ax = figure.add_subplot(1,1,1, projection=crs.Mercator())# adds a stock image as a backgroundax.stock_img()# adds national bordersax.add_feature(cfeature.BORDERS)# add coastlinesax.add_feature(cfeature.COASTLINE)plt.show()"
},
{
"code": null,
"e": 2198,
"s": 1935,
"text": "By modifying the variable ax, more information is added to the map. In this case, national borders and coastlines are drawn. Additional features, such as major rivers and lakes map also be included with the same method. A full list of features can be found here."
},
{
"code": null,
"e": 2414,
"s": 2198,
"text": "The above maps use the famous Mercator projection. While perfectly sufficient in most cases, Mercator map distorts land sizes because it stretches a sphere onto a square. Luckily, Cartopy supports other projections."
},
{
"code": null,
"e": 2564,
"s": 2414,
"text": "figure = plt.figure(figsize=(8,6))# set the projection to Mollweideax = figure.add_subplot(1,1,1, projection=crs.Mollweide())ax.stock_img()plt.show()"
},
{
"code": null,
"e": 2708,
"s": 2564,
"text": "By changing the projection argument from crs.Mercator() to crs.Molleweide(), a different, more elliptical (and accurate) projection is created."
},
{
"code": null,
"e": 2894,
"s": 2708,
"text": "figure = plt.figure(figsize=(8,6))# Set the projection to Interrupted Goode Homolosineax = figure.add_subplot(1,1,1, projection=crs.InterruptedGoodeHomolosine())ax.stock_img()plt.show()"
},
{
"code": null,
"e": 3009,
"s": 2894,
"text": "An even more accurate projection can be produced by using InterruptedGoodeHomolosine() in the projection argument."
},
{
"code": null,
"e": 3100,
"s": 3009,
"text": "These are by no means the only projections Cartopy can map. A full list can be found here."
},
{
"code": null,
"e": 3237,
"s": 3100,
"text": "While world maps are useful in many contexts, oftentimes data needs to be represented in a local area, such as a continent or a country."
},
{
"code": null,
"e": 3627,
"s": 3237,
"text": "figure = plt.figure(figsize=(8,6))ax = figure.add_subplot(1,1,1, projection=crs.Mercator())ax.add_feature(cfeature.COASTLINE)ax.add_feature(cfeature.STATES)# Zoom in on the US by setting longitude/latitude parametersax.set_extent( [ -135, # minimum latitude -60, # min longitude 20, # max latitude 55 # max longitude ], crs=crs.PlateCarree())plt.show()"
},
{
"code": null,
"e": 3843,
"s": 3627,
"text": "After the map is initialized and the usual features are added, the ax variable is additionally modified with the set_extent() method, which specifies the ranges of longitude and latitude to set the focus on the map."
},
{
"code": null,
"e": 4094,
"s": 3843,
"text": "Note the argument crs, which specifies which coordinate system to use. The general convention is to use the coordinates of the Plate Carrée projection even if it disagrees with the projection of the map, because it produces more predictable results."
},
{
"code": null,
"e": 4406,
"s": 4094,
"text": "So far, we’ve only talked about producing generic maps, but now we’ll discussing plotting data onto those maps. The only requirement is that each observation have a valid latitude and longitude. To demonstrate, a source file of 341 airports from the US is taken from Kaggle and will be plotted on a scatter map."
},
{
"code": null,
"e": 4473,
"s": 4406,
"text": "import pandas as pd# Read the datadf = pd.read_csv(\"airports.csv\")"
},
{
"code": null,
"e": 4593,
"s": 4473,
"text": "Before any mapping is done, the Pandas library is imported to structure data and the CSV file is read into a DataFrame."
},
{
"code": null,
"e": 5004,
"s": 4593,
"text": "figure = plt.figure(figsize=(8,6))ax = figure.add_subplot(1,1,1, projection=crs.PlateCarree())ax.add_feature(cfeature.COASTLINE)ax.add_feature(cfeature.STATES)ax.set_extent( [-135, -60, 20, 55], crs=crs.PlateCarree())# modify the plot by adding a scatterplot over the mapplt.scatter( x=df[\"LONGITUDE\"], y=df[\"LATITUDE\"], color=\"red\", s=4, alpha=1, transform=crs.PlateCarree())plt.show()"
},
{
"code": null,
"e": 5238,
"s": 5004,
"text": "Essentially, after creating a map, Matplotlib adds a scatterplot on top of the image. To those familiar with the popular graphing library, the syntax should look very familiar. To those who aren’t, the breakdown of the arguments are:"
},
{
"code": null,
"e": 5289,
"s": 5238,
"text": "x: the data on the x-axis. In this case, longitude"
},
{
"code": null,
"e": 5339,
"s": 5289,
"text": "y: the data on the y-axis. In this case, latitude"
},
{
"code": null,
"e": 5371,
"s": 5339,
"text": "color: the color of the markers"
},
{
"code": null,
"e": 5398,
"s": 5371,
"text": "s: the size of the markers"
},
{
"code": null,
"e": 5450,
"s": 5398,
"text": "alpha: the transparency of the markers, from 0 to 1"
},
{
"code": null,
"e": 5560,
"s": 5450,
"text": "Additional arguments may be passed on the scatterplot to customize it further. A full list may be found here."
},
{
"code": null,
"e": 5688,
"s": 5560,
"text": "Also note the transform argument, which, by convention, uses the Plate Carrée projection for a similar reason as set_extent()."
},
{
"code": null,
"e": 5877,
"s": 5688,
"text": "Cartopy is a diverse map library. Allowing for various projections and coordinate systems, it supports a wide range of possible use cases from ecological tracking to business intelligence."
}
] |
C - Storage Classes
|
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program −
auto
register
static
extern
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables.
The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.
In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result −
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows −
$gcc main.c support.c
It will produce the executable program a.out. When this program is executed, it produces the following result −
count is 5
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2291,
"s": 2084,
"text": "A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program −"
},
{
"code": null,
"e": 2296,
"s": 2291,
"text": "auto"
},
{
"code": null,
"e": 2305,
"s": 2296,
"text": "register"
},
{
"code": null,
"e": 2312,
"s": 2305,
"text": "static"
},
{
"code": null,
"e": 2319,
"s": 2312,
"text": "extern"
},
{
"code": null,
"e": 2396,
"s": 2319,
"text": "The auto storage class is the default storage class for all local variables."
},
{
"code": null,
"e": 2433,
"s": 2396,
"text": "{\n int mount;\n auto int month;\n}"
},
{
"code": null,
"e": 2570,
"s": 2433,
"text": "The example above defines two variables with in the same storage class. 'auto' can only be used within functions, i.e., local variables."
},
{
"code": null,
"e": 2870,
"s": 2570,
"text": "The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location)."
},
{
"code": null,
"e": 2898,
"s": 2870,
"text": "{\n register int miles;\n}"
},
{
"code": null,
"e": 3202,
"s": 2898,
"text": "The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions."
},
{
"code": null,
"e": 3511,
"s": 3202,
"text": "The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls."
},
{
"code": null,
"e": 3677,
"s": 3511,
"text": "The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared."
},
{
"code": null,
"e": 3822,
"s": 3677,
"text": "In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class."
},
{
"code": null,
"e": 4159,
"s": 3822,
"text": "#include <stdio.h>\n \n/* function declaration */\nvoid func(void);\n \nstatic int count = 5; /* global variable */\n \nmain() {\n\n while(count--) {\n func();\n }\n\t\n return 0;\n}\n\n/* function definition */\nvoid func( void ) {\n\n static int i = 5; /* local static variable */\n i++;\n\n printf(\"i is %d and count is %d\\n\", i, count);\n}"
},
{
"code": null,
"e": 4240,
"s": 4159,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4352,
"s": 4240,
"text": "i is 6 and count is 4\ni is 7 and count is 3\ni is 8 and count is 2\ni is 9 and count is 1\ni is 10 and count is 0\n"
},
{
"code": null,
"e": 4619,
"s": 4352,
"text": "The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined."
},
{
"code": null,
"e": 4931,
"s": 4619,
"text": "When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file."
},
{
"code": null,
"e": 5073,
"s": 4931,
"text": "The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below."
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "First File: main.c"
},
{
"code": null,
"e": 5199,
"s": 5092,
"text": "#include <stdio.h>\n \nint count ;\nextern void write_extern();\n \nmain() {\n count = 5;\n write_extern();\n}"
},
{
"code": null,
"e": 5222,
"s": 5199,
"text": "Second File: support.c"
},
{
"code": null,
"e": 5326,
"s": 5222,
"text": "#include <stdio.h>\n \nextern int count;\n \nvoid write_extern(void) {\n printf(\"count is %d\\n\", count);\n}"
},
{
"code": null,
"e": 5490,
"s": 5326,
"text": "Here, extern is being used to declare count in the second file, where as it has its definition in the first file, main.c. Now, compile these two files as follows −"
},
{
"code": null,
"e": 5513,
"s": 5490,
"text": "$gcc main.c support.c\n"
},
{
"code": null,
"e": 5625,
"s": 5513,
"text": "It will produce the executable program a.out. When this program is executed, it produces the following result −"
},
{
"code": null,
"e": 5637,
"s": 5625,
"text": "count is 5\n"
},
{
"code": null,
"e": 5644,
"s": 5637,
"text": " Print"
},
{
"code": null,
"e": 5655,
"s": 5644,
"text": " Add Notes"
}
] |
How to append two DataFrames in Pandas?
|
To append the rows of one dataframe with the rows of another, we can use the Pandas append() function. With the help of append(), we can append columns too. Let's take an example and see how to use this method.
Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df1.
Print the input DataFrame, df1.
Create another DataFrame, df2, with the same column names and print it.
Use the append method, df1.append(df2, ignore_index=True), to append the rows of df2 with df2.
Print the resultatnt DataFrame.
import pandas as pd
df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"x": [1, 3], "y": [1, 9], "z": [29, 30]})
print "Input DataFrame 1 is:\n", df1
print "Input DataFrame 2 is:\n", df2
df3 = df1.append(df2, ignore_index=True)
print "After appending, DataFrame is: \n", df3
Input DataFrame 1 is:
x y z
0 5 4 9
1 2 7 3
Input DataFrame 2 is:
x y z
0 1 1 29
1 3 9 30
After appending, DataFrame is:
x y z
0 5 4 9
1 2 7 3
2 1 1 29
3 3 9 30
Now, let's use different column names for the dataframes and use the append() function without ignore_index parameter. The default value of ignore_index is False.
import pandas as pd
df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"a": [1, 3], "b": [1, 9], "c": [29, 30]})
print "Input DataFrame 1 is:\n", df1
print "Input DataFrame 2 is:\n", df2
df3 = df1.append(df2)
print "After appending, DataFrame is: \n", df3
Now, it will produce the following output
Input DataFrame 1 is:
x y z
0 5 4 9
1 2 7 3
Input DataFrame 2 is:
a b c
0 1 1 29
1 3 9 30
After appending, DataFrame is:
x y z a b c
0 5.0 4.0 9.0 NaN NaN NaN
1 2.0 7.0 3.0 NaN NaN NaN
0 NaN NaN NaN 1.0 1.0 29.0
1 NaN NaN NaN 3.0 9.0 30.0
|
[
{
"code": null,
"e": 1273,
"s": 1062,
"text": "To append the rows of one dataframe with the rows of another, we can use the Pandas append() function. With the help of append(), we can append columns too. Let's take an example and see how to use this method."
},
{
"code": null,
"e": 1358,
"s": 1273,
"text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df1."
},
{
"code": null,
"e": 1390,
"s": 1358,
"text": "Print the input DataFrame, df1."
},
{
"code": null,
"e": 1462,
"s": 1390,
"text": "Create another DataFrame, df2, with the same column names and print it."
},
{
"code": null,
"e": 1557,
"s": 1462,
"text": "Use the append method, df1.append(df2, ignore_index=True), to append the rows of df2 with df2."
},
{
"code": null,
"e": 1589,
"s": 1557,
"text": "Print the resultatnt DataFrame."
},
{
"code": null,
"e": 1897,
"s": 1589,
"text": "import pandas as pd\n\ndf1 = pd.DataFrame({\"x\": [5, 2], \"y\": [4, 7], \"z\": [9, 3]})\ndf2 = pd.DataFrame({\"x\": [1, 3], \"y\": [1, 9], \"z\": [29, 30]})\n\nprint \"Input DataFrame 1 is:\\n\", df1\nprint \"Input DataFrame 2 is:\\n\", df2\n\ndf3 = df1.append(df2, ignore_index=True)\n\nprint \"After appending, DataFrame is: \\n\", df3"
},
{
"code": null,
"e": 2067,
"s": 1897,
"text": "Input DataFrame 1 is:\n x y z\n0 5 4 9\n1 2 7 3\n\nInput DataFrame 2 is:\n x y z\n0 1 1 29\n1 3 9 30\n\nAfter appending, DataFrame is:\n x y z\n0 5 4 9\n1 2 7 3\n2 1 1 29\n3 3 9 30"
},
{
"code": null,
"e": 2230,
"s": 2067,
"text": "Now, let's use different column names for the dataframes and use the append() function without ignore_index parameter. The default value of ignore_index is False."
},
{
"code": null,
"e": 2525,
"s": 2230,
"text": "import pandas as pd\n\ndf1 = pd.DataFrame({\"x\": [5, 2], \"y\": [4, 7], \"z\": [9, 3]})\ndf2 = pd.DataFrame({\"a\": [1, 3], \"b\": [1, 9], \"c\": [29, 30]})\n\n\nprint \"Input DataFrame 1 is:\\n\", df1 \nprint \"Input DataFrame 2 is:\\n\", df2 \n\n\ndf3 = df1.append(df2)\n\n\nprint \"After appending, DataFrame is: \\n\", df3 "
},
{
"code": null,
"e": 2567,
"s": 2525,
"text": "Now, it will produce the following output"
},
{
"code": null,
"e": 2851,
"s": 2567,
"text": "Input DataFrame 1 is:\n x y z\n0 5 4 9\n1 2 7 3\n\nInput DataFrame 2 is:\n a b c\n0 1 1 29\n1 3 9 30\n\nAfter appending, DataFrame is:\n x y z a b c\n0 5.0 4.0 9.0 NaN NaN NaN\n1 2.0 7.0 3.0 NaN NaN NaN\n0 NaN NaN NaN 1.0 1.0 29.0\n1 NaN NaN NaN 3.0 9.0 30.0"
}
] |
SQL Tryit Editor v1.6
|
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 86,
"s": 0,
"text": "INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)"
},
{
"code": null,
"e": 171,
"s": 86,
"text": "SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;"
},
{
"code": null,
"e": 173,
"s": 171,
"text": ""
},
{
"code": null,
"e": 236,
"s": 173,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 296,
"s": 236,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 364,
"s": 296,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 402,
"s": 364,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 487,
"s": 402,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 661,
"s": 487,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 712,
"s": 661,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 780,
"s": 712,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 951,
"s": 780,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 1051,
"s": 951,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1111,
"s": 1051,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
Forecasting with Machine Learning Models | by Federico Garza Ramírez | Towards Data Science
|
By Nixtla Team.
TL;DR: We introduce mlforecast, an open source framework from Nixtla that makes the use of machine learning models in time series forecasting tasks fast and easy. It allows you to focus on the model and features instead of implementation details. With mlforecast you can make experiments in an esasier way and it has a built-in backtesting functionality to help you find the best performing model.
You can use mlforecast in your own infrastructure or use our fully hosted solution. Just send us a mail to federico@nixtla.io for testing the private beta.
Although this example contains only a single time series it, the framework is able to handle hundreds of thousands of them and is very efficient both time and memory wise.
We at Nixtla, are trying to make time series forecasting more accessible to everyone. In this post, we’ll talk about using machine learning models in forecasting tasks. We’ll use an example to show what the main challenges are and then we’ll introduce mlforecast, a framework that facilitates using machine learning models in forecasting. mlforecast does feature engineering and takes care of the updates for you, the user only has to provide a regressor that follows the scikit-learn API (implements fit and predict) and specify the features that she wants to use. These features can be lags, lag-based transformations, and date features. (For further feature creation or an automated forecasting pipeline check nixtla.)
For many years classical methods like ARIMA and ETS dominated the forecasting field. One of the reasons was that most of the use cases involved forecasting low-frequency series with monthly, quarterly, or yearly granularity. Furthermore, there weren’t many time-series datasets, so fitting a single model to each one and getting forecasts from them was straightforward.
However, in recent years, the need to forecast bigger datasets higher frequencies has risen. Bigger and higher frequency time series impose a challenge for classical forecasting methods. Those methods aren’t meant to model many time series together, and their implementation is suboptimal and slow (you have to train many models) and besides, there could be some common or shared patterns between the series that could be learned by modeling them together.
To address this problem, there have been various efforts in proposing different methods that can train a single model on many time series. Some fascinating deep learning architectures have been designed that can accurately forecast many time series like ESRNN, DeepAR, NBEATS among others. (Check nixtlats and Replicating ESRNN results for our WIP.)
Traditional machine learning models like gradient boosted trees have been used as well and have shown that they can achieve very good performance as well. However, using these models with lag-based features isn’t very straightforward because you have to update your features in every timestep in order to compute the predictions. Additionally, depending on your forecasting horizon and the lags that you use, at some point you run out of real values of your series to update your features, so you have to do something to fill those gaps. One possible approach is to use your predictions as the values for the series and update your features using them. This is exactly what mlforecast does for you.
In the following section, we’ll show a very simple example with a single series to highlight the difficulties in using machine learning models in forecasting tasks. This will later motivate the use of mlforecast, a library that makes the whole process easier and faster.
Our data has daily seasonality and as you can see in the creation, it is basically just dayofweek + Uniform({-1, 0, 1}).
Let’s say we want forecasts for the next 14 days, the first step would be deciding which model and features to use, so we’ll create a validation set containing the last 14 days in our data.
As a starting point, we’ll try lag 7 and lag 14.
We can see the expected relationship between the lags and the target. For example, when lag-7 is 2, y can be either 0, 1, 2, 3 or 4. This is because every day of the week can have the values [day — 1, day, day + 1], so when we’re at the day of the week number 2, we can get values 1, 2 or 3. However the value 2 can come from day of the week 1, whose minimum is 0, and it can come from the day of week 3, whose maximum is 4.
Computing lag values leaves some rows with nulls.
We’ll drop these before training.
For simplicity sake, we’ll train a linear regression without intercept. Since the best model would be taking the average for each day of the week, we expect to get coefficients that are close to 0.5.
This model is taking 0.51 * lag_7 + 0.45 * lag_14.
Great. We have our trained model. How can we compute the forecast for the next 14 days? Machine learning models a feature matrix X and output the predicted values y. So we need to create the feature matrix X for the next 14 days and give it to our model.
If we want to get the lag-7 for the next day, following the training set, we can just get the value in the 7th position starting from the end. The lag-7 two days after the end of the training set would be the value in the 6th position starting from the end and so on. Similarly for the lag-14.
As you may have noticed we can only get 7 of the lag-7 values from our history and we can get all 14 values for the lag-14. With this information we can only forecast the next 7 days, so we’ll only take the first 7 values of the lag-14.
With these features, we can compute the forecasts for the next 7 days.
These values can be interpreted as the values of our series for the next 7 days following the last training date. In order to compute the forecasts following that date, we can use these values as if they were the values of our series and use them as lag-7 for the following periods.
In other words, we can fill the rest of our features matrix with these values and the real values of the lag-14.
As you can see we’re still using the real values of the lag-14 and we’ve plugged in our predictions as the values for the lag-7. We can now use these features to predict the remaining 7 days.
And now we have our forecasts for the next 14 days! This wasn’t that painful but it wasn’t pretty or easy either. And we just used lags which are the easiest feature we can have.
What if we had used lag-1? We would have needed to do this predict-update step 14 times!
And what if we had more elaborate features like the rolling mean over some lag? As you can imagine it can get quite messy and is very error prone.
With these problems in mind, we created mlforecast, which is a framework to help you forecast time series using machine learning models. It takes care of all these messy details for you. You just need to give it a model and define which features you want to use and let mlforecast do the rest.
mlforecast is available in PyPI (pip install mlforecast) as well as conda-forge (conda install -c conda-forge mlforecast).
The previously described problem can be solved using mlforecast with the following code.
First, we have to set up our data in the required format.
This is the required input format.
an index named unique_id that identifies each time serie. In this case we only have one but you can have as many as you want.
a ds column with the dates.
a y column with the values.
Now we’ll import the TimeSeries transformer, where we define the features that we want to use. We’ll also import the Forecast class, which will hold our transformer and model and will run the forecasting pipeline for us.
We initialize our transformer specifying the lags that we want to use.
As you can see this transformer will use lag-7 and lag-14 as features. Now we define our model.
We create a Forecast object with the model and the time series transformer and fit it to our data.
And now we just call predict with the forecast horizon that we want.
This was a lot easier and internally this did the same as we did before. Let's verify real quick.
Check that we got the same predictions:
Check that we got the same model:
Having this high-level abstraction allows us to focus on defining the best features and model instead of worrying about implementation details. For example, we can try out different lags very easily by writing a simple function that leverages mlforecast:
In the previous examples, we manually split our data. The Forecast object also has a backtest method that can do that for us.
We’ll first get all of our data into the required format.
Now we instantiate a Forecast object as we did previously and call the backtest method instead.
This returns a generator with the results for each window.
result2 here is the same as the evaluation we did manually.
We can define a validation scheme for different lags using several windows.
We can specify transformations on the lags as well as just lags. The window_ops library has some implementations of different window functions. You can also define your own transformations.
Let’s try a seasonal rolling mean, this takes the average over the last n seasons, in this case, it would be the average of the last n Mondays, Tuesdays, etc. Computing the updates for this feature would probably be a bit annoying, however, using this framework we can just pass it to lag_transforms. If the transformations take additional arguments (additional to the values of the series) we specify a tuple like (transform_function, arg1, arg2), which in this case are season_length and window_size.
help(seasonal_rolling_mean)Help on CPUDispatcher in module window_ops.rolling:seasonal_rolling_mean(input_array: numpy.ndarray, season_length: int, window_size: int, min_samples: Union[int, NoneType] = None) -> numpy.ndarray Compute the seasonal_rolling_mean over the last non-na window_size samples of the input array starting at min_samples.
lag_transforms takes a dictionary where the keys are the lags that we want to apply the transformations to and the values are the transformations themselves.
You can also specify date features to be computed, which are attributes of the ds column and are updated in each time step as well. In this example, the best model would be taking the average over each day of the week, which can be accomplished by doing one-hot encoding on the day of the week column and fitting a linear model.
mlforecast has more features like distributed training and a CLI. If you’re interested you can learn more in the following resources:
GitHub repo: https://github.com/Nixtla/mlforecast
Documentation: https://nixtla.github.io/mlforecast/
Example using mlforecast in the M5 competition: https://www.kaggle.com/lemuz90/m5-mlforecast
|
[
{
"code": null,
"e": 188,
"s": 172,
"text": "By Nixtla Team."
},
{
"code": null,
"e": 586,
"s": 188,
"text": "TL;DR: We introduce mlforecast, an open source framework from Nixtla that makes the use of machine learning models in time series forecasting tasks fast and easy. It allows you to focus on the model and features instead of implementation details. With mlforecast you can make experiments in an esasier way and it has a built-in backtesting functionality to help you find the best performing model."
},
{
"code": null,
"e": 742,
"s": 586,
"text": "You can use mlforecast in your own infrastructure or use our fully hosted solution. Just send us a mail to federico@nixtla.io for testing the private beta."
},
{
"code": null,
"e": 914,
"s": 742,
"text": "Although this example contains only a single time series it, the framework is able to handle hundreds of thousands of them and is very efficient both time and memory wise."
},
{
"code": null,
"e": 1636,
"s": 914,
"text": "We at Nixtla, are trying to make time series forecasting more accessible to everyone. In this post, we’ll talk about using machine learning models in forecasting tasks. We’ll use an example to show what the main challenges are and then we’ll introduce mlforecast, a framework that facilitates using machine learning models in forecasting. mlforecast does feature engineering and takes care of the updates for you, the user only has to provide a regressor that follows the scikit-learn API (implements fit and predict) and specify the features that she wants to use. These features can be lags, lag-based transformations, and date features. (For further feature creation or an automated forecasting pipeline check nixtla.)"
},
{
"code": null,
"e": 2006,
"s": 1636,
"text": "For many years classical methods like ARIMA and ETS dominated the forecasting field. One of the reasons was that most of the use cases involved forecasting low-frequency series with monthly, quarterly, or yearly granularity. Furthermore, there weren’t many time-series datasets, so fitting a single model to each one and getting forecasts from them was straightforward."
},
{
"code": null,
"e": 2463,
"s": 2006,
"text": "However, in recent years, the need to forecast bigger datasets higher frequencies has risen. Bigger and higher frequency time series impose a challenge for classical forecasting methods. Those methods aren’t meant to model many time series together, and their implementation is suboptimal and slow (you have to train many models) and besides, there could be some common or shared patterns between the series that could be learned by modeling them together."
},
{
"code": null,
"e": 2813,
"s": 2463,
"text": "To address this problem, there have been various efforts in proposing different methods that can train a single model on many time series. Some fascinating deep learning architectures have been designed that can accurately forecast many time series like ESRNN, DeepAR, NBEATS among others. (Check nixtlats and Replicating ESRNN results for our WIP.)"
},
{
"code": null,
"e": 3512,
"s": 2813,
"text": "Traditional machine learning models like gradient boosted trees have been used as well and have shown that they can achieve very good performance as well. However, using these models with lag-based features isn’t very straightforward because you have to update your features in every timestep in order to compute the predictions. Additionally, depending on your forecasting horizon and the lags that you use, at some point you run out of real values of your series to update your features, so you have to do something to fill those gaps. One possible approach is to use your predictions as the values for the series and update your features using them. This is exactly what mlforecast does for you."
},
{
"code": null,
"e": 3783,
"s": 3512,
"text": "In the following section, we’ll show a very simple example with a single series to highlight the difficulties in using machine learning models in forecasting tasks. This will later motivate the use of mlforecast, a library that makes the whole process easier and faster."
},
{
"code": null,
"e": 3904,
"s": 3783,
"text": "Our data has daily seasonality and as you can see in the creation, it is basically just dayofweek + Uniform({-1, 0, 1})."
},
{
"code": null,
"e": 4094,
"s": 3904,
"text": "Let’s say we want forecasts for the next 14 days, the first step would be deciding which model and features to use, so we’ll create a validation set containing the last 14 days in our data."
},
{
"code": null,
"e": 4143,
"s": 4094,
"text": "As a starting point, we’ll try lag 7 and lag 14."
},
{
"code": null,
"e": 4568,
"s": 4143,
"text": "We can see the expected relationship between the lags and the target. For example, when lag-7 is 2, y can be either 0, 1, 2, 3 or 4. This is because every day of the week can have the values [day — 1, day, day + 1], so when we’re at the day of the week number 2, we can get values 1, 2 or 3. However the value 2 can come from day of the week 1, whose minimum is 0, and it can come from the day of week 3, whose maximum is 4."
},
{
"code": null,
"e": 4618,
"s": 4568,
"text": "Computing lag values leaves some rows with nulls."
},
{
"code": null,
"e": 4652,
"s": 4618,
"text": "We’ll drop these before training."
},
{
"code": null,
"e": 4852,
"s": 4652,
"text": "For simplicity sake, we’ll train a linear regression without intercept. Since the best model would be taking the average for each day of the week, we expect to get coefficients that are close to 0.5."
},
{
"code": null,
"e": 4903,
"s": 4852,
"text": "This model is taking 0.51 * lag_7 + 0.45 * lag_14."
},
{
"code": null,
"e": 5158,
"s": 4903,
"text": "Great. We have our trained model. How can we compute the forecast for the next 14 days? Machine learning models a feature matrix X and output the predicted values y. So we need to create the feature matrix X for the next 14 days and give it to our model."
},
{
"code": null,
"e": 5452,
"s": 5158,
"text": "If we want to get the lag-7 for the next day, following the training set, we can just get the value in the 7th position starting from the end. The lag-7 two days after the end of the training set would be the value in the 6th position starting from the end and so on. Similarly for the lag-14."
},
{
"code": null,
"e": 5689,
"s": 5452,
"text": "As you may have noticed we can only get 7 of the lag-7 values from our history and we can get all 14 values for the lag-14. With this information we can only forecast the next 7 days, so we’ll only take the first 7 values of the lag-14."
},
{
"code": null,
"e": 5760,
"s": 5689,
"text": "With these features, we can compute the forecasts for the next 7 days."
},
{
"code": null,
"e": 6043,
"s": 5760,
"text": "These values can be interpreted as the values of our series for the next 7 days following the last training date. In order to compute the forecasts following that date, we can use these values as if they were the values of our series and use them as lag-7 for the following periods."
},
{
"code": null,
"e": 6156,
"s": 6043,
"text": "In other words, we can fill the rest of our features matrix with these values and the real values of the lag-14."
},
{
"code": null,
"e": 6348,
"s": 6156,
"text": "As you can see we’re still using the real values of the lag-14 and we’ve plugged in our predictions as the values for the lag-7. We can now use these features to predict the remaining 7 days."
},
{
"code": null,
"e": 6527,
"s": 6348,
"text": "And now we have our forecasts for the next 14 days! This wasn’t that painful but it wasn’t pretty or easy either. And we just used lags which are the easiest feature we can have."
},
{
"code": null,
"e": 6616,
"s": 6527,
"text": "What if we had used lag-1? We would have needed to do this predict-update step 14 times!"
},
{
"code": null,
"e": 6763,
"s": 6616,
"text": "And what if we had more elaborate features like the rolling mean over some lag? As you can imagine it can get quite messy and is very error prone."
},
{
"code": null,
"e": 7057,
"s": 6763,
"text": "With these problems in mind, we created mlforecast, which is a framework to help you forecast time series using machine learning models. It takes care of all these messy details for you. You just need to give it a model and define which features you want to use and let mlforecast do the rest."
},
{
"code": null,
"e": 7180,
"s": 7057,
"text": "mlforecast is available in PyPI (pip install mlforecast) as well as conda-forge (conda install -c conda-forge mlforecast)."
},
{
"code": null,
"e": 7269,
"s": 7180,
"text": "The previously described problem can be solved using mlforecast with the following code."
},
{
"code": null,
"e": 7327,
"s": 7269,
"text": "First, we have to set up our data in the required format."
},
{
"code": null,
"e": 7362,
"s": 7327,
"text": "This is the required input format."
},
{
"code": null,
"e": 7488,
"s": 7362,
"text": "an index named unique_id that identifies each time serie. In this case we only have one but you can have as many as you want."
},
{
"code": null,
"e": 7516,
"s": 7488,
"text": "a ds column with the dates."
},
{
"code": null,
"e": 7544,
"s": 7516,
"text": "a y column with the values."
},
{
"code": null,
"e": 7765,
"s": 7544,
"text": "Now we’ll import the TimeSeries transformer, where we define the features that we want to use. We’ll also import the Forecast class, which will hold our transformer and model and will run the forecasting pipeline for us."
},
{
"code": null,
"e": 7836,
"s": 7765,
"text": "We initialize our transformer specifying the lags that we want to use."
},
{
"code": null,
"e": 7932,
"s": 7836,
"text": "As you can see this transformer will use lag-7 and lag-14 as features. Now we define our model."
},
{
"code": null,
"e": 8031,
"s": 7932,
"text": "We create a Forecast object with the model and the time series transformer and fit it to our data."
},
{
"code": null,
"e": 8100,
"s": 8031,
"text": "And now we just call predict with the forecast horizon that we want."
},
{
"code": null,
"e": 8198,
"s": 8100,
"text": "This was a lot easier and internally this did the same as we did before. Let's verify real quick."
},
{
"code": null,
"e": 8238,
"s": 8198,
"text": "Check that we got the same predictions:"
},
{
"code": null,
"e": 8272,
"s": 8238,
"text": "Check that we got the same model:"
},
{
"code": null,
"e": 8527,
"s": 8272,
"text": "Having this high-level abstraction allows us to focus on defining the best features and model instead of worrying about implementation details. For example, we can try out different lags very easily by writing a simple function that leverages mlforecast:"
},
{
"code": null,
"e": 8653,
"s": 8527,
"text": "In the previous examples, we manually split our data. The Forecast object also has a backtest method that can do that for us."
},
{
"code": null,
"e": 8711,
"s": 8653,
"text": "We’ll first get all of our data into the required format."
},
{
"code": null,
"e": 8807,
"s": 8711,
"text": "Now we instantiate a Forecast object as we did previously and call the backtest method instead."
},
{
"code": null,
"e": 8866,
"s": 8807,
"text": "This returns a generator with the results for each window."
},
{
"code": null,
"e": 8926,
"s": 8866,
"text": "result2 here is the same as the evaluation we did manually."
},
{
"code": null,
"e": 9002,
"s": 8926,
"text": "We can define a validation scheme for different lags using several windows."
},
{
"code": null,
"e": 9192,
"s": 9002,
"text": "We can specify transformations on the lags as well as just lags. The window_ops library has some implementations of different window functions. You can also define your own transformations."
},
{
"code": null,
"e": 9695,
"s": 9192,
"text": "Let’s try a seasonal rolling mean, this takes the average over the last n seasons, in this case, it would be the average of the last n Mondays, Tuesdays, etc. Computing the updates for this feature would probably be a bit annoying, however, using this framework we can just pass it to lag_transforms. If the transformations take additional arguments (additional to the values of the series) we specify a tuple like (transform_function, arg1, arg2), which in this case are season_length and window_size."
},
{
"code": null,
"e": 10045,
"s": 9695,
"text": "help(seasonal_rolling_mean)Help on CPUDispatcher in module window_ops.rolling:seasonal_rolling_mean(input_array: numpy.ndarray, season_length: int, window_size: int, min_samples: Union[int, NoneType] = None) -> numpy.ndarray Compute the seasonal_rolling_mean over the last non-na window_size samples of the input array starting at min_samples."
},
{
"code": null,
"e": 10203,
"s": 10045,
"text": "lag_transforms takes a dictionary where the keys are the lags that we want to apply the transformations to and the values are the transformations themselves."
},
{
"code": null,
"e": 10532,
"s": 10203,
"text": "You can also specify date features to be computed, which are attributes of the ds column and are updated in each time step as well. In this example, the best model would be taking the average over each day of the week, which can be accomplished by doing one-hot encoding on the day of the week column and fitting a linear model."
},
{
"code": null,
"e": 10666,
"s": 10532,
"text": "mlforecast has more features like distributed training and a CLI. If you’re interested you can learn more in the following resources:"
},
{
"code": null,
"e": 10716,
"s": 10666,
"text": "GitHub repo: https://github.com/Nixtla/mlforecast"
},
{
"code": null,
"e": 10768,
"s": 10716,
"text": "Documentation: https://nixtla.github.io/mlforecast/"
}
] |
Downloading The Kinetics Dataset For Human Action Recognition in Deep Learning | by Mark Gituma | Towards Data Science
|
If you are interested in performing deep learning for human activity or action recognition, you are bound to come across the Kinetics dataset released by deep mind. There are 3 main versions of the dataset; Kinetics 400, Kinetics 600 and the Kinetics 700 version. Kinetics 700 is the latest version at the time of the writing of this blog.
The Kinetics 700 dataset is described on the deep mind website as:
A large-scale, high-quality dataset of URL links to approximately 650,000 video clips that covers 700 human action classes, including human-object interactions such as playing instruments, as well as human-human interactions such as shaking hands and hugging. Each action class has at least 600 video clips. Each clip is human annotated with a single action class and lasts around 10s.
The URL links in the above context means YouTube URL links, therefore, the videos are YouTube videos.
The dataset is becoming a standard for human activity recognition and is increasingly been used as a benchmark in several action recognition papers as well as a baseline for deep learning architectures designed to process video data. The main vision for the Kinetics dataset is that it become’s the ImageNet equivalent of video data.
This blog will go through the steps taken taken in downloading the videos from the annotations files as well as challenges faced and some strategies used to get around the challenges. It will highlight some basic statistics about the data which will hopefully help you make informed decisions if you choose to download it yourself. However, it won’t go into too much detail about the annotations dataset e.g. how it was collected, the distribution of the different classes etc. This information can be found by reading the following papers:
The Kinetics Human Action Video Dataset (https://arxiv.org/pdf/1705.06950.pdf)
A Short Note on the Kinetics-700 Human Action Dataset (https://arxiv.org/pdf/1907.06987.pdf)
A kinetics dataset explorer was created to make it easy to visualize the data. The explorer can be found on http://kinetics-explorer.com/
The biggest pain point when dealing with the Kinetics dataset as opposed to the ImageNet or COCO equivalents is that the actual videos are not available for download. In place, an annotations file is provided which contains a list of entries in json and csv format containing the YouTube URL links, action category and the start and end times of the action category within the video.
The implications are that you have to download the videos yourself and crop them at the correct temporal range. There are about 650,000 videos, therefore this is not an easy task due to the various challenges we will cover later.
The annotations file can be downloaded from the following link. Below is a screenshot of what you should see.
Kinetics 700 is the dataset of focus for this blog. Clicking the “Download dataset” link, downloads a 25 MB gzip file containing the annotation files. After extracting the contents of the gzip file, there are 3 folders which contain the train, val and test datasets in 2 file formats (csv and json). The structure of the csv file is:
label,youtube_id,time_start,time_end,splittestifying,---QUuC4vJs,84,94,validatewashing feet,--GkrdYZ9Tc,0,10,validateair drumming,--nQbRBEz2s,104,114,validate...
The items in the CSV file can be broken down as follows:
The label indicates what type of human activity is found within the video e.g. testifying, washing feet, air drumming etc.
The youtube_id is the unique video identifier YouTube uses for each video. The complete video can be downloaded by substituting the youtube_id into the following string https://www.youtube.com/watch?v={youtube_id} .
The time_start and time_end (in seconds) indicates the section within the video where the human activity indicated by the label is found. Using the first row of the csv sample with label testifying as an example, the video length is 95 seconds (can be verified from https://www.youtube.com/watch?v=---QUuC4vJs), the label of interest will therefore be between 84–94 seconds which forms the temporal range.
The split indicates whether it belongs to the training, validation or testing dataset.
The structure of the json file is as follows, which should be easy to follow from the csv context:
{ "---QUuC4vJs": { "annotations": { "label": "testifying", "segment": [ 84.0, 94.0 ] }, "duration": 10.0, "subset": "validate", "url": "https://www.youtube.com/watch?v=---QUuC4vJs" }, "--GkrdYZ9Tc": { "annotations": { "label": "washing feet", "segment": [ 0.0, 10.0 ] }, "duration": 10.0, "subset": "validate", "url": "https://www.youtube.com/watch?v=--GkrdYZ9Tc" },....}
The json files are much larger than the csv files, occupying 197.5 MB as opposed to 24.5 MB in memory, so might a bit faster to read data from csv as opposed to json. However, most open source software that are capable of downloading the kinetics dataset from the annotations file use the json format so might need to pre-process the csv data to the correct format. Personally I chose the JSON format due to the open source code base I ended up using.
The data download was primarily on a desktop computer running Ubuntu 18.04 with consistent internet connection at about 60 Mb/s download speed with 16 GB of memory. However, some of the downloading occurred over my MacBook Pro when I was not using it.
I did try to use AWS and Google Cloud however there were significant throttling issues from YouTube which will be addressed in the errors section.
The next thing to consider is the codebase to download the data. There are two main options:
Write the code base yourself.
Find an existing open source codebase and if necessary modify it as required.
The second option was chosen and the codebase selected was the showmax/kinetics-downloader and a fork of it was created in dancelogue/kinetics-datasets-downloader. The main requirements to use the codebase are python ≥ 3.4, ffmpeg and youtube-dl. Where youtube-dl is used to do the actual download while ffmpeg is used to crop the video at the required segment i.e. the time_start and time_end times.
How to use the codebase is covered in the README.md file therefore we will not delve into the code. It is worth noting though that it uses the python multiprocessing module which I found to be necessary when downloading such a large dataset, and we will cover why in this blog.
Some modifications were made based on issues encountered when downloading the dataset. The modifications to the codebase includes:
Ability to write to a stats.csv file to track how long each download took as well as the duration of the ffmpeg cropping time for each video. Unfortunately, the intuition to create this functionality only occurred after half the dataset was downloaded. So the stats data does not cover the whole sample, but it should be sufficient enough to gain insight into the download process.
Ability to write to a failed.csv file to indicate which video had errors and what were the errors returned.
Ability to pause the download process once throttling occurred.
The stats and failed logs were used to generate basic stats about the data and will hopefully help you make informed decisions if you choose to download the data yourself.
YouTube is a dynamic platform which means videos are added and removed all the time. Therefore downloading the Kinetics dataset at different times will not have consistent results due due to videos being taken down. The following pie chart shows the downloaded and missing videos in my kinetics dataset.
The total downloaded video count is 631604 while the failed videos is 15380, which means 2.37 % of the entire dataset could not be downloaded out of a total of 646984 videos. It is assumed this is within acceptable error margins.
The following pie chart shows the split of the downloaded videos between the training, testing and validation set.
As expected, majority of the videos consists of training set data, which makes up 83.94 % of the dataset. The test set makes up 10.13 % of the dataset while the validation set makes up 5.93 % of the dataset.
In order to figure out how long it would take to download the entire dataset, the download time and the time it took to generate crop the videos (FFMPEG duration)was logged in seconds. As mentioned the stats for only 298651 videos were logged. The table below shows the mean and max of the individual processes.
Full indicates the entire dataset while IQR indicates the data within the interquartile range. Getting the interquartile data was necessary to prevent extreme outliers as shown by the high max value for the download duration and the FFMPEG duration. The theoretical time to download 646984 videos sequentially was:
Using the Full mean the anticipated download time is 176.1 days.
With the IQR mean the anticipated download time is 80.7 days.
This assumes the videos are downloaded synchronously without any interruptions. Luckily we have multiprocessing in our favour. I was running 16 separate processes using the python multiprocessing module.
The pie chart below indicates the dominant process between download dominant and ffmpeg (cropping) dominant tasks.
It can be seen that for most of the download process, the actual download process dominates, while the ffmpeg process dominates only 1.67 % of the time. Thus the main bottleneck in the entire process is actually downloading the videos from YouTube.
One of the first mistakes I made when downloading the kinetics dataset was downloading videos at a higher quality than necessary (this could indicate why there were quite extreme outliers).
Eventually I settled on videos with a max resolution of 360p, after all, these videos are meant to be consumed by machines and not people. Videos at this quality contain enough information to train the relevant deep learning algorithms, and are significantly faster to download and crop and take less space on disk during storage. It can be argued that a lower resolution could be tried as well i.e. 240p or 144p which will lead to significant space and time savings during download while maintaining the same baseline/benchmark accuracies.
A quick calculation was conducted to figure out the space requirements and it was found that the entire cropped dataset occupied 628.43 GB on disk. In order to download the dataset you probably need about 20 GB extra (depending on number of concurrent downloads occurring) to account for the full un cropped videos which needs to be stored temporarily.
The reasons 2.37 % of the videos failed to download were recorded and are shown in the following pie chart. The number next to the description in the legend was the total instances where the particular error occurred.
Majority of the errors are based on YouTube’s error messages and the description is an indicator of a group of errors. These are:
Video Not Available (10606) errors were by far the largest cause for failures and contained a variety of reasons such as the uploader deleting their YouTube account or having their accounts deleted by YouTube, videos only being available in certain countries, videos being made private etc.
Content warning (2451) errors were probably due to age restricted content and is assumed an authenticated account was required where the account holder is assumed to be over 18 years of age.
HTTP Error 404 (943) errors could potentially be due to the Kinetics video youtube_id being wrong as 404 generally indicates a page not found error code. I didn’t have time to investigate this hypothesis though.
Copyright (672) errors are videos removed due to copyright claims.
Video Removed By User (337) errors as the name states, the user deleted the videos.
Miscellaneous (144) errors were probably due to errors to do with the library being used or the error reason could not be identified.
Violating YouTube Terms (134) errors was usually videos taken down for violating community guidelines on spam, racism, bullying, nudity etc.
Duplicate Video (2) errors seems to indicate YouTube doesn’t allow for duplicate videos.
HTTP Error 503 (1) error occurred only once and relates to a service not found error, not sure why this was the case.
Even though there were issues downloading the video, the failed videos formed only 2.37 % of the entire dataset which can be considered within acceptable error margins. However, it is worth noting though as time progresses the fraction of failed videos will increase as more videos get taken down over time.
Even though these were the errors that prevented the videos from being downloaded, there was one error which proved to be the most frustrating experience in downloading the YouTube videos, the dreaded 429 too many requests error.
It is by far is the biggest pain point of downloading the kinetics dataset and this is what it made me feel like for the duration of the download process.
The primary reason for this error is caused by YouTube throttling requests which I assume is done by blacklisting the requesting ip address. It makes sense for YouTube to throttle requests where some of the reasons includes reducing the load to the server, preventing malicious parties from having access to the data etc. But it is a pain when downloading 650 000 video clips.
What makes it especially challenging is the time it took for the requesting ip addresses to be allowed again i.e. the “cooling off” period. From experience it took anywhere from 12 hours to 5 days. I wasn’t able to find a discernible pattern to get around it. The most amount of videos I was able to download in a single session before been throttled was 136963, the pie chart below shows the distributions between the runs (some of the runs were terminated manually as opposed to throttling).
The throttling issues has been highlighted in different sources as a major hindrance when downloading data from YouTube.
https://github.com/activitynet/ActivityNet/issues/51
https://github.com/activitynet/ActivityNet/issues/28
https://stackoverflow.com/questions/57488759/npmyoutube-dl-and-lamda-http-error-429-too-many-requests
https://github.com/ytdl-org/youtube-dl/issues/21729
As far as I could tell the criteria by which an ip address is blacklisted is not clear. On my home desktop I could download over 50 000 videos before hitting the 429 error code, however moving to AWS or Google cloud I could maybe manage a 100 downloads before hitting the 429 error. Perhaps there is some criteria YouTube uses to immediately blacklist ip addresses from cloud VM vs personal machines.
When the HTTP Error 429 was encountered it’s best to stop the download and either try again at a later time or change IP addresses.
The main viable option I was able to come up with was to change IP addresses by switching networks. Having 2 different OS (e.g. Windows and Ubuntu) on the same machine worked for sometime. If all else fails., wait for the cool off period.
As downloading the dataset was not a huge priority at the time, when all the networking workaround options were encountering the HTTP Error 429 status, download of the dataset stopped and was attempted a few days later. I didn’t explore other options such as using a VPN etc.
One major topic that hasn’t been covered so far is ethics i.e. scraping YouTube videos. On one hand the annotations file for the videos exist and was provided by Deepmind which is a subsidiary of Google, on the other hand, what are the rules in downloading the dataset especially for deep learning research. There are quite a few papers out there which make use of the data which shows that people are downloading it. It kind of feels like the head in the sand scenario is happening.
This could possibly be the reason as to why the data has not been made publicly available, as such, anyone interested in deep learning must download it themselves. There are several issues with this approach which I believe are:
Firstly it hinders deep learning research with video data as the kinetics dataset is not a trivial dataset to download.
The datasets between 2 different researchers might be different due to missing videos which means results reported in research papers might not be exactly reproducible.
Not sure what the workaround concerning the ethical situation can be in making the data public but hopefully Deepmind will make the video data easily accessible for non commercial use.
Hopefully this blog has given you some insights when it comes to downloading the Kinetics dataset and the challenges faced should you attempt it yourself.
The Kinetics dataset was necessary as I undertook a personal project for the whole of 2019 on building a Shazam for dance deep learning start-up. The Kinetics data was used to pre-train the dance algorithms as a proof of concept. I will soon be blogging about this process.
If you have any questions or anything needs clarification, you can book a time with me on https://mbele.io/mark
|
[
{
"code": null,
"e": 512,
"s": 172,
"text": "If you are interested in performing deep learning for human activity or action recognition, you are bound to come across the Kinetics dataset released by deep mind. There are 3 main versions of the dataset; Kinetics 400, Kinetics 600 and the Kinetics 700 version. Kinetics 700 is the latest version at the time of the writing of this blog."
},
{
"code": null,
"e": 579,
"s": 512,
"text": "The Kinetics 700 dataset is described on the deep mind website as:"
},
{
"code": null,
"e": 965,
"s": 579,
"text": "A large-scale, high-quality dataset of URL links to approximately 650,000 video clips that covers 700 human action classes, including human-object interactions such as playing instruments, as well as human-human interactions such as shaking hands and hugging. Each action class has at least 600 video clips. Each clip is human annotated with a single action class and lasts around 10s."
},
{
"code": null,
"e": 1067,
"s": 965,
"text": "The URL links in the above context means YouTube URL links, therefore, the videos are YouTube videos."
},
{
"code": null,
"e": 1401,
"s": 1067,
"text": "The dataset is becoming a standard for human activity recognition and is increasingly been used as a benchmark in several action recognition papers as well as a baseline for deep learning architectures designed to process video data. The main vision for the Kinetics dataset is that it become’s the ImageNet equivalent of video data."
},
{
"code": null,
"e": 1942,
"s": 1401,
"text": "This blog will go through the steps taken taken in downloading the videos from the annotations files as well as challenges faced and some strategies used to get around the challenges. It will highlight some basic statistics about the data which will hopefully help you make informed decisions if you choose to download it yourself. However, it won’t go into too much detail about the annotations dataset e.g. how it was collected, the distribution of the different classes etc. This information can be found by reading the following papers:"
},
{
"code": null,
"e": 2021,
"s": 1942,
"text": "The Kinetics Human Action Video Dataset (https://arxiv.org/pdf/1705.06950.pdf)"
},
{
"code": null,
"e": 2114,
"s": 2021,
"text": "A Short Note on the Kinetics-700 Human Action Dataset (https://arxiv.org/pdf/1907.06987.pdf)"
},
{
"code": null,
"e": 2252,
"s": 2114,
"text": "A kinetics dataset explorer was created to make it easy to visualize the data. The explorer can be found on http://kinetics-explorer.com/"
},
{
"code": null,
"e": 2636,
"s": 2252,
"text": "The biggest pain point when dealing with the Kinetics dataset as opposed to the ImageNet or COCO equivalents is that the actual videos are not available for download. In place, an annotations file is provided which contains a list of entries in json and csv format containing the YouTube URL links, action category and the start and end times of the action category within the video."
},
{
"code": null,
"e": 2866,
"s": 2636,
"text": "The implications are that you have to download the videos yourself and crop them at the correct temporal range. There are about 650,000 videos, therefore this is not an easy task due to the various challenges we will cover later."
},
{
"code": null,
"e": 2976,
"s": 2866,
"text": "The annotations file can be downloaded from the following link. Below is a screenshot of what you should see."
},
{
"code": null,
"e": 3310,
"s": 2976,
"text": "Kinetics 700 is the dataset of focus for this blog. Clicking the “Download dataset” link, downloads a 25 MB gzip file containing the annotation files. After extracting the contents of the gzip file, there are 3 folders which contain the train, val and test datasets in 2 file formats (csv and json). The structure of the csv file is:"
},
{
"code": null,
"e": 3472,
"s": 3310,
"text": "label,youtube_id,time_start,time_end,splittestifying,---QUuC4vJs,84,94,validatewashing feet,--GkrdYZ9Tc,0,10,validateair drumming,--nQbRBEz2s,104,114,validate..."
},
{
"code": null,
"e": 3529,
"s": 3472,
"text": "The items in the CSV file can be broken down as follows:"
},
{
"code": null,
"e": 3652,
"s": 3529,
"text": "The label indicates what type of human activity is found within the video e.g. testifying, washing feet, air drumming etc."
},
{
"code": null,
"e": 3868,
"s": 3652,
"text": "The youtube_id is the unique video identifier YouTube uses for each video. The complete video can be downloaded by substituting the youtube_id into the following string https://www.youtube.com/watch?v={youtube_id} ."
},
{
"code": null,
"e": 4274,
"s": 3868,
"text": "The time_start and time_end (in seconds) indicates the section within the video where the human activity indicated by the label is found. Using the first row of the csv sample with label testifying as an example, the video length is 95 seconds (can be verified from https://www.youtube.com/watch?v=---QUuC4vJs), the label of interest will therefore be between 84–94 seconds which forms the temporal range."
},
{
"code": null,
"e": 4361,
"s": 4274,
"text": "The split indicates whether it belongs to the training, validation or testing dataset."
},
{
"code": null,
"e": 4460,
"s": 4361,
"text": "The structure of the json file is as follows, which should be easy to follow from the csv context:"
},
{
"code": null,
"e": 4866,
"s": 4460,
"text": "{ \"---QUuC4vJs\": { \"annotations\": { \"label\": \"testifying\", \"segment\": [ 84.0, 94.0 ] }, \"duration\": 10.0, \"subset\": \"validate\", \"url\": \"https://www.youtube.com/watch?v=---QUuC4vJs\" }, \"--GkrdYZ9Tc\": { \"annotations\": { \"label\": \"washing feet\", \"segment\": [ 0.0, 10.0 ] }, \"duration\": 10.0, \"subset\": \"validate\", \"url\": \"https://www.youtube.com/watch?v=--GkrdYZ9Tc\" },....}"
},
{
"code": null,
"e": 5318,
"s": 4866,
"text": "The json files are much larger than the csv files, occupying 197.5 MB as opposed to 24.5 MB in memory, so might a bit faster to read data from csv as opposed to json. However, most open source software that are capable of downloading the kinetics dataset from the annotations file use the json format so might need to pre-process the csv data to the correct format. Personally I chose the JSON format due to the open source code base I ended up using."
},
{
"code": null,
"e": 5570,
"s": 5318,
"text": "The data download was primarily on a desktop computer running Ubuntu 18.04 with consistent internet connection at about 60 Mb/s download speed with 16 GB of memory. However, some of the downloading occurred over my MacBook Pro when I was not using it."
},
{
"code": null,
"e": 5717,
"s": 5570,
"text": "I did try to use AWS and Google Cloud however there were significant throttling issues from YouTube which will be addressed in the errors section."
},
{
"code": null,
"e": 5810,
"s": 5717,
"text": "The next thing to consider is the codebase to download the data. There are two main options:"
},
{
"code": null,
"e": 5840,
"s": 5810,
"text": "Write the code base yourself."
},
{
"code": null,
"e": 5918,
"s": 5840,
"text": "Find an existing open source codebase and if necessary modify it as required."
},
{
"code": null,
"e": 6319,
"s": 5918,
"text": "The second option was chosen and the codebase selected was the showmax/kinetics-downloader and a fork of it was created in dancelogue/kinetics-datasets-downloader. The main requirements to use the codebase are python ≥ 3.4, ffmpeg and youtube-dl. Where youtube-dl is used to do the actual download while ffmpeg is used to crop the video at the required segment i.e. the time_start and time_end times."
},
{
"code": null,
"e": 6597,
"s": 6319,
"text": "How to use the codebase is covered in the README.md file therefore we will not delve into the code. It is worth noting though that it uses the python multiprocessing module which I found to be necessary when downloading such a large dataset, and we will cover why in this blog."
},
{
"code": null,
"e": 6728,
"s": 6597,
"text": "Some modifications were made based on issues encountered when downloading the dataset. The modifications to the codebase includes:"
},
{
"code": null,
"e": 7110,
"s": 6728,
"text": "Ability to write to a stats.csv file to track how long each download took as well as the duration of the ffmpeg cropping time for each video. Unfortunately, the intuition to create this functionality only occurred after half the dataset was downloaded. So the stats data does not cover the whole sample, but it should be sufficient enough to gain insight into the download process."
},
{
"code": null,
"e": 7218,
"s": 7110,
"text": "Ability to write to a failed.csv file to indicate which video had errors and what were the errors returned."
},
{
"code": null,
"e": 7282,
"s": 7218,
"text": "Ability to pause the download process once throttling occurred."
},
{
"code": null,
"e": 7454,
"s": 7282,
"text": "The stats and failed logs were used to generate basic stats about the data and will hopefully help you make informed decisions if you choose to download the data yourself."
},
{
"code": null,
"e": 7758,
"s": 7454,
"text": "YouTube is a dynamic platform which means videos are added and removed all the time. Therefore downloading the Kinetics dataset at different times will not have consistent results due due to videos being taken down. The following pie chart shows the downloaded and missing videos in my kinetics dataset."
},
{
"code": null,
"e": 7988,
"s": 7758,
"text": "The total downloaded video count is 631604 while the failed videos is 15380, which means 2.37 % of the entire dataset could not be downloaded out of a total of 646984 videos. It is assumed this is within acceptable error margins."
},
{
"code": null,
"e": 8103,
"s": 7988,
"text": "The following pie chart shows the split of the downloaded videos between the training, testing and validation set."
},
{
"code": null,
"e": 8311,
"s": 8103,
"text": "As expected, majority of the videos consists of training set data, which makes up 83.94 % of the dataset. The test set makes up 10.13 % of the dataset while the validation set makes up 5.93 % of the dataset."
},
{
"code": null,
"e": 8623,
"s": 8311,
"text": "In order to figure out how long it would take to download the entire dataset, the download time and the time it took to generate crop the videos (FFMPEG duration)was logged in seconds. As mentioned the stats for only 298651 videos were logged. The table below shows the mean and max of the individual processes."
},
{
"code": null,
"e": 8938,
"s": 8623,
"text": "Full indicates the entire dataset while IQR indicates the data within the interquartile range. Getting the interquartile data was necessary to prevent extreme outliers as shown by the high max value for the download duration and the FFMPEG duration. The theoretical time to download 646984 videos sequentially was:"
},
{
"code": null,
"e": 9003,
"s": 8938,
"text": "Using the Full mean the anticipated download time is 176.1 days."
},
{
"code": null,
"e": 9065,
"s": 9003,
"text": "With the IQR mean the anticipated download time is 80.7 days."
},
{
"code": null,
"e": 9269,
"s": 9065,
"text": "This assumes the videos are downloaded synchronously without any interruptions. Luckily we have multiprocessing in our favour. I was running 16 separate processes using the python multiprocessing module."
},
{
"code": null,
"e": 9384,
"s": 9269,
"text": "The pie chart below indicates the dominant process between download dominant and ffmpeg (cropping) dominant tasks."
},
{
"code": null,
"e": 9633,
"s": 9384,
"text": "It can be seen that for most of the download process, the actual download process dominates, while the ffmpeg process dominates only 1.67 % of the time. Thus the main bottleneck in the entire process is actually downloading the videos from YouTube."
},
{
"code": null,
"e": 9823,
"s": 9633,
"text": "One of the first mistakes I made when downloading the kinetics dataset was downloading videos at a higher quality than necessary (this could indicate why there were quite extreme outliers)."
},
{
"code": null,
"e": 10364,
"s": 9823,
"text": "Eventually I settled on videos with a max resolution of 360p, after all, these videos are meant to be consumed by machines and not people. Videos at this quality contain enough information to train the relevant deep learning algorithms, and are significantly faster to download and crop and take less space on disk during storage. It can be argued that a lower resolution could be tried as well i.e. 240p or 144p which will lead to significant space and time savings during download while maintaining the same baseline/benchmark accuracies."
},
{
"code": null,
"e": 10717,
"s": 10364,
"text": "A quick calculation was conducted to figure out the space requirements and it was found that the entire cropped dataset occupied 628.43 GB on disk. In order to download the dataset you probably need about 20 GB extra (depending on number of concurrent downloads occurring) to account for the full un cropped videos which needs to be stored temporarily."
},
{
"code": null,
"e": 10935,
"s": 10717,
"text": "The reasons 2.37 % of the videos failed to download were recorded and are shown in the following pie chart. The number next to the description in the legend was the total instances where the particular error occurred."
},
{
"code": null,
"e": 11065,
"s": 10935,
"text": "Majority of the errors are based on YouTube’s error messages and the description is an indicator of a group of errors. These are:"
},
{
"code": null,
"e": 11356,
"s": 11065,
"text": "Video Not Available (10606) errors were by far the largest cause for failures and contained a variety of reasons such as the uploader deleting their YouTube account or having their accounts deleted by YouTube, videos only being available in certain countries, videos being made private etc."
},
{
"code": null,
"e": 11547,
"s": 11356,
"text": "Content warning (2451) errors were probably due to age restricted content and is assumed an authenticated account was required where the account holder is assumed to be over 18 years of age."
},
{
"code": null,
"e": 11759,
"s": 11547,
"text": "HTTP Error 404 (943) errors could potentially be due to the Kinetics video youtube_id being wrong as 404 generally indicates a page not found error code. I didn’t have time to investigate this hypothesis though."
},
{
"code": null,
"e": 11826,
"s": 11759,
"text": "Copyright (672) errors are videos removed due to copyright claims."
},
{
"code": null,
"e": 11910,
"s": 11826,
"text": "Video Removed By User (337) errors as the name states, the user deleted the videos."
},
{
"code": null,
"e": 12044,
"s": 11910,
"text": "Miscellaneous (144) errors were probably due to errors to do with the library being used or the error reason could not be identified."
},
{
"code": null,
"e": 12185,
"s": 12044,
"text": "Violating YouTube Terms (134) errors was usually videos taken down for violating community guidelines on spam, racism, bullying, nudity etc."
},
{
"code": null,
"e": 12274,
"s": 12185,
"text": "Duplicate Video (2) errors seems to indicate YouTube doesn’t allow for duplicate videos."
},
{
"code": null,
"e": 12392,
"s": 12274,
"text": "HTTP Error 503 (1) error occurred only once and relates to a service not found error, not sure why this was the case."
},
{
"code": null,
"e": 12700,
"s": 12392,
"text": "Even though there were issues downloading the video, the failed videos formed only 2.37 % of the entire dataset which can be considered within acceptable error margins. However, it is worth noting though as time progresses the fraction of failed videos will increase as more videos get taken down over time."
},
{
"code": null,
"e": 12930,
"s": 12700,
"text": "Even though these were the errors that prevented the videos from being downloaded, there was one error which proved to be the most frustrating experience in downloading the YouTube videos, the dreaded 429 too many requests error."
},
{
"code": null,
"e": 13085,
"s": 12930,
"text": "It is by far is the biggest pain point of downloading the kinetics dataset and this is what it made me feel like for the duration of the download process."
},
{
"code": null,
"e": 13462,
"s": 13085,
"text": "The primary reason for this error is caused by YouTube throttling requests which I assume is done by blacklisting the requesting ip address. It makes sense for YouTube to throttle requests where some of the reasons includes reducing the load to the server, preventing malicious parties from having access to the data etc. But it is a pain when downloading 650 000 video clips."
},
{
"code": null,
"e": 13956,
"s": 13462,
"text": "What makes it especially challenging is the time it took for the requesting ip addresses to be allowed again i.e. the “cooling off” period. From experience it took anywhere from 12 hours to 5 days. I wasn’t able to find a discernible pattern to get around it. The most amount of videos I was able to download in a single session before been throttled was 136963, the pie chart below shows the distributions between the runs (some of the runs were terminated manually as opposed to throttling)."
},
{
"code": null,
"e": 14077,
"s": 13956,
"text": "The throttling issues has been highlighted in different sources as a major hindrance when downloading data from YouTube."
},
{
"code": null,
"e": 14130,
"s": 14077,
"text": "https://github.com/activitynet/ActivityNet/issues/51"
},
{
"code": null,
"e": 14183,
"s": 14130,
"text": "https://github.com/activitynet/ActivityNet/issues/28"
},
{
"code": null,
"e": 14285,
"s": 14183,
"text": "https://stackoverflow.com/questions/57488759/npmyoutube-dl-and-lamda-http-error-429-too-many-requests"
},
{
"code": null,
"e": 14337,
"s": 14285,
"text": "https://github.com/ytdl-org/youtube-dl/issues/21729"
},
{
"code": null,
"e": 14738,
"s": 14337,
"text": "As far as I could tell the criteria by which an ip address is blacklisted is not clear. On my home desktop I could download over 50 000 videos before hitting the 429 error code, however moving to AWS or Google cloud I could maybe manage a 100 downloads before hitting the 429 error. Perhaps there is some criteria YouTube uses to immediately blacklist ip addresses from cloud VM vs personal machines."
},
{
"code": null,
"e": 14870,
"s": 14738,
"text": "When the HTTP Error 429 was encountered it’s best to stop the download and either try again at a later time or change IP addresses."
},
{
"code": null,
"e": 15109,
"s": 14870,
"text": "The main viable option I was able to come up with was to change IP addresses by switching networks. Having 2 different OS (e.g. Windows and Ubuntu) on the same machine worked for sometime. If all else fails., wait for the cool off period."
},
{
"code": null,
"e": 15385,
"s": 15109,
"text": "As downloading the dataset was not a huge priority at the time, when all the networking workaround options were encountering the HTTP Error 429 status, download of the dataset stopped and was attempted a few days later. I didn’t explore other options such as using a VPN etc."
},
{
"code": null,
"e": 15869,
"s": 15385,
"text": "One major topic that hasn’t been covered so far is ethics i.e. scraping YouTube videos. On one hand the annotations file for the videos exist and was provided by Deepmind which is a subsidiary of Google, on the other hand, what are the rules in downloading the dataset especially for deep learning research. There are quite a few papers out there which make use of the data which shows that people are downloading it. It kind of feels like the head in the sand scenario is happening."
},
{
"code": null,
"e": 16098,
"s": 15869,
"text": "This could possibly be the reason as to why the data has not been made publicly available, as such, anyone interested in deep learning must download it themselves. There are several issues with this approach which I believe are:"
},
{
"code": null,
"e": 16218,
"s": 16098,
"text": "Firstly it hinders deep learning research with video data as the kinetics dataset is not a trivial dataset to download."
},
{
"code": null,
"e": 16387,
"s": 16218,
"text": "The datasets between 2 different researchers might be different due to missing videos which means results reported in research papers might not be exactly reproducible."
},
{
"code": null,
"e": 16572,
"s": 16387,
"text": "Not sure what the workaround concerning the ethical situation can be in making the data public but hopefully Deepmind will make the video data easily accessible for non commercial use."
},
{
"code": null,
"e": 16727,
"s": 16572,
"text": "Hopefully this blog has given you some insights when it comes to downloading the Kinetics dataset and the challenges faced should you attempt it yourself."
},
{
"code": null,
"e": 17001,
"s": 16727,
"text": "The Kinetics dataset was necessary as I undertook a personal project for the whole of 2019 on building a Shazam for dance deep learning start-up. The Kinetics data was used to pre-train the dance algorithms as a proof of concept. I will soon be blogging about this process."
}
] |
A subtle guide to get that college internship - GeeksforGeeks
|
25 Oct, 2018
Wisdoms for CS/IT/ECE/EE guys of 1st, 2nd or 3rd year.
You might wonder what does an amateur has to say for a topic that is mostly taken up by much experienced counsellors and teachers.Well, that may be true but I believe, the best solution to any problem is available with only one who has invested good time solving it and since I did, I promise you, you won’t be disappointed
Please note that I focus on companies that provide On Campus interviews for internships, in Indian colleges. Also, as these are just experience based ideas, you are free to take any other path that you find better, but be generous enough to write them down in comments.
You must have heard this famous quote of Thomas Alva Edison–
Genius is 99% perspiration and 1% inspiration
Taking very broad references from the quote above, I will be discussing our problem in parts. Firstly the perspiration part and then the inspiration part because you know, 99% matters
The perspiration
Let me get it straight to you. You need to work hard, very hard. Right from the first year in your college. I believe, since you have taken CS/IT/ECE/EE as one of your engineering branches, you already know that Coding is the key.
But what does it really mean??
Coding as what this is referred to is the first thing an CS/IT guy gets curious about. Indeed he must be. But let me tell you the real essence in those words. Coding is not the key, the key here is Problem Solving.
It is problem solving, a setting of your mind that helps you to get easy answers to any problem that you face in your day to day life, within time.You might not notice, but the way you carry out your task mostly determines that whether you will be able to complete it or not.
Problem Solving will help you when you in myriad ways when you are trying to solve a coding problem. The major benefit of problem solving attitude is that it helps us to develop a series of thoughts, a series of very well structured thoughts, that ultimately leads to the solution. A bridge that connects thought by thought to the destination where you feel that ‘ I have got this problem’ and Yeah! you know it.
Now you might already know the ways to help you with this, but still for the real lucky beginners, let me make this very verbose.
Start by solving puzzles. The same puzzles at which we used to get startled in our childhood. Find some good puzzles like the knight’s tour problem, the travelling salesman problem, the pirate and coins problem. Explore GeeksforGeeks. Please mind that you need to focus on the details of the problem and how beautifully it gets solved. It can happen when you have seen the solution, or in the best case, found one.
Moving on, start your practice on the online judges like hackerrank and hackerearth. These websites have programmes like 30 days of code and the Code monk respectively that will help you get started slowly but steadily, and trust me being steady is IMPORTANT!
Then after some weeks of good practice and a feel Good feeling, take part in the online competitions that are regularly conducted by these websites. These competitions help you to cope up with pressure conditions that might arise in your one to one interview round or even at the aptitude and coding tests, taken mostly as the first round by 99% of the companies.
Also GeeksForGeeks provide you with programmes like Sudo Placement and Sudo Placement 2 that are completely free to join and essentially enables you to get the mindset right for the Coding and Aptitude test. The questions asked in these tests are similar to those that are asked by maximum companies out there.
Remember, Patience and hard work, will pay off.
Now, since we have moved past the competitive coding part, i would like to take up the development part. This mainly comprises of the projects in which you might have contributed and the applications that you might have developed.
I would recommend you to start a practice that i follow i.e Competitive Driven Development. Sounds similar to a development standard, but this is different.
CDD, enables you to write efficient codes. As you will learn more of data structures and develop your competitive skills, the problems that you face when developing an application will get more easily solved and the application will also be innately FAST!
If you wish you might review the thoughts above as for now we move on to the ‘inspiration’ part of the deed. Mind it, The Problem Solving attitude !
The inspiration part
Here too, i won’t be beating around the bush but be to the point. Instead i will take references from my mistakes and that of my friends, so that you are ready with the right outlook of personality, exactly needed.
The moment you get into a university, always look for like minded people. You are not searching for friends, instead you are searching for someone with whom you can talk about your ideas and someone who will be happy to listen to and if needed, correct them. Don’t make yourself alone, ever.The process takes time, but this only starts real ‘productive’ friendships in colleges.
Also, avoid distractions! You might have heard this many time. In fact we all get to listen this all through our childhood, don’t we? But, taking a bit mature perspective on this will make you realise that distractions are all those things in your life that pulls you down. Everything that gives you a feeling of remorse or sadness, not immediately but later, is a distraction. Do you know the cool fact about distractions? We tend to go after them just for the temporary happiness they provide, and this is all they can provide.
I repeat myself, Patience and hardwork, will pay off .
Be easy on yourself and lead a happy life. Think clear and positive. Be prepared for challenges. Don’t ever get overwhelmed by your own thoughts and talk them out to a friend. You must know, an idea can create everything but also can destroy the same.
I also write on medium so if you find my writing interesting, I would love if you follow me there.
Career-Advices
Interview Tips
placement preparation
Technical Scripter 2018
Articles
CS - Placements
Placements
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Const keyword in C++
Amazon’s most frequently asked interview questions | Set 2
Service-Oriented Architecture
Must Do Questions for Companies like TCS, CTS, HCL, IBM ...
Lamport's logical clock
Applications of linked list data structure
Most asked Computer Science Subjects Interview Questions in Amazon, Microsoft, Flipkart
TCS Interview Questions
Hotel Management System
Minimum Cost Maximum Flow from a Graph using Bellman Ford Algorithm
|
[
{
"code": null,
"e": 24902,
"s": 24874,
"text": "\n25 Oct, 2018"
},
{
"code": null,
"e": 24957,
"s": 24902,
"text": "Wisdoms for CS/IT/ECE/EE guys of 1st, 2nd or 3rd year."
},
{
"code": null,
"e": 25282,
"s": 24957,
"text": "You might wonder what does an amateur has to say for a topic that is mostly taken up by much experienced counsellors and teachers.Well, that may be true but I believe, the best solution to any problem is available with only one who has invested good time solving it and since I did, I promise you, you won’t be disappointed "
},
{
"code": null,
"e": 25552,
"s": 25282,
"text": "Please note that I focus on companies that provide On Campus interviews for internships, in Indian colleges. Also, as these are just experience based ideas, you are free to take any other path that you find better, but be generous enough to write them down in comments."
},
{
"code": null,
"e": 25613,
"s": 25552,
"text": "You must have heard this famous quote of Thomas Alva Edison–"
},
{
"code": null,
"e": 25659,
"s": 25613,
"text": "Genius is 99% perspiration and 1% inspiration"
},
{
"code": null,
"e": 25844,
"s": 25659,
"text": "Taking very broad references from the quote above, I will be discussing our problem in parts. Firstly the perspiration part and then the inspiration part because you know, 99% matters "
},
{
"code": null,
"e": 25861,
"s": 25844,
"text": "The perspiration"
},
{
"code": null,
"e": 26092,
"s": 25861,
"text": "Let me get it straight to you. You need to work hard, very hard. Right from the first year in your college. I believe, since you have taken CS/IT/ECE/EE as one of your engineering branches, you already know that Coding is the key."
},
{
"code": null,
"e": 26123,
"s": 26092,
"text": "But what does it really mean??"
},
{
"code": null,
"e": 26338,
"s": 26123,
"text": "Coding as what this is referred to is the first thing an CS/IT guy gets curious about. Indeed he must be. But let me tell you the real essence in those words. Coding is not the key, the key here is Problem Solving."
},
{
"code": null,
"e": 26614,
"s": 26338,
"text": "It is problem solving, a setting of your mind that helps you to get easy answers to any problem that you face in your day to day life, within time.You might not notice, but the way you carry out your task mostly determines that whether you will be able to complete it or not."
},
{
"code": null,
"e": 27027,
"s": 26614,
"text": "Problem Solving will help you when you in myriad ways when you are trying to solve a coding problem. The major benefit of problem solving attitude is that it helps us to develop a series of thoughts, a series of very well structured thoughts, that ultimately leads to the solution. A bridge that connects thought by thought to the destination where you feel that ‘ I have got this problem’ and Yeah! you know it."
},
{
"code": null,
"e": 27157,
"s": 27027,
"text": "Now you might already know the ways to help you with this, but still for the real lucky beginners, let me make this very verbose."
},
{
"code": null,
"e": 27572,
"s": 27157,
"text": "Start by solving puzzles. The same puzzles at which we used to get startled in our childhood. Find some good puzzles like the knight’s tour problem, the travelling salesman problem, the pirate and coins problem. Explore GeeksforGeeks. Please mind that you need to focus on the details of the problem and how beautifully it gets solved. It can happen when you have seen the solution, or in the best case, found one."
},
{
"code": null,
"e": 27832,
"s": 27572,
"text": "Moving on, start your practice on the online judges like hackerrank and hackerearth. These websites have programmes like 30 days of code and the Code monk respectively that will help you get started slowly but steadily, and trust me being steady is IMPORTANT!"
},
{
"code": null,
"e": 28196,
"s": 27832,
"text": "Then after some weeks of good practice and a feel Good feeling, take part in the online competitions that are regularly conducted by these websites. These competitions help you to cope up with pressure conditions that might arise in your one to one interview round or even at the aptitude and coding tests, taken mostly as the first round by 99% of the companies."
},
{
"code": null,
"e": 28507,
"s": 28196,
"text": "Also GeeksForGeeks provide you with programmes like Sudo Placement and Sudo Placement 2 that are completely free to join and essentially enables you to get the mindset right for the Coding and Aptitude test. The questions asked in these tests are similar to those that are asked by maximum companies out there."
},
{
"code": null,
"e": 28555,
"s": 28507,
"text": "Remember, Patience and hard work, will pay off."
},
{
"code": null,
"e": 28786,
"s": 28555,
"text": "Now, since we have moved past the competitive coding part, i would like to take up the development part. This mainly comprises of the projects in which you might have contributed and the applications that you might have developed."
},
{
"code": null,
"e": 28943,
"s": 28786,
"text": "I would recommend you to start a practice that i follow i.e Competitive Driven Development. Sounds similar to a development standard, but this is different."
},
{
"code": null,
"e": 29199,
"s": 28943,
"text": "CDD, enables you to write efficient codes. As you will learn more of data structures and develop your competitive skills, the problems that you face when developing an application will get more easily solved and the application will also be innately FAST!"
},
{
"code": null,
"e": 29348,
"s": 29199,
"text": "If you wish you might review the thoughts above as for now we move on to the ‘inspiration’ part of the deed. Mind it, The Problem Solving attitude !"
},
{
"code": null,
"e": 29369,
"s": 29348,
"text": "The inspiration part"
},
{
"code": null,
"e": 29584,
"s": 29369,
"text": "Here too, i won’t be beating around the bush but be to the point. Instead i will take references from my mistakes and that of my friends, so that you are ready with the right outlook of personality, exactly needed."
},
{
"code": null,
"e": 29963,
"s": 29584,
"text": "The moment you get into a university, always look for like minded people. You are not searching for friends, instead you are searching for someone with whom you can talk about your ideas and someone who will be happy to listen to and if needed, correct them. Don’t make yourself alone, ever.The process takes time, but this only starts real ‘productive’ friendships in colleges."
},
{
"code": null,
"e": 30493,
"s": 29963,
"text": "Also, avoid distractions! You might have heard this many time. In fact we all get to listen this all through our childhood, don’t we? But, taking a bit mature perspective on this will make you realise that distractions are all those things in your life that pulls you down. Everything that gives you a feeling of remorse or sadness, not immediately but later, is a distraction. Do you know the cool fact about distractions? We tend to go after them just for the temporary happiness they provide, and this is all they can provide."
},
{
"code": null,
"e": 30548,
"s": 30493,
"text": "I repeat myself, Patience and hardwork, will pay off ."
},
{
"code": null,
"e": 30800,
"s": 30548,
"text": "Be easy on yourself and lead a happy life. Think clear and positive. Be prepared for challenges. Don’t ever get overwhelmed by your own thoughts and talk them out to a friend. You must know, an idea can create everything but also can destroy the same."
},
{
"code": null,
"e": 30899,
"s": 30800,
"text": "I also write on medium so if you find my writing interesting, I would love if you follow me there."
},
{
"code": null,
"e": 30914,
"s": 30899,
"text": "Career-Advices"
},
{
"code": null,
"e": 30929,
"s": 30914,
"text": "Interview Tips"
},
{
"code": null,
"e": 30951,
"s": 30929,
"text": "placement preparation"
},
{
"code": null,
"e": 30975,
"s": 30951,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 30984,
"s": 30975,
"text": "Articles"
},
{
"code": null,
"e": 31000,
"s": 30984,
"text": "CS - Placements"
},
{
"code": null,
"e": 31011,
"s": 31000,
"text": "Placements"
},
{
"code": null,
"e": 31030,
"s": 31011,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31128,
"s": 31030,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31137,
"s": 31128,
"text": "Comments"
},
{
"code": null,
"e": 31150,
"s": 31137,
"text": "Old Comments"
},
{
"code": null,
"e": 31171,
"s": 31150,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 31230,
"s": 31171,
"text": "Amazon’s most frequently asked interview questions | Set 2"
},
{
"code": null,
"e": 31260,
"s": 31230,
"text": "Service-Oriented Architecture"
},
{
"code": null,
"e": 31320,
"s": 31260,
"text": "Must Do Questions for Companies like TCS, CTS, HCL, IBM ..."
},
{
"code": null,
"e": 31344,
"s": 31320,
"text": "Lamport's logical clock"
},
{
"code": null,
"e": 31387,
"s": 31344,
"text": "Applications of linked list data structure"
},
{
"code": null,
"e": 31475,
"s": 31387,
"text": "Most asked Computer Science Subjects Interview Questions in Amazon, Microsoft, Flipkart"
},
{
"code": null,
"e": 31499,
"s": 31475,
"text": "TCS Interview Questions"
},
{
"code": null,
"e": 31523,
"s": 31499,
"text": "Hotel Management System"
}
] |
Python time altzone() Method
|
Python time method altzone() is the attribute of the time module. This returns the offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.
Following is the syntax for altzone() method −
time.altzone
NA
NA
This method returns the offset of the local DST timezone, in seconds west of UTC, if one is defined.
The following example shows the usage of altzone() method.
#!/usr/bin/python
import time
print "time.altzone %d " % time.altzone
When we run above program, it produces following result −
time.altzone() 25200
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2542,
"s": 2244,
"text": "Python time method altzone() is the attribute of the time module. This returns the offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero."
},
{
"code": null,
"e": 2589,
"s": 2542,
"text": "Following is the syntax for altzone() method −"
},
{
"code": null,
"e": 2603,
"s": 2589,
"text": "time.altzone\n"
},
{
"code": null,
"e": 2606,
"s": 2603,
"text": "NA"
},
{
"code": null,
"e": 2609,
"s": 2606,
"text": "NA"
},
{
"code": null,
"e": 2710,
"s": 2609,
"text": "This method returns the offset of the local DST timezone, in seconds west of UTC, if one is defined."
},
{
"code": null,
"e": 2769,
"s": 2710,
"text": "The following example shows the usage of altzone() method."
},
{
"code": null,
"e": 2840,
"s": 2769,
"text": "#!/usr/bin/python\nimport time\n\nprint \"time.altzone %d \" % time.altzone"
},
{
"code": null,
"e": 2898,
"s": 2840,
"text": "When we run above program, it produces following result −"
},
{
"code": null,
"e": 2920,
"s": 2898,
"text": "time.altzone() 25200\n"
},
{
"code": null,
"e": 2957,
"s": 2920,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 2973,
"s": 2957,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3006,
"s": 2973,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3025,
"s": 3006,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3060,
"s": 3025,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3082,
"s": 3060,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3116,
"s": 3082,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3144,
"s": 3116,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3179,
"s": 3144,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3193,
"s": 3179,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3226,
"s": 3193,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3243,
"s": 3226,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3250,
"s": 3243,
"text": " Print"
},
{
"code": null,
"e": 3261,
"s": 3250,
"text": " Add Notes"
}
] |
MySQL Stored Procedure to create a table?
|
Following is the query to create a stored procedure that creates a table. Here, we are creating a table with three columns, one of them is Id −
mysql> DELIMITER //
mysql> CREATE PROCEDURE Stored_Procedure_CreatingTable()
BEGIN
create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserFirstName varchar(20),
UserLastName varchar(20)
);
END;
//
Query OK, 0 rows affected (0.16 sec)
mysql> DELIMITER ;
Now you can call stored procedure with the help of CALL command −
mysql> call Stored_Procedure_CreatingTable();
Query OK, 0 rows affected (0.18 sec)
Let us check the description of table using DESC command −
mysql> desc DemoTable;
This will produce the following output −
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
| UserFirstName | varchar(20) | YES | | NULL | |
| UserLastName | varchar(20) | YES | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
3 rows in set (0.04 sec)
|
[
{
"code": null,
"e": 1206,
"s": 1062,
"text": "Following is the query to create a stored procedure that creates a table. Here, we are creating a table with three columns, one of them is Id −"
},
{
"code": null,
"e": 1528,
"s": 1206,
"text": "mysql> DELIMITER //\n mysql> CREATE PROCEDURE Stored_Procedure_CreatingTable()\n BEGIN\n create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n UserFirstName varchar(20),\n UserLastName varchar(20)\n );\n END;\n //\n Query OK, 0 rows affected (0.16 sec)\nmysql> DELIMITER ;"
},
{
"code": null,
"e": 1594,
"s": 1528,
"text": "Now you can call stored procedure with the help of CALL command −"
},
{
"code": null,
"e": 1677,
"s": 1594,
"text": "mysql> call Stored_Procedure_CreatingTable();\nQuery OK, 0 rows affected (0.18 sec)"
},
{
"code": null,
"e": 1736,
"s": 1677,
"text": "Let us check the description of table using DESC command −"
},
{
"code": null,
"e": 1759,
"s": 1736,
"text": "mysql> desc DemoTable;"
},
{
"code": null,
"e": 1800,
"s": 1759,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2329,
"s": 1800,
"text": "+---------------+-------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+---------------+-------------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| UserFirstName | varchar(20) | YES | | NULL | |\n| UserLastName | varchar(20) | YES | | NULL | |\n+---------------+-------------+------+-----+---------+----------------+\n3 rows in set (0.04 sec)"
}
] |
How to handle ESC keydown on JavaScript popup window?
|
As we know the ESC has the keycode 27. If you will use the keycode 27, then you can handle the condition.
Following is the code −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<body>
</body>
<script>
$(document).keydown(function (eventValue) {
if (eventValue.keyCode == 27) {
console.log("ESC key is pressed....");
}
else {
console.log("Some other is key pressed....")
}
});
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now I am going to press another button except the ESC key.
This will produce the following output on console −
Now, I am going to press the ESC key. The console output will change −
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "As we know the ESC has the keycode 27. If you will use the keycode 27, then you can handle the condition."
},
{
"code": null,
"e": 1192,
"s": 1168,
"text": "Following is the code −"
},
{
"code": null,
"e": 1956,
"s": 1192,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>Document</title>\n</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" rel=\"stylesheet\" />\n<body>\n</body>\n<script>\n $(document).keydown(function (eventValue) {\n if (eventValue.keyCode == 27) {\n console.log(\"ESC key is pressed....\");\n }\n else {\n console.log(\"Some other is key pressed....\")\n }\n });\n</script>\n</html>"
},
{
"code": null,
"e": 2118,
"s": 1956,
"text": "To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2159,
"s": 2118,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2218,
"s": 2159,
"text": "Now I am going to press another button except the ESC key."
},
{
"code": null,
"e": 2270,
"s": 2218,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2341,
"s": 2270,
"text": "Now, I am going to press the ESC key. The console output will change −"
}
] |
Linux Admin - Set Up Perl for CentOS Linux
|
Perl has been around for a long time. It was originally designed as a reporting language used for parsing text files. With increased popularity, Perl has added a module support or CPAN, sockets, threading, and other features needed in a powerful scripting language.
The biggest advantage of Perl over PHP, Python, or Ruby is: it gets things done with minimal fuss. This philosophy of Perl does not always mean it gets things done the right way. However, for administration tasks on Linux, Perl is considered as the go-to choice for a scripting language.
Some advantages of Perl over Python or Ruby are −
Powerful text processing
Powerful text processing
Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)
Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)
Perl can do anything (almost)
Perl can do anything (almost)
Some drawbacks of Perl are −
Syntax can be confusing
Syntax can be confusing
Coding style in Perl can be unique and bog down collaboration
Coding style in Perl can be unique and bog down collaboration
Perl is not really Object Oriented
Perl is not really Object Oriented
Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used.
Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used.
When deciding whether to use Perl, Python or PHP; the following questions should be asked −
Will this application ever need versioning?
Will other people ever need to modify the code?
Will other people need to use this application?
Will this application ever be used on another machine or CPU architecture?
If the answers to all the above are "no", Perl is a good choice and may speed things up in terms of end-results.
With this mentioned, let's configure our CentOS server to use the most recent version of Perl.
Before installing Perl, we need to understand the support for Perl. Officially, Perl is only supported far back as the last two stable versions. So, we want to be sure to keep our development environment isolated from the CentOS version.
The reason for isolation is: if someone releases a tool in Perl to the CentOS community, more than likely it will be modified to work on Perl as shipped with CentOS. However, we also want to have the latest version installed for development purposes. Like Python, CentOS ships Perl focused on the reliability and not cutting edge.
Let's check our current version of Perl on CentOS 7.
[root@CentOS]# perl -v
This is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi
We are currently running Perl 5.16.3. The most current version as of this writing is: perl-5.24.0
We definitely want to upgrade our version, being able to use up-to-date Perl modules in our code. Fortunately, there is a great tool for maintaining Perl environments and keeping our CentOS version of Perl isolated. It is called perlbrew.
Let's install Perl Brew.
[root@CentOS]# curl -L https://install.perlbrew.pl | bash
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 170 100 170 0 0 396 0 --:--:-- --:--:-- --:--:-- 397
100 1247 100 1247 0 0 1929 0 --:--:-- --:--:-- --:--:-- 1929
Now that we have Perl Brew installed, let's make an environment for the latest version of Perl.
First, we will need the currently installed version of Perl to bootstrap the perlbrew install. Thus, let's get some needed Perl modules from the CentOS repository.
Note − When available we always want to use CentOS Perl modules versus CPAN with our CentOS Perl installation.
Step 1 − Install CentOS Perl Make::Maker module.
[root@CentOS]# yum -y install perl-ExtUtils-MakeMaker.noarch
Step 2 − Install the latest version of perl.
[root@CentOS build]# source ~/perl5/perlbrew/etc/bashrc
[root@CentOS build]# perlbrew install -n -j4 --threads perl-5.24.1
The options we chose for our Perl install are −
n − No tests
n − No tests
j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)
j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)
threads − Enable threading support for Perl
threads − Enable threading support for Perl
After our installation has been performed successfully, let's switch to our newest Perl environment.
[root@CentOS]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1
A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.
[root@CentOS]# perl -v
This is perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linuxthread-multi
(with 1 registered patch, see perl -V for more detail)
Copyright 1987-2017, Larry Wall
Perl may be copied only under the terms of either the Artistic License or the GNU General
Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on this system
using "man perl" or "perldoc perl". If you have access to the Internet, point your
browser at http://www.perl.org/, the Perl Home Page.
[root@CentOS]#
Simple perl script printing perl version running within the context of our perlbrew environment −
[root@CentOS]# cat ./ver.pl
#!/usr/bin/perl
print $^V . "\n";
[root@CentOS]# perl ./ver.pl
v5.24.1
[root@CentOS]#
Once perl is installed, we can load cpan modules with perl brew's cpanm −
[root@CentOS]# perl-brew install-cpanm
Now let's use the cpanm installer to make the LWP module with our current Perl version of 5.24.1 in perl brew.
Step 1 − Switch to the context of our current Perl version.
[root@CentOS ~]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1
A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.
[root@CentOS ~]#
Step 2 − Install LWP User Agent Perl Module.
[root@CentOS ~]# ~/perl5/perlbrew/bin/cpanm -i LWP::UserAgent
Step 3 − Now let's test our Perl environment with the new CPAN module.
[root@CentOS ~]# cat ./get_header.pl
#!/usr/bin/perl
use LWP;
my $browser = LWP::UserAgent->new();
my $response = $browser->get("http://www.slcc.edu/");
unless(!$response->is_success) {
print $response->header("Server");
}
[root@CentOS ~]# perl ./get_header.pl
Microsoft-IIS/8.5 [root@CentOS ~]#
There you have it! Perl Brew makes isolating perl environments a snap and can be considered as a best practice as things get with Perl.
57 Lectures
7.5 hours
Mamta Tripathi
25 Lectures
3 hours
Lets Kode It
14 Lectures
1.5 hours
Abhilash Nelson
58 Lectures
2.5 hours
Frahaan Hussain
129 Lectures
23 hours
Eduonix Learning Solutions
23 Lectures
5 hours
Pranjal Srivastava, Harshit Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2523,
"s": 2257,
"text": "Perl has been around for a long time. It was originally designed as a reporting language used for parsing text files. With increased popularity, Perl has added a module support or CPAN, sockets, threading, and other features needed in a powerful scripting language."
},
{
"code": null,
"e": 2811,
"s": 2523,
"text": "The biggest advantage of Perl over PHP, Python, or Ruby is: it gets things done with minimal fuss. This philosophy of Perl does not always mean it gets things done the right way. However, for administration tasks on Linux, Perl is considered as the go-to choice for a scripting language."
},
{
"code": null,
"e": 2861,
"s": 2811,
"text": "Some advantages of Perl over Python or Ruby are −"
},
{
"code": null,
"e": 2886,
"s": 2861,
"text": "Powerful text processing"
},
{
"code": null,
"e": 2911,
"s": 2886,
"text": "Powerful text processing"
},
{
"code": null,
"e": 3051,
"s": 2911,
"text": "Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)"
},
{
"code": null,
"e": 3191,
"s": 3051,
"text": "Perl makes writing scripts quick and dirty (usually a Perl script will be several dozen lines shorter than an equivalent in Python or Ruby)"
},
{
"code": null,
"e": 3221,
"s": 3191,
"text": "Perl can do anything (almost)"
},
{
"code": null,
"e": 3251,
"s": 3221,
"text": "Perl can do anything (almost)"
},
{
"code": null,
"e": 3280,
"s": 3251,
"text": "Some drawbacks of Perl are −"
},
{
"code": null,
"e": 3304,
"s": 3280,
"text": "Syntax can be confusing"
},
{
"code": null,
"e": 3328,
"s": 3304,
"text": "Syntax can be confusing"
},
{
"code": null,
"e": 3390,
"s": 3328,
"text": "Coding style in Perl can be unique and bog down collaboration"
},
{
"code": null,
"e": 3452,
"s": 3390,
"text": "Coding style in Perl can be unique and bog down collaboration"
},
{
"code": null,
"e": 3487,
"s": 3452,
"text": "Perl is not really Object Oriented"
},
{
"code": null,
"e": 3522,
"s": 3487,
"text": "Perl is not really Object Oriented"
},
{
"code": null,
"e": 3624,
"s": 3522,
"text": "Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used."
},
{
"code": null,
"e": 3726,
"s": 3624,
"text": "Typically, there isn't a lot of thought put into standardization and best-practice when Perl is used."
},
{
"code": null,
"e": 3818,
"s": 3726,
"text": "When deciding whether to use Perl, Python or PHP; the following questions should be asked −"
},
{
"code": null,
"e": 3862,
"s": 3818,
"text": "Will this application ever need versioning?"
},
{
"code": null,
"e": 3910,
"s": 3862,
"text": "Will other people ever need to modify the code?"
},
{
"code": null,
"e": 3958,
"s": 3910,
"text": "Will other people need to use this application?"
},
{
"code": null,
"e": 4033,
"s": 3958,
"text": "Will this application ever be used on another machine or CPU architecture?"
},
{
"code": null,
"e": 4146,
"s": 4033,
"text": "If the answers to all the above are \"no\", Perl is a good choice and may speed things up in terms of end-results."
},
{
"code": null,
"e": 4241,
"s": 4146,
"text": "With this mentioned, let's configure our CentOS server to use the most recent version of Perl."
},
{
"code": null,
"e": 4479,
"s": 4241,
"text": "Before installing Perl, we need to understand the support for Perl. Officially, Perl is only supported far back as the last two stable versions. So, we want to be sure to keep our development environment isolated from the CentOS version."
},
{
"code": null,
"e": 4810,
"s": 4479,
"text": "The reason for isolation is: if someone releases a tool in Perl to the CentOS community, more than likely it will be modified to work on Perl as shipped with CentOS. However, we also want to have the latest version installed for development purposes. Like Python, CentOS ships Perl focused on the reliability and not cutting edge."
},
{
"code": null,
"e": 4863,
"s": 4810,
"text": "Let's check our current version of Perl on CentOS 7."
},
{
"code": null,
"e": 4975,
"s": 4863,
"text": "[root@CentOS]# perl -v \nThis is perl 5, version 16, subversion 3 (v5.16.3) built for x86_64-linux-thread-multi\n"
},
{
"code": null,
"e": 5073,
"s": 4975,
"text": "We are currently running Perl 5.16.3. The most current version as of this writing is: perl-5.24.0"
},
{
"code": null,
"e": 5312,
"s": 5073,
"text": "We definitely want to upgrade our version, being able to use up-to-date Perl modules in our code. Fortunately, there is a great tool for maintaining Perl environments and keeping our CentOS version of Perl isolated. It is called perlbrew."
},
{
"code": null,
"e": 5337,
"s": 5312,
"text": "Let's install Perl Brew."
},
{
"code": null,
"e": 5710,
"s": 5337,
"text": "[root@CentOS]# curl -L https://install.perlbrew.pl | bash \n% Total % Received % Xferd Average Speed Time Time Time Current \n Dload Upload Total Spent Left Speed \n100 170 100 170 0 0 396 0 --:--:-- --:--:-- --:--:-- 397 \n100 1247 100 1247 0 0 1929 0 --:--:-- --:--:-- --:--:-- 1929\n"
},
{
"code": null,
"e": 5806,
"s": 5710,
"text": "Now that we have Perl Brew installed, let's make an environment for the latest version of Perl."
},
{
"code": null,
"e": 5970,
"s": 5806,
"text": "First, we will need the currently installed version of Perl to bootstrap the perlbrew install. Thus, let's get some needed Perl modules from the CentOS repository."
},
{
"code": null,
"e": 6081,
"s": 5970,
"text": "Note − When available we always want to use CentOS Perl modules versus CPAN with our CentOS Perl installation."
},
{
"code": null,
"e": 6130,
"s": 6081,
"text": "Step 1 − Install CentOS Perl Make::Maker module."
},
{
"code": null,
"e": 6192,
"s": 6130,
"text": "[root@CentOS]# yum -y install perl-ExtUtils-MakeMaker.noarch\n"
},
{
"code": null,
"e": 6237,
"s": 6192,
"text": "Step 2 − Install the latest version of perl."
},
{
"code": null,
"e": 6361,
"s": 6237,
"text": "[root@CentOS build]# source ~/perl5/perlbrew/etc/bashrc\n[root@CentOS build]# perlbrew install -n -j4 --threads perl-5.24.1\n"
},
{
"code": null,
"e": 6409,
"s": 6361,
"text": "The options we chose for our Perl install are −"
},
{
"code": null,
"e": 6422,
"s": 6409,
"text": "n − No tests"
},
{
"code": null,
"e": 6435,
"s": 6422,
"text": "n − No tests"
},
{
"code": null,
"e": 6530,
"s": 6435,
"text": "j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)"
},
{
"code": null,
"e": 6625,
"s": 6530,
"text": "j4 − Execute 4 threads in parallel for the installation routines (we are using a quadcore CPU)"
},
{
"code": null,
"e": 6669,
"s": 6625,
"text": "threads − Enable threading support for Perl"
},
{
"code": null,
"e": 6713,
"s": 6669,
"text": "threads − Enable threading support for Perl"
},
{
"code": null,
"e": 6814,
"s": 6713,
"text": "After our installation has been performed successfully, let's switch to our newest Perl environment."
},
{
"code": null,
"e": 7559,
"s": 6814,
"text": "[root@CentOS]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1\n\nA sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it.\n\n[root@CentOS]# perl -v\n\nThis is perl 5, version 24, subversion 1 (v5.24.1) built for x86_64-linuxthread-multi\n\n(with 1 registered patch, see perl -V for more detail)\n\nCopyright 1987-2017, Larry Wall\n\nPerl may be copied only under the terms of either the Artistic License or the GNU General\nPublic License, which may be found in the Perl 5 source kit.\n\nComplete documentation for Perl, including FAQ lists, should be found on this system \nusing \"man perl\" or \"perldoc perl\". If you have access to the Internet, point your \nbrowser at http://www.perl.org/, the Perl Home Page.\n\n[root@CentOS]#\n"
},
{
"code": null,
"e": 7657,
"s": 7559,
"text": "Simple perl script printing perl version running within the context of our perlbrew environment −"
},
{
"code": null,
"e": 7722,
"s": 7657,
"text": "[root@CentOS]# cat ./ver.pl \n#!/usr/bin/perl\nprint $^V . \"\\n\";\n"
},
{
"code": null,
"e": 7778,
"s": 7722,
"text": "[root@CentOS]# perl ./ver.pl \nv5.24.1 \n[root@CentOS]#\n"
},
{
"code": null,
"e": 7852,
"s": 7778,
"text": "Once perl is installed, we can load cpan modules with perl brew's cpanm −"
},
{
"code": null,
"e": 7892,
"s": 7852,
"text": "[root@CentOS]# perl-brew install-cpanm\n"
},
{
"code": null,
"e": 8003,
"s": 7892,
"text": "Now let's use the cpanm installer to make the LWP module with our current Perl version of 5.24.1 in perl brew."
},
{
"code": null,
"e": 8063,
"s": 8003,
"text": "Step 1 − Switch to the context of our current Perl version."
},
{
"code": null,
"e": 8127,
"s": 8063,
"text": "[root@CentOS ~]# ~/perl5/perlbrew/bin/perlbrew use perl-5.24.1\n"
},
{
"code": null,
"e": 8216,
"s": 8127,
"text": "A sub-shell is launched with perl-5.24.1 as the activated perl. Run 'exit' to finish it."
},
{
"code": null,
"e": 8234,
"s": 8216,
"text": "[root@CentOS ~]#\n"
},
{
"code": null,
"e": 8279,
"s": 8234,
"text": "Step 2 − Install LWP User Agent Perl Module."
},
{
"code": null,
"e": 8342,
"s": 8279,
"text": "[root@CentOS ~]# ~/perl5/perlbrew/bin/cpanm -i LWP::UserAgent\n"
},
{
"code": null,
"e": 8413,
"s": 8342,
"text": "Step 3 − Now let's test our Perl environment with the new CPAN module."
},
{
"code": null,
"e": 8723,
"s": 8413,
"text": "[root@CentOS ~]# cat ./get_header.pl \n#!/usr/bin/perl \nuse LWP; \nmy $browser = LWP::UserAgent->new(); \nmy $response = $browser->get(\"http://www.slcc.edu/\"); \nunless(!$response->is_success) { \n print $response->header(\"Server\"); \n}\n\n[root@CentOS ~]# perl ./get_header.pl \nMicrosoft-IIS/8.5 [root@CentOS ~]#"
},
{
"code": null,
"e": 8859,
"s": 8723,
"text": "There you have it! Perl Brew makes isolating perl environments a snap and can be considered as a best practice as things get with Perl."
},
{
"code": null,
"e": 8894,
"s": 8859,
"text": "\n 57 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8910,
"s": 8894,
"text": " Mamta Tripathi"
},
{
"code": null,
"e": 8943,
"s": 8910,
"text": "\n 25 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 8957,
"s": 8943,
"text": " Lets Kode It"
},
{
"code": null,
"e": 8992,
"s": 8957,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9009,
"s": 8992,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 9044,
"s": 9009,
"text": "\n 58 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 9061,
"s": 9044,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 9096,
"s": 9061,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 9124,
"s": 9096,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9157,
"s": 9124,
"text": "\n 23 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9197,
"s": 9157,
"text": " Pranjal Srivastava, Harshit Srivastava"
},
{
"code": null,
"e": 9204,
"s": 9197,
"text": " Print"
},
{
"code": null,
"e": 9215,
"s": 9204,
"text": " Add Notes"
}
] |
Servlets - Life Cycle
|
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet container.
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
31 Lectures
12.5 hours
Uplatz
38 Lectures
4.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2334,
"s": 2185,
"text": "A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet."
},
{
"code": null,
"e": 2391,
"s": 2334,
"text": "The servlet is initialized by calling the init() method."
},
{
"code": null,
"e": 2448,
"s": 2391,
"text": "The servlet is initialized by calling the init() method."
},
{
"code": null,
"e": 2515,
"s": 2448,
"text": "The servlet calls service() method to process a client's request. "
},
{
"code": null,
"e": 2582,
"s": 2515,
"text": "The servlet calls service() method to process a client's request. "
},
{
"code": null,
"e": 2641,
"s": 2582,
"text": "The servlet is terminated by calling the destroy() method."
},
{
"code": null,
"e": 2700,
"s": 2641,
"text": "The servlet is terminated by calling the destroy() method."
},
{
"code": null,
"e": 2775,
"s": 2700,
"text": "Finally, servlet is garbage collected by the garbage collector of the JVM."
},
{
"code": null,
"e": 2850,
"s": 2775,
"text": "Finally, servlet is garbage collected by the garbage collector of the JVM."
},
{
"code": null,
"e": 2903,
"s": 2850,
"text": "Now let us discuss the life cycle methods in detail."
},
{
"code": null,
"e": 3122,
"s": 2903,
"text": "The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets."
},
{
"code": null,
"e": 3302,
"s": 3122,
"text": "The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started."
},
{
"code": null,
"e": 3590,
"s": 3302,
"text": "When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet."
},
{
"code": null,
"e": 3635,
"s": 3590,
"text": "The init method definition looks like this −"
},
{
"code": null,
"e": 3711,
"s": 3635,
"text": "public void init() throws ServletException {\n // Initialization code...\n}"
},
{
"code": null,
"e": 3955,
"s": 3711,
"text": "The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client."
},
{
"code": null,
"e": 4212,
"s": 3955,
"text": "Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate."
},
{
"code": null,
"e": 4251,
"s": 4212,
"text": "Here is the signature of this method −"
},
{
"code": null,
"e": 4366,
"s": 4251,
"text": "public void service(ServletRequest request, ServletResponse response) \n throws ServletException, IOException {\n}"
},
{
"code": null,
"e": 4658,
"s": 4366,
"text": "The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client."
},
{
"code": null,
"e": 4790,
"s": 4658,
"text": "The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods."
},
{
"code": null,
"e": 4938,
"s": 4790,
"text": "A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method."
},
{
"code": null,
"e": 5077,
"s": 4938,
"text": "public void doGet(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n // Servlet code\n}"
},
{
"code": null,
"e": 5206,
"s": 5077,
"text": "A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method."
},
{
"code": null,
"e": 5346,
"s": 5206,
"text": "public void doPost(HttpServletRequest request, HttpServletResponse response)\n throws ServletException, IOException {\n // Servlet code\n}"
},
{
"code": null,
"e": 5611,
"s": 5346,
"text": "The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities."
},
{
"code": null,
"e": 5750,
"s": 5611,
"text": "After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −"
},
{
"code": null,
"e": 5803,
"s": 5750,
"text": "public void destroy() {\n // Finalization code...\n}"
},
{
"code": null,
"e": 5871,
"s": 5803,
"text": "The following figure depicts a typical servlet life-cycle scenario."
},
{
"code": null,
"e": 5956,
"s": 5871,
"text": "First the HTTP requests coming to the server are delegated to the servlet container."
},
{
"code": null,
"e": 6041,
"s": 5956,
"text": "First the HTTP requests coming to the server are delegated to the servlet container."
},
{
"code": null,
"e": 6119,
"s": 6041,
"text": "The servlet container loads the servlet before invoking the service() method."
},
{
"code": null,
"e": 6197,
"s": 6119,
"text": "The servlet container loads the servlet before invoking the service() method."
},
{
"code": null,
"e": 6360,
"s": 6197,
"text": "Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet."
},
{
"code": null,
"e": 6523,
"s": 6360,
"text": "Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet."
},
{
"code": null,
"e": 6558,
"s": 6523,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6572,
"s": 6558,
"text": " Karthikeya T"
},
{
"code": null,
"e": 6607,
"s": 6572,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6623,
"s": 6607,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6656,
"s": 6623,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6672,
"s": 6656,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6708,
"s": 6672,
"text": "\n 31 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6716,
"s": 6708,
"text": " Uplatz"
},
{
"code": null,
"e": 6751,
"s": 6716,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6769,
"s": 6751,
"text": " Packt Publishing"
},
{
"code": null,
"e": 6776,
"s": 6769,
"text": " Print"
},
{
"code": null,
"e": 6787,
"s": 6776,
"text": " Add Notes"
}
] |
How can I append a tuple into another tuple in Python?
|
You can directly add a tuple to another tuple using a + operator. For example,
x = (1, 2, 3)
y = (4, 5)
x = x + y
print(x)
This will give the output
x = (1, 2, 3)
y = (4, 5)
x = x + y
|
[
{
"code": null,
"e": 1141,
"s": 1062,
"text": "You can directly add a tuple to another tuple using a + operator. For example,"
},
{
"code": null,
"e": 1185,
"s": 1141,
"text": "x = (1, 2, 3)\ny = (4, 5)\nx = x + y\nprint(x)"
},
{
"code": null,
"e": 1211,
"s": 1185,
"text": "This will give the output"
},
{
"code": null,
"e": 1246,
"s": 1211,
"text": "x = (1, 2, 3)\ny = (4, 5)\nx = x + y"
}
] |
Perl send Function
|
This function sends a message on SOCKET (the opposite of recv). If the socket is unconnected, you must supply a destination to communicate to with the TO parameter. In this case, the sendto system function is used in place of the system send function.
The FLAGS parameter is formed from the bitwise or of 0 and one or more of the MSG_OOB and MSG_DONTROUTE options. MSG_OOB allows you to send out-of-band data on sockets that support this notion.
The underlying protocol must also support out-of-band data. Only SOCK_STREAM sockets created in the AF_INET address family support out-of-band data. The MSG_DONTROUTE option is turned on for the duration of the operation. Only diagnostic or routing programs use it.
Following is the simple syntax for this function −
send SOCKET, MSG, FLAGS, TO
send SOCKET, MSG, FLAGS
This function returns undef on failure else Integer, number of bytes sent.
46 Lectures
4.5 hours
Devi Killada
11 Lectures
1.5 hours
Harshit Srivastava
30 Lectures
6 hours
TELCOMA Global
24 Lectures
2 hours
Mohammad Nauman
68 Lectures
7 hours
Stone River ELearning
58 Lectures
6.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2472,
"s": 2220,
"text": "This function sends a message on SOCKET (the opposite of recv). If the socket is unconnected, you must supply a destination to communicate to with the TO parameter. In this case, the sendto system function is used in place of the system send function."
},
{
"code": null,
"e": 2666,
"s": 2472,
"text": "The FLAGS parameter is formed from the bitwise or of 0 and one or more of the MSG_OOB and MSG_DONTROUTE options. MSG_OOB allows you to send out-of-band data on sockets that support this notion."
},
{
"code": null,
"e": 2932,
"s": 2666,
"text": "The underlying protocol must also support out-of-band data. Only SOCK_STREAM sockets created in the AF_INET address family support out-of-band data. The MSG_DONTROUTE option is turned on for the duration of the operation. Only diagnostic or routing programs use it."
},
{
"code": null,
"e": 2983,
"s": 2932,
"text": "Following is the simple syntax for this function −"
},
{
"code": null,
"e": 3037,
"s": 2983,
"text": "send SOCKET, MSG, FLAGS, TO\n\nsend SOCKET, MSG, FLAGS\n"
},
{
"code": null,
"e": 3112,
"s": 3037,
"text": "This function returns undef on failure else Integer, number of bytes sent."
},
{
"code": null,
"e": 3147,
"s": 3112,
"text": "\n 46 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3161,
"s": 3147,
"text": " Devi Killada"
},
{
"code": null,
"e": 3196,
"s": 3161,
"text": "\n 11 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3216,
"s": 3196,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 3249,
"s": 3216,
"text": "\n 30 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3265,
"s": 3249,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3298,
"s": 3265,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3315,
"s": 3298,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 3348,
"s": 3315,
"text": "\n 68 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3371,
"s": 3348,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3406,
"s": 3371,
"text": "\n 58 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3429,
"s": 3406,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3436,
"s": 3429,
"text": " Print"
},
{
"code": null,
"e": 3447,
"s": 3436,
"text": " Add Notes"
}
] |
Jenkins - Setup Build Jobs
|
For this exercise, we will create a job in Jenkins which picks up a simple HelloWorld application, builds and runs the java program.
Step 1 − Go to the Jenkins dashboard and Click on New Item
Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’
Step 3 − The following screen will come up in which you can specify the details of the job.
Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git repository(E:\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the URL of the local git repository.
Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository.
Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command
Step 6 − In the command window, enter the following commands and then click on the Save button.
Javac HelloWorld.java
Java HelloWorld
Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job.
Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress.
Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has been executed successfully. Click on the #1 in the Build history to bring up the details of the build.
Step 10 − Click on the Console Output link to see the details of the build
Apart from the steps shown above there are just so many ways to create a build job, the options available are many, which what makes Jenkins such a fantastic continuous deployment tool.
38 Lectures
5 hours
Eduonix Learning Solutions
41 Lectures
5 hours
AR Shankar
42 Lectures
2 hours
Chaitanya Allidona
37 Lectures
2.5 hours
Spotle Learn
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2256,
"s": 2123,
"text": "For this exercise, we will create a job in Jenkins which picks up a simple HelloWorld application, builds and runs the java program."
},
{
"code": null,
"e": 2315,
"s": 2256,
"text": "Step 1 − Go to the Jenkins dashboard and Click on New Item"
},
{
"code": null,
"e": 2445,
"s": 2315,
"text": "Step 2 − In the next screen, enter the Item name, in this case we have named it Helloworld. Choose the ‘Freestyle project option’"
},
{
"code": null,
"e": 2537,
"s": 2445,
"text": "Step 3 − The following screen will come up in which you can specify the details of the job."
},
{
"code": null,
"e": 2832,
"s": 2537,
"text": "Step 4 − We need to specify the location of files which need to be built. In this example, we will assume that a local git repository(E:\\Program) has been setup which contains a ‘HelloWorld.java’ file. Hence scroll down and click on the Git option and enter the URL of the local git repository."
},
{
"code": null,
"e": 3132,
"s": 2832,
"text": "Note − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository."
},
{
"code": null,
"e": 3229,
"s": 3132,
"text": "Step 5 − Now go to the Build section and click on Add build step → Execute Windows batch command"
},
{
"code": null,
"e": 3325,
"s": 3229,
"text": "Step 6 − In the command window, enter the following commands and then click on the Save button."
},
{
"code": null,
"e": 3364,
"s": 3325,
"text": "Javac HelloWorld.java\nJava HelloWorld\n"
},
{
"code": null,
"e": 3472,
"s": 3364,
"text": "Step 7 − Once saved, you can click on the Build Now option to see if you have successfully defined the job."
},
{
"code": null,
"e": 3594,
"s": 3472,
"text": "Step 8 − Once the build is scheduled, it will run. The following Build history section shows that a build is in progress."
},
{
"code": null,
"e": 3840,
"s": 3594,
"text": "Step 9 − Once the build is completed, a status of the build will show if the build was successful or not. In our case, the following build has been executed successfully. Click on the #1 in the Build history to bring up the details of the build."
},
{
"code": null,
"e": 3915,
"s": 3840,
"text": "Step 10 − Click on the Console Output link to see the details of the build"
},
{
"code": null,
"e": 4101,
"s": 3915,
"text": "Apart from the steps shown above there are just so many ways to create a build job, the options available are many, which what makes Jenkins such a fantastic continuous deployment tool."
},
{
"code": null,
"e": 4134,
"s": 4101,
"text": "\n 38 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4162,
"s": 4134,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4195,
"s": 4162,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4207,
"s": 4195,
"text": " AR Shankar"
},
{
"code": null,
"e": 4240,
"s": 4207,
"text": "\n 42 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4260,
"s": 4240,
"text": " Chaitanya Allidona"
},
{
"code": null,
"e": 4295,
"s": 4260,
"text": "\n 37 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4309,
"s": 4295,
"text": " Spotle Learn"
},
{
"code": null,
"e": 4316,
"s": 4309,
"text": " Print"
},
{
"code": null,
"e": 4327,
"s": 4316,
"text": " Add Notes"
}
] |
Data Structures | Binary Search Trees | Question 7
|
28 Jun, 2021
The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004)(A) 2(B) 3(C) 4(D) 6Answer: (B)Explanation: Constructed binary search tree will be..
10
/ \
1 15
\ / \
3 12 16
\
5
Quiz of this Question
Binary Search Trees
Data Structures
Data Structures-Binary Search Trees
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Data Structures | Array | Question 2
Data Structures | Queue | Question 2
Data Structures | Hash | Question 5
Amazon Interview Experience for SDE-II
Data Structures | Linked List | Question 4
Data Structures | Linked List | Question 16
Data Structures | Linked List | Question 11
Data Structures | Linked List | Question 15
Data Structures | Queue | Question 11
Data Structures | Linked List | Question 8
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 377,
"s": 53,
"text": "The following numbers are inserted into an empty binary search tree in the given order: 10, 1, 3, 5, 15, 12, 16. What is the height of the binary search tree (the height is the maximum distance of a leaf node from the root)? (GATE CS 2004)(A) 2(B) 3(C) 4(D) 6Answer: (B)Explanation: Constructed binary search tree will be.."
},
{
"code": null,
"e": 559,
"s": 377,
"text": " 10\n / \\\n 1 15\n \\ / \\\n 3 12 16\n \\\n 5"
},
{
"code": null,
"e": 581,
"s": 559,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 601,
"s": 581,
"text": "Binary Search Trees"
},
{
"code": null,
"e": 617,
"s": 601,
"text": "Data Structures"
},
{
"code": null,
"e": 653,
"s": 617,
"text": "Data Structures-Binary Search Trees"
},
{
"code": null,
"e": 669,
"s": 653,
"text": "Data Structures"
},
{
"code": null,
"e": 685,
"s": 669,
"text": "Data Structures"
},
{
"code": null,
"e": 783,
"s": 685,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 820,
"s": 783,
"text": "Data Structures | Array | Question 2"
},
{
"code": null,
"e": 857,
"s": 820,
"text": "Data Structures | Queue | Question 2"
},
{
"code": null,
"e": 893,
"s": 857,
"text": "Data Structures | Hash | Question 5"
},
{
"code": null,
"e": 932,
"s": 893,
"text": "Amazon Interview Experience for SDE-II"
},
{
"code": null,
"e": 975,
"s": 932,
"text": "Data Structures | Linked List | Question 4"
},
{
"code": null,
"e": 1019,
"s": 975,
"text": "Data Structures | Linked List | Question 16"
},
{
"code": null,
"e": 1063,
"s": 1019,
"text": "Data Structures | Linked List | Question 11"
},
{
"code": null,
"e": 1107,
"s": 1063,
"text": "Data Structures | Linked List | Question 15"
},
{
"code": null,
"e": 1145,
"s": 1107,
"text": "Data Structures | Queue | Question 11"
}
] |
Sum of middle row and column in Matrix
|
11 Jun, 2022
Given an integer matrix of odd dimensions (3 * 3, 5 * 5). then the task is to find the sum of the middle row & column elements. Examples:
Input : 2 5 7
3 7 2
5 6 9
Output : Sum of middle row = 12
Sum of middle column = 18
Input : 1 3 5 6 7
3 5 3 2 1
1 2 3 4 5
7 9 2 1 6
9 1 5 3 2
Output : Sum of middle row = 15
Sum of middle column = 18
CPP
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of// middle row and column in matrix#include <iostream>using namespace std;const int MAX = 100; void middlesum(int mat[][MAX], int n){ int row_sum = 0, col_sum = 0; //loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2][i]; cout << "Sum of middle row = " << row_sum<<endl; //loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i][n / 2]; cout << "Sum of middle column = " << col_sum;} // Driver functionint main(){ int mat[][MAX] = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); return 0;}
// java program to find sum of// middle row and column in matrix import java.io.*; class GFG { static int MAX = 100; static void middlesum(int mat[][], int n){ int row_sum = 0, col_sum = 0; // loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2][i]; System.out.println ( "Sum of middle row = " + row_sum); // loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i][n / 2]; System.out.println ( "Sum of middle column = " + col_sum);} // Driver function public static void main (String[] args) { int mat[][] = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); }} // This code is contributed by vt_m.
# Python program to find sum of# middle row and column in matrix def middlesum(mat,n): row_sum = 0 col_sum = 0 # loop for sum of row for i in range(n): row_sum += mat[n // 2][i] print("Sum of middle row = ", row_sum) # loop for sum of column for i in range(n): col_sum += mat[i][n // 2] print("Sum of middle column = ", col_sum) # Driver codemat= [[2, 5, 7], [3, 7, 2], [5, 6, 9]] middlesum(mat, 3) # This code is contributed# by Anant Agarwal.
// C# program to find sum of// middle row and column in matrixusing System; class GFG { //static int MAX = 100; static void middlesum(int [,]mat, int n) { int row_sum = 0, col_sum = 0; // loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2, i]; Console.WriteLine ( "Sum of middle row = " + row_sum); // loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i, n / 2]; Console.WriteLine ( "Sum of middle column = " + col_sum); } // Driver function public static void Main () { int [,]mat = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); }} // This code is contributed by vt_m.
<?php// PHP program to find sum of// middle row and column in matrix function middlesum( $mat, $n){ $row_sum = 0; $col_sum = 0; //loop for sum of row for ( $i = 0; $i < $n; $i++) $row_sum += $mat[$n / 2][$i]; echo "Sum of middle row = " , $row_sum,"\n"; //loop for sum of column for ( $i = 0; $i < $n; $i++) $col_sum += $mat[$i][$n / 2]; echo "Sum of middle column = " , $col_sum;} // Driver function $mat = array(array(2, 5, 7), array(3, 7, 2), array(5, 6, 9)); middlesum($mat, 3); // This code is contributed by anuj_67.?>
<script> // Javascript program to find sum of// middle row and column in matrix var MAX = 100; function middlesum(mat , n) { var row_sum = 0, col_sum = 0; // loop for sum of row for (i = 0; i < n; i++) row_sum += mat[parseInt(n / 2)][i]; document.write( "Sum of middle row = " + row_sum+"<br/>" ); // loop for sum of column for (i = 0; i < n; i++) col_sum += mat[i][parseInt(n / 2)]; document.write( "Sum of middle column = " + col_sum ); } // Driver function var mat = [ [ 2, 5, 7 ], [ 3, 7, 2 ], [ 5, 6, 9 ] ]; middlesum(mat, 3); // This code contributed by aashish1995 </script>
Output:
Sum of middle row = 12
Sum of middle column = 18
Time Complexity : O(n) Auxiliary Space : O(1) using constant space to initialize row_sum and col_sum variables
vt_m
aashish1995
technophpfij
CBSE - Class 11
school-programming
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rat in a Maze | Backtracking-2
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Sudoku | Backtracking-7
Count all possible paths from top left to bottom right of a mXn matrix
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Inheritance in C++
Interfaces in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 193,
"s": 53,
"text": "Given an integer matrix of odd dimensions (3 * 3, 5 * 5). then the task is to find the sum of the middle row & column elements. Examples: "
},
{
"code": null,
"e": 468,
"s": 193,
"text": "Input : 2 5 7\n 3 7 2\n 5 6 9\nOutput : Sum of middle row = 12\n Sum of middle column = 18\n\nInput : 1 3 5 6 7\n 3 5 3 2 1\n 1 2 3 4 5\n 7 9 2 1 6\n 9 1 5 3 2\nOutput : Sum of middle row = 15\n Sum of middle column = 18"
},
{
"code": null,
"e": 476,
"s": 472,
"text": "CPP"
},
{
"code": null,
"e": 481,
"s": 476,
"text": "Java"
},
{
"code": null,
"e": 489,
"s": 481,
"text": "Python3"
},
{
"code": null,
"e": 492,
"s": 489,
"text": "C#"
},
{
"code": null,
"e": 496,
"s": 492,
"text": "PHP"
},
{
"code": null,
"e": 507,
"s": 496,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of// middle row and column in matrix#include <iostream>using namespace std;const int MAX = 100; void middlesum(int mat[][MAX], int n){ int row_sum = 0, col_sum = 0; //loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2][i]; cout << \"Sum of middle row = \" << row_sum<<endl; //loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i][n / 2]; cout << \"Sum of middle column = \" << col_sum;} // Driver functionint main(){ int mat[][MAX] = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); return 0;}",
"e": 1223,
"s": 507,
"text": null
},
{
"code": "// java program to find sum of// middle row and column in matrix import java.io.*; class GFG { static int MAX = 100; static void middlesum(int mat[][], int n){ int row_sum = 0, col_sum = 0; // loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2][i]; System.out.println ( \"Sum of middle row = \" + row_sum); // loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i][n / 2]; System.out.println ( \"Sum of middle column = \" + col_sum);} // Driver function public static void main (String[] args) { int mat[][] = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); }} // This code is contributed by vt_m.",
"e": 2020,
"s": 1223,
"text": null
},
{
"code": "# Python program to find sum of# middle row and column in matrix def middlesum(mat,n): row_sum = 0 col_sum = 0 # loop for sum of row for i in range(n): row_sum += mat[n // 2][i] print(\"Sum of middle row = \", row_sum) # loop for sum of column for i in range(n): col_sum += mat[i][n // 2] print(\"Sum of middle column = \", col_sum) # Driver codemat= [[2, 5, 7], [3, 7, 2], [5, 6, 9]] middlesum(mat, 3) # This code is contributed# by Anant Agarwal.",
"e": 2591,
"s": 2020,
"text": null
},
{
"code": "// C# program to find sum of// middle row and column in matrixusing System; class GFG { //static int MAX = 100; static void middlesum(int [,]mat, int n) { int row_sum = 0, col_sum = 0; // loop for sum of row for (int i = 0; i < n; i++) row_sum += mat[n / 2, i]; Console.WriteLine ( \"Sum of middle row = \" + row_sum); // loop for sum of column for (int i = 0; i < n; i++) col_sum += mat[i, n / 2]; Console.WriteLine ( \"Sum of middle column = \" + col_sum); } // Driver function public static void Main () { int [,]mat = {{2, 5, 7}, {3, 7, 2}, {5, 6, 9}}; middlesum(mat, 3); }} // This code is contributed by vt_m.",
"e": 3456,
"s": 2591,
"text": null
},
{
"code": "<?php// PHP program to find sum of// middle row and column in matrix function middlesum( $mat, $n){ $row_sum = 0; $col_sum = 0; //loop for sum of row for ( $i = 0; $i < $n; $i++) $row_sum += $mat[$n / 2][$i]; echo \"Sum of middle row = \" , $row_sum,\"\\n\"; //loop for sum of column for ( $i = 0; $i < $n; $i++) $col_sum += $mat[$i][$n / 2]; echo \"Sum of middle column = \" , $col_sum;} // Driver function $mat = array(array(2, 5, 7), array(3, 7, 2), array(5, 6, 9)); middlesum($mat, 3); // This code is contributed by anuj_67.?>",
"e": 4133,
"s": 3456,
"text": null
},
{
"code": "<script> // Javascript program to find sum of// middle row and column in matrix var MAX = 100; function middlesum(mat , n) { var row_sum = 0, col_sum = 0; // loop for sum of row for (i = 0; i < n; i++) row_sum += mat[parseInt(n / 2)][i]; document.write( \"Sum of middle row = \" + row_sum+\"<br/>\" ); // loop for sum of column for (i = 0; i < n; i++) col_sum += mat[i][parseInt(n / 2)]; document.write( \"Sum of middle column = \" + col_sum ); } // Driver function var mat = [ [ 2, 5, 7 ], [ 3, 7, 2 ], [ 5, 6, 9 ] ]; middlesum(mat, 3); // This code contributed by aashish1995 </script>",
"e": 4894,
"s": 4133,
"text": null
},
{
"code": null,
"e": 4904,
"s": 4894,
"text": "Output: "
},
{
"code": null,
"e": 4953,
"s": 4904,
"text": "Sum of middle row = 12\nSum of middle column = 18"
},
{
"code": null,
"e": 5065,
"s": 4953,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) using constant space to initialize row_sum and col_sum variables "
},
{
"code": null,
"e": 5070,
"s": 5065,
"text": "vt_m"
},
{
"code": null,
"e": 5082,
"s": 5070,
"text": "aashish1995"
},
{
"code": null,
"e": 5095,
"s": 5082,
"text": "technophpfij"
},
{
"code": null,
"e": 5111,
"s": 5095,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 5130,
"s": 5111,
"text": "school-programming"
},
{
"code": null,
"e": 5137,
"s": 5130,
"text": "Matrix"
},
{
"code": null,
"e": 5156,
"s": 5137,
"text": "School Programming"
},
{
"code": null,
"e": 5163,
"s": 5156,
"text": "Matrix"
},
{
"code": null,
"e": 5261,
"s": 5163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5292,
"s": 5261,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 5327,
"s": 5292,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 5371,
"s": 5327,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 5395,
"s": 5371,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 5466,
"s": 5395,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 5484,
"s": 5466,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5509,
"s": 5484,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5525,
"s": 5509,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5544,
"s": 5525,
"text": "Inheritance in C++"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.