title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python Program to find largest element in an array
|
04 Jan, 2018
Given an array, find the largest element in it.
Input : arr[] = {10, 20, 4}
Output : 20
Input : arr[] = {20, 10, 20, 4, 100}
Output : 100
# Python3 program to find maximum# in arr[] of size n # python function to find maximum# in arr[] of size ndef largest(arr,n): # Initialize maximum element max = arr[0] # Traverse array elements from second # and compare every element with # current max for i in range(1, n): if arr[i] > max: max = arr[i] return max # Driver Codearr = [10, 324, 45, 90, 9808]n = len(arr)Ans = largest(arr,n)print ("Largest in given array is",Ans) # This code is contributed by Smitha Dinesh Semwal
Please refer complete article on Program to find largest element in an array for more details!
ssaha3475
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jan, 2018"
},
{
"code": null,
"e": 100,
"s": 52,
"text": "Given an array, find the largest element in it."
},
{
"code": null,
"e": 192,
"s": 100,
"text": "Input : arr[] = {10, 20, 4}\nOutput : 20\n\nInput : arr[] = {20, 10, 20, 4, 100}\nOutput : 100\n"
},
{
"code": "# Python3 program to find maximum# in arr[] of size n # python function to find maximum# in arr[] of size ndef largest(arr,n): # Initialize maximum element max = arr[0] # Traverse array elements from second # and compare every element with # current max for i in range(1, n): if arr[i] > max: max = arr[i] return max # Driver Codearr = [10, 324, 45, 90, 9808]n = len(arr)Ans = largest(arr,n)print (\"Largest in given array is\",Ans) # This code is contributed by Smitha Dinesh Semwal",
"e": 722,
"s": 192,
"text": null
},
{
"code": null,
"e": 817,
"s": 722,
"text": "Please refer complete article on Program to find largest element in an array for more details!"
},
{
"code": null,
"e": 827,
"s": 817,
"text": "ssaha3475"
},
{
"code": null,
"e": 843,
"s": 827,
"text": "Python Programs"
}
] |
Java class dependency analyzer in Java 8 with Examples - GeeksforGeeks
|
29 Jan, 2020
Java class dependency analyzer: jdeps is a new command-line tool introduced in JDK 8 to understand the static dependencies and libraries of application i.e. jdeps command shows the package-level or class-level dependencies of Java class files. The input for jdeps can be a .class file pathname, a JAR file or it can be a fully qualified class name to analyze all class files. Whenever we provide any input to jdeps command line tool then it generates the dependencies to the system console. jdeps introduced with various options which affect the output. As per option, jdeps command-line tool generates the output.
Example:
// Simple Java program to see the jdeps// generated output with various options import java.util.List;import java.util.ArrayList; class Geeks { public static void main(String args[]) { List<String> list1 = new ArrayList<>(); List<String> list2 = new ArrayList<>(); List<String> list3 = new ArrayList<>(); list1.add("Geeks"); list2.add("for"); list3.add("geeks"); System.out.println(list1); System.out.println(list2); System.out.println(list3); }}
Note: We have to compile above Geeks.java file and compiler will generate Geeks.class file and We have to use this file as an input for jdeps. Here I am running with Java 9 and we will see the output of jdeps with different options for this Geeks.class file as per Java 9.
Output:
jdeps Geeks.class
Various options available for jdeps:
-dotoutput directoryPath: If we will use this option, then jdeps will generate one dot file into the directory per each analyzed archive named .dot listing the dependencies. It will also generate a summary file named summary.dot specifying the dependencies among the archives.Output:jdeps -dotoutput C:\Users\DubeyBis\Desktop\jdeps Geeks.classIt will generate two files inside C:\Users\DubeyBis\Desktop\jdeps folder with the name Geeks.class.dot and summary.dot and the content of these files are below:Geeks.class.dotdigraph "Geeks.class" {
// Path: Geeks.class
"" -> "java.io (java.base)";
"" -> "java.lang (java.base)";
"" -> "java.lang.invoke (java.base)";
"" -> "java.util (java.base)";
}
summary.dotdigraph "summary" {
"Geeks.class" -> "rt.jar";
}
Output:
jdeps -dotoutput C:\Users\DubeyBis\Desktop\jdeps Geeks.class
It will generate two files inside C:\Users\DubeyBis\Desktop\jdeps folder with the name Geeks.class.dot and summary.dot and the content of these files are below:
Geeks.class.dot
digraph "Geeks.class" {
// Path: Geeks.class
"" -> "java.io (java.base)";
"" -> "java.lang (java.base)";
"" -> "java.lang.invoke (java.base)";
"" -> "java.util (java.base)";
}
summary.dot
digraph "summary" {
"Geeks.class" -> "rt.jar";
}
-summary: It will print only the summary. Instead of -summary, we can use -s also.Output:jdeps -summary Geeks.class
Output:
jdeps -summary Geeks.class
-verbose: It will print all class-level dependencies. Instead of -verbose, we can use -v also.Output:jdeps -verbose Geeks.class
Output:
jdeps -verbose Geeks.class
-verbose:package: Prints package-level dependencies excluding dependencies within the same archive.
-verbose:class: Prints class-level dependencies excluding dependencies within the same archive.Output:jdeps -verbose:class Geeks.class
Output:
jdeps -verbose:class Geeks.class
Java 8
Java-Classes
Technical Scripter 2019
Java
Technical Scripter
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": "\n29 Jan, 2020"
},
{
"code": null,
"e": 24172,
"s": 23557,
"text": "Java class dependency analyzer: jdeps is a new command-line tool introduced in JDK 8 to understand the static dependencies and libraries of application i.e. jdeps command shows the package-level or class-level dependencies of Java class files. The input for jdeps can be a .class file pathname, a JAR file or it can be a fully qualified class name to analyze all class files. Whenever we provide any input to jdeps command line tool then it generates the dependencies to the system console. jdeps introduced with various options which affect the output. As per option, jdeps command-line tool generates the output."
},
{
"code": null,
"e": 24181,
"s": 24172,
"text": "Example:"
},
{
"code": "// Simple Java program to see the jdeps// generated output with various options import java.util.List;import java.util.ArrayList; class Geeks { public static void main(String args[]) { List<String> list1 = new ArrayList<>(); List<String> list2 = new ArrayList<>(); List<String> list3 = new ArrayList<>(); list1.add(\"Geeks\"); list2.add(\"for\"); list3.add(\"geeks\"); System.out.println(list1); System.out.println(list2); System.out.println(list3); }}",
"e": 24708,
"s": 24181,
"text": null
},
{
"code": null,
"e": 24981,
"s": 24708,
"text": "Note: We have to compile above Geeks.java file and compiler will generate Geeks.class file and We have to use this file as an input for jdeps. Here I am running with Java 9 and we will see the output of jdeps with different options for this Geeks.class file as per Java 9."
},
{
"code": null,
"e": 24989,
"s": 24981,
"text": "Output:"
},
{
"code": null,
"e": 25007,
"s": 24989,
"text": "jdeps Geeks.class"
},
{
"code": null,
"e": 25044,
"s": 25007,
"text": "Various options available for jdeps:"
},
{
"code": null,
"e": 25892,
"s": 25044,
"text": "-dotoutput directoryPath: If we will use this option, then jdeps will generate one dot file into the directory per each analyzed archive named .dot listing the dependencies. It will also generate a summary file named summary.dot specifying the dependencies among the archives.Output:jdeps -dotoutput C:\\Users\\DubeyBis\\Desktop\\jdeps Geeks.classIt will generate two files inside C:\\Users\\DubeyBis\\Desktop\\jdeps folder with the name Geeks.class.dot and summary.dot and the content of these files are below:Geeks.class.dotdigraph \"Geeks.class\" {\n // Path: Geeks.class\n \"\" -> \"java.io (java.base)\";\n \"\" -> \"java.lang (java.base)\";\n \"\" -> \"java.lang.invoke (java.base)\";\n \"\" -> \"java.util (java.base)\";\n}\nsummary.dotdigraph \"summary\" {\n \"Geeks.class\" -> \"rt.jar\";\n}\n"
},
{
"code": null,
"e": 25900,
"s": 25892,
"text": "Output:"
},
{
"code": null,
"e": 25961,
"s": 25900,
"text": "jdeps -dotoutput C:\\Users\\DubeyBis\\Desktop\\jdeps Geeks.class"
},
{
"code": null,
"e": 26122,
"s": 25961,
"text": "It will generate two files inside C:\\Users\\DubeyBis\\Desktop\\jdeps folder with the name Geeks.class.dot and summary.dot and the content of these files are below:"
},
{
"code": null,
"e": 26138,
"s": 26122,
"text": "Geeks.class.dot"
},
{
"code": null,
"e": 26399,
"s": 26138,
"text": "digraph \"Geeks.class\" {\n // Path: Geeks.class\n \"\" -> \"java.io (java.base)\";\n \"\" -> \"java.lang (java.base)\";\n \"\" -> \"java.lang.invoke (java.base)\";\n \"\" -> \"java.util (java.base)\";\n}\n"
},
{
"code": null,
"e": 26411,
"s": 26399,
"text": "summary.dot"
},
{
"code": null,
"e": 26470,
"s": 26411,
"text": "digraph \"summary\" {\n \"Geeks.class\" -> \"rt.jar\";\n}\n"
},
{
"code": null,
"e": 26586,
"s": 26470,
"text": "-summary: It will print only the summary. Instead of -summary, we can use -s also.Output:jdeps -summary Geeks.class"
},
{
"code": null,
"e": 26594,
"s": 26586,
"text": "Output:"
},
{
"code": null,
"e": 26621,
"s": 26594,
"text": "jdeps -summary Geeks.class"
},
{
"code": null,
"e": 26749,
"s": 26621,
"text": "-verbose: It will print all class-level dependencies. Instead of -verbose, we can use -v also.Output:jdeps -verbose Geeks.class"
},
{
"code": null,
"e": 26757,
"s": 26749,
"text": "Output:"
},
{
"code": null,
"e": 26784,
"s": 26757,
"text": "jdeps -verbose Geeks.class"
},
{
"code": null,
"e": 26884,
"s": 26784,
"text": "-verbose:package: Prints package-level dependencies excluding dependencies within the same archive."
},
{
"code": null,
"e": 27019,
"s": 26884,
"text": "-verbose:class: Prints class-level dependencies excluding dependencies within the same archive.Output:jdeps -verbose:class Geeks.class"
},
{
"code": null,
"e": 27027,
"s": 27019,
"text": "Output:"
},
{
"code": null,
"e": 27060,
"s": 27027,
"text": "jdeps -verbose:class Geeks.class"
},
{
"code": null,
"e": 27067,
"s": 27060,
"text": "Java 8"
},
{
"code": null,
"e": 27080,
"s": 27067,
"text": "Java-Classes"
},
{
"code": null,
"e": 27104,
"s": 27080,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 27109,
"s": 27104,
"text": "Java"
},
{
"code": null,
"e": 27128,
"s": 27109,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27133,
"s": 27128,
"text": "Java"
},
{
"code": null,
"e": 27231,
"s": 27133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27240,
"s": 27231,
"text": "Comments"
},
{
"code": null,
"e": 27253,
"s": 27240,
"text": "Old Comments"
},
{
"code": null,
"e": 27283,
"s": 27253,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27298,
"s": 27283,
"text": "Stream In Java"
},
{
"code": null,
"e": 27319,
"s": 27298,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27365,
"s": 27319,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27384,
"s": 27365,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27401,
"s": 27384,
"text": "Generics in Java"
},
{
"code": null,
"e": 27444,
"s": 27401,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27460,
"s": 27444,
"text": "Strings in Java"
},
{
"code": null,
"e": 27509,
"s": 27460,
"text": "How to remove an element from ArrayList in Java?"
}
] |
Count natural numbers whose factorials are divisible by x but not y - GeeksforGeeks
|
26 Mar, 2021
Given two numbers x and y (x <= y), find out the total number of natural numbers, say i, for which i! is divisible by x but not y. Examples :
Input : x = 2, y = 5
Output : 3
There are three numbers, 2, 3 and 4
whose factorials are divisible by x
but not y.
Input: x = 15, y = 25
Output: 5
5! = 120 % 15 = 0 && 120 % 25 != 0
6! = 720 % 15 = 0 && 720 % 25 != 0
7! = 5040 % 15 = 0 && 5040 % 25 != 0
8! = 40320 % 15 = 0 && 40320 % 25 != 0
9! = 362880 % 15 = 0 && 362880 % 25 != 0
So total count = 5
Input: x = 10, y = 15
Output: 0
For all numbers greater than or equal to y, their factorials are divisible by y. So all natural numbers to be counted must be less than y.A simple solution is to iterate from 1 to y-1 and for every number i check if i! is divisible by x and not divisible by y. If we apply this naive approach, we wouldn’t go above 20! or 21! (long long int will have its upper limit) A better solution is based on below post. Find the first natural number whose factorial is divisible by x We find the first natural numbers whose factorials are divisible by x! and y! using above approach. Let the first natural numbers whose factorials are divisible by x and y be xf and yf respectively. Our final answer would be yf – xf. This formula is based on the fact that if i! is divisible by a number x, then (i+1)!, (i+2)!, ... are also divisible by x.Below is the implementation.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count natural numbers whose// factorials are divisible by x but not y.#include<bits/stdc++.h>using namespace std; // GCD function to compute the greatest// divisor among a and bint gcd(int a, int b){ if ((a % b) == 0) return b; return gcd(b, a % b);} // Returns first number whose factorial// is divisible by x.int firstFactorialDivisibleNumber(int x){ int i = 1; // Result int new_x = x; for (i=1; i<x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i;} // Count of natural numbers whose factorials// are divisible by x but not y.int countFactorialXNotY(int x, int y){ // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x));} // Driver codeint main(void){ int x = 15, y = 25; cout << countFactorialXNotY(x, y); return 0;}
// Java program to count natural numbers whose// factorials are divisible by x but not y. class GFG{ // GCD function to compute the greatest // divisor among a and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // is divisible by x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Count of natural numbers whose factorials // are divisible by x but not y. static int countFactorialXNotY(int x, int y) { // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)); } // Driver code public static void main (String[] args) { int x = 15, y = 25; System.out.print(countFactorialXNotY(x, y)); }} // This code is contributed by Anant Agarwal.
# Python program to count natural# numbers whose factorials are# divisible by x but not y. # GCD function to compute the greatest# divisor among a and bdef gcd(a, b): if ((a % b) == 0): return b return gcd(b, a % b) # Returns first number whose factorial# is divisible by x.def firstFactorialDivisibleNumber(x): # Result i = 1 new_x = x for i in range(1, x): # Remove common factors new_x /= gcd(i, new_x) # We found first i. if (new_x == 1): break return i # Count of natural numbers whose# factorials are divisible by x but# not y.def countFactorialXNotY(x, y): # Return difference between first # natural number whose factorial # is divisible by y and first # natural number whose factorial # is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)) # Driver codex = 15y = 25 print(countFactorialXNotY(x, y)) # This code is contributed by Anant Agarwal.
// C# program to count natural numbers whose// factorials are divisible by x but not y.using System; class GFG{ // GCD function to compute the greatest // divisor among a and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // is divisible by x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Count of natural numbers whose factorials // are divisible by x but not y. static int countFactorialXNotY(int x, int y) { // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)); } // Driver code public static void Main () { int x = 15, y = 25; Console.Write(countFactorialXNotY(x, y)); }} // This code is contributed by nitin mittal.
<?php// PHP program to count natural// numbers whose factorials are// divisible by x but not y. // GCD function to compute the// greatest divisor among a and bfunction gcd($a, $b){ if (($a % $b) == 0) return $b; return gcd($b, $a % $b);} // Returns first number whose// factorial is divisible by x.function firstFactorialDivisibleNumber($x){ // Result $i = 1; $new_x = $x; for ($i = 1; $i < $x; $i++) { // Remove common factors $new_x /= gcd($i, $new_x); // We found first i. if ($new_x == 1) break; } return $i;} // Count of natural numbers// whose factorials are divisible// by x but not y.function countFactorialXNotY($x, $y){ // Return difference between // first natural number whose // factorial is divisible by // y and first natural number // whose factorial is divisible by x. return (firstFactorialDivisibleNumber($y) - firstFactorialDivisibleNumber($x));} // Driver code$x = 15; $y = 25;echo(countFactorialXNotY($x, $y)); // This code is contributed by Ajit.?>
<script> // Javascript program to Merge two sorted halves of// array Into Single Sorted Array // GCD function to compute the greatest // divisor among a and b function gcd(a, b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // is divisible by x. function firstFactorialDivisibleNumber(x) { let i = 1; // Result let new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Count of natural numbers whose factorials // are divisible by x but not y. function countFactorialXNotY(x, y) { // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)); } // Driver code let x = 15, y = 25; document.write(countFactorialXNotY(x, y)); </script>
Output :
5
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to 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.
nitin mittal
jit_t
ManasChhabra2
splevel62
divisibility
factorial
GCD-LCM
Mathematical
Mathematical
factorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Modulo Operator (%) in C/C++ with Examples
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Merge two sorted arrays
Euclidean algorithms (Basic and Extended)
Modular multiplicative inverse
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 25179,
"s": 25151,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 25323,
"s": 25179,
"text": "Given two numbers x and y (x <= y), find out the total number of natural numbers, say i, for which i! is divisible by x but not y. Examples : "
},
{
"code": null,
"e": 25710,
"s": 25323,
"text": "Input : x = 2, y = 5\nOutput : 3\nThere are three numbers, 2, 3 and 4\nwhose factorials are divisible by x\nbut not y.\n\nInput: x = 15, y = 25\nOutput: 5\n5! = 120 % 15 = 0 && 120 % 25 != 0\n6! = 720 % 15 = 0 && 720 % 25 != 0\n7! = 5040 % 15 = 0 && 5040 % 25 != 0\n8! = 40320 % 15 = 0 && 40320 % 25 != 0\n9! = 362880 % 15 = 0 && 362880 % 25 != 0\nSo total count = 5\n\nInput: x = 10, y = 15\nOutput: 0"
},
{
"code": null,
"e": 26573,
"s": 25712,
"text": "For all numbers greater than or equal to y, their factorials are divisible by y. So all natural numbers to be counted must be less than y.A simple solution is to iterate from 1 to y-1 and for every number i check if i! is divisible by x and not divisible by y. If we apply this naive approach, we wouldn’t go above 20! or 21! (long long int will have its upper limit) A better solution is based on below post. Find the first natural number whose factorial is divisible by x We find the first natural numbers whose factorials are divisible by x! and y! using above approach. Let the first natural numbers whose factorials are divisible by x and y be xf and yf respectively. Our final answer would be yf – xf. This formula is based on the fact that if i! is divisible by a number x, then (i+1)!, (i+2)!, ... are also divisible by x.Below is the implementation. "
},
{
"code": null,
"e": 26577,
"s": 26573,
"text": "C++"
},
{
"code": null,
"e": 26582,
"s": 26577,
"text": "Java"
},
{
"code": null,
"e": 26590,
"s": 26582,
"text": "Python3"
},
{
"code": null,
"e": 26593,
"s": 26590,
"text": "C#"
},
{
"code": null,
"e": 26597,
"s": 26593,
"text": "PHP"
},
{
"code": null,
"e": 26608,
"s": 26597,
"text": "Javascript"
},
{
"code": "// C++ program to count natural numbers whose// factorials are divisible by x but not y.#include<bits/stdc++.h>using namespace std; // GCD function to compute the greatest// divisor among a and bint gcd(int a, int b){ if ((a % b) == 0) return b; return gcd(b, a % b);} // Returns first number whose factorial// is divisible by x.int firstFactorialDivisibleNumber(int x){ int i = 1; // Result int new_x = x; for (i=1; i<x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i;} // Count of natural numbers whose factorials// are divisible by x but not y.int countFactorialXNotY(int x, int y){ // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x));} // Driver codeint main(void){ int x = 15, y = 25; cout << countFactorialXNotY(x, y); return 0;}",
"e": 27682,
"s": 26608,
"text": null
},
{
"code": "// Java program to count natural numbers whose// factorials are divisible by x but not y. class GFG{ // GCD function to compute the greatest // divisor among a and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // is divisible by x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Count of natural numbers whose factorials // are divisible by x but not y. static int countFactorialXNotY(int x, int y) { // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)); } // Driver code public static void main (String[] args) { int x = 15, y = 25; System.out.print(countFactorialXNotY(x, y)); }} // This code is contributed by Anant Agarwal.",
"e": 29021,
"s": 27682,
"text": null
},
{
"code": "# Python program to count natural# numbers whose factorials are# divisible by x but not y. # GCD function to compute the greatest# divisor among a and bdef gcd(a, b): if ((a % b) == 0): return b return gcd(b, a % b) # Returns first number whose factorial# is divisible by x.def firstFactorialDivisibleNumber(x): # Result i = 1 new_x = x for i in range(1, x): # Remove common factors new_x /= gcd(i, new_x) # We found first i. if (new_x == 1): break return i # Count of natural numbers whose# factorials are divisible by x but# not y.def countFactorialXNotY(x, y): # Return difference between first # natural number whose factorial # is divisible by y and first # natural number whose factorial # is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)) # Driver codex = 15y = 25 print(countFactorialXNotY(x, y)) # This code is contributed by Anant Agarwal.",
"e": 30065,
"s": 29021,
"text": null
},
{
"code": "// C# program to count natural numbers whose// factorials are divisible by x but not y.using System; class GFG{ // GCD function to compute the greatest // divisor among a and b static int gcd(int a, int b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // is divisible by x. static int firstFactorialDivisibleNumber(int x) { int i = 1; // Result int new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Count of natural numbers whose factorials // are divisible by x but not y. static int countFactorialXNotY(int x, int y) { // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)); } // Driver code public static void Main () { int x = 15, y = 25; Console.Write(countFactorialXNotY(x, y)); }} // This code is contributed by nitin mittal.",
"e": 31443,
"s": 30065,
"text": null
},
{
"code": "<?php// PHP program to count natural// numbers whose factorials are// divisible by x but not y. // GCD function to compute the// greatest divisor among a and bfunction gcd($a, $b){ if (($a % $b) == 0) return $b; return gcd($b, $a % $b);} // Returns first number whose// factorial is divisible by x.function firstFactorialDivisibleNumber($x){ // Result $i = 1; $new_x = $x; for ($i = 1; $i < $x; $i++) { // Remove common factors $new_x /= gcd($i, $new_x); // We found first i. if ($new_x == 1) break; } return $i;} // Count of natural numbers// whose factorials are divisible// by x but not y.function countFactorialXNotY($x, $y){ // Return difference between // first natural number whose // factorial is divisible by // y and first natural number // whose factorial is divisible by x. return (firstFactorialDivisibleNumber($y) - firstFactorialDivisibleNumber($x));} // Driver code$x = 15; $y = 25;echo(countFactorialXNotY($x, $y)); // This code is contributed by Ajit.?>",
"e": 32527,
"s": 31443,
"text": null
},
{
"code": "<script> // Javascript program to Merge two sorted halves of// array Into Single Sorted Array // GCD function to compute the greatest // divisor among a and b function gcd(a, b) { if ((a % b) == 0) return b; return gcd(b, a % b); } // Returns first number whose factorial // is divisible by x. function firstFactorialDivisibleNumber(x) { let i = 1; // Result let new_x = x; for (i = 1; i < x; i++) { // Remove common factors new_x /= gcd(i, new_x); // We found first i. if (new_x == 1) break; } return i; } // Count of natural numbers whose factorials // are divisible by x but not y. function countFactorialXNotY(x, y) { // Return difference between first natural // number whose factorial is divisible by // y and first natural number whose factorial // is divisible by x. return (firstFactorialDivisibleNumber(y) - firstFactorialDivisibleNumber(x)); } // Driver code let x = 15, y = 25; document.write(countFactorialXNotY(x, y)); </script>",
"e": 33775,
"s": 32527,
"text": null
},
{
"code": null,
"e": 33785,
"s": 33775,
"text": "Output : "
},
{
"code": null,
"e": 33787,
"s": 33785,
"text": "5"
},
{
"code": null,
"e": 34213,
"s": 33787,
"text": "This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to 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": 34226,
"s": 34213,
"text": "nitin mittal"
},
{
"code": null,
"e": 34232,
"s": 34226,
"text": "jit_t"
},
{
"code": null,
"e": 34246,
"s": 34232,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 34256,
"s": 34246,
"text": "splevel62"
},
{
"code": null,
"e": 34269,
"s": 34256,
"text": "divisibility"
},
{
"code": null,
"e": 34279,
"s": 34269,
"text": "factorial"
},
{
"code": null,
"e": 34287,
"s": 34279,
"text": "GCD-LCM"
},
{
"code": null,
"e": 34300,
"s": 34287,
"text": "Mathematical"
},
{
"code": null,
"e": 34313,
"s": 34300,
"text": "Mathematical"
},
{
"code": null,
"e": 34323,
"s": 34313,
"text": "factorial"
},
{
"code": null,
"e": 34421,
"s": 34323,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34430,
"s": 34421,
"text": "Comments"
},
{
"code": null,
"e": 34443,
"s": 34430,
"text": "Old Comments"
},
{
"code": null,
"e": 34492,
"s": 34443,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 34535,
"s": 34492,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 34578,
"s": 34535,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 34610,
"s": 34578,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 34634,
"s": 34610,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 34676,
"s": 34634,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 34707,
"s": 34676,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 34729,
"s": 34707,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 34771,
"s": 34729,
"text": "Program to find GCD or HCF of two numbers"
}
] |
Squares in N*N Chessboard | Practice | GeeksforGeeks
|
Find total number of Squares in a N*N cheesboard.
Example 1:
Input:
N = 1
Output:
1
Explanation:
A 1*1 chessboard has only 1 square.
Example 2:
Input:
N = 2
Output:
5
Explanation:
A 2*2 chessboard has 5 squares.
4 1*1 squares and a 2*2 square.
Your Task:
You don't need to read input or print anything. Your task is to complete the function squaresInChessBoard() which takes an Integer N as input and returns the number of squares in a N*N chessboard.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
+1
princejee20192 months ago
C++ CODE || EASY TO UNDERSTAND
class Solution { public: long long squaresInChessBoard(long long n) { long long sum=n*(n+1)*(2*n+1)/6; return sum; }};
0
abhya972 months ago
// Simple C++ solution
class Solution { public: long long squaresInChessBoard(long long N) { long long squ = 0; while(N!=0) { squ = squ + (N * N); N--; } return squ; }};
+2
asit1234kumar32193 months ago
One Liner code, mathematical series formula approach
return N*(N+1)*(2*N+1)/6;
0
shubham9063 months ago
// BY recursion
if(N==1) return (long)1; return N*N + squaresInChessBoard(N-1);
+1
vravikant813 months ago
class Solution { public: long long squaresInChessBoard(long long N) { // code here long long square=0,n=N+1; while(n--) square+=n*n; return square; }};
+1
sejalbkadamdhad3 months ago
// C++ Solution:-
long long squaresInChessBoard(long long N) { // code here long long sum=0; long long i; for(i=1;i<=N;i++) { sum=sum+i*i; } return sum; }
0
dishasarna20014 months ago
Expected Time Complexity: O(1)Expected Auxiliary Space: O(1)//C++ Solution
class Solution { public: long long squaresInChessBoard(long long N) { // code here return (N*(N+1)*(2*N+1))/6; }};
0
gouravmodi104 months ago
o(1) time & space
long long squaresInChessBoard(long long n) {
return (n*(n+1)*(2*n+1))/6;
}
0
arish824 months ago
long long squaresInChessBoard(long long N) {
long long ans=N*(N+1)*(2*N+1)/6;
return ans;
}
0
manishdoley234 months ago
Simple C++ solution
class Solution {
public:
long long squaresInChessBoard(long long N) {
// code here
long long sum = 0;
if(N==1) return 1;
while(N!=0){
sum += N*N;
N--;
}
return sum;
}
};
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": 288,
"s": 238,
"text": "Find total number of Squares in a N*N cheesboard."
},
{
"code": null,
"e": 301,
"s": 290,
"text": "Example 1:"
},
{
"code": null,
"e": 373,
"s": 301,
"text": "Input:\nN = 1\nOutput:\n1\nExplanation:\nA 1*1 chessboard has only 1 square."
},
{
"code": null,
"e": 384,
"s": 373,
"text": "Example 2:"
},
{
"code": null,
"e": 485,
"s": 384,
"text": "Input:\nN = 2\nOutput:\n5\nExplanation:\nA 2*2 chessboard has 5 squares.\n4 1*1 squares and a 2*2 square.\n"
},
{
"code": null,
"e": 695,
"s": 487,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function squaresInChessBoard() which takes an Integer N as input and returns the number of squares in a N*N chessboard."
},
{
"code": null,
"e": 759,
"s": 697,
"text": "Expected Time Complexity: O(1)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 788,
"s": 761,
"text": "Constraints:\n1 <= N <= 105"
},
{
"code": null,
"e": 791,
"s": 788,
"text": "+1"
},
{
"code": null,
"e": 817,
"s": 791,
"text": "princejee20192 months ago"
},
{
"code": null,
"e": 848,
"s": 817,
"text": "C++ CODE || EASY TO UNDERSTAND"
},
{
"code": null,
"e": 983,
"s": 848,
"text": "class Solution { public: long long squaresInChessBoard(long long n) { long long sum=n*(n+1)*(2*n+1)/6; return sum; }};"
},
{
"code": null,
"e": 985,
"s": 983,
"text": "0"
},
{
"code": null,
"e": 1005,
"s": 985,
"text": "abhya972 months ago"
},
{
"code": null,
"e": 1028,
"s": 1005,
"text": "// Simple C++ solution"
},
{
"code": null,
"e": 1252,
"s": 1028,
"text": "class Solution { public: long long squaresInChessBoard(long long N) { long long squ = 0; while(N!=0) { squ = squ + (N * N); N--; } return squ; }};"
},
{
"code": null,
"e": 1255,
"s": 1252,
"text": "+2"
},
{
"code": null,
"e": 1285,
"s": 1255,
"text": "asit1234kumar32193 months ago"
},
{
"code": null,
"e": 1339,
"s": 1285,
"text": "One Liner code, mathematical series formula approach "
},
{
"code": null,
"e": 1365,
"s": 1339,
"text": "return N*(N+1)*(2*N+1)/6;"
},
{
"code": null,
"e": 1367,
"s": 1365,
"text": "0"
},
{
"code": null,
"e": 1390,
"s": 1367,
"text": "shubham9063 months ago"
},
{
"code": null,
"e": 1406,
"s": 1390,
"text": "// BY recursion"
},
{
"code": null,
"e": 1484,
"s": 1408,
"text": "if(N==1) return (long)1; return N*N + squaresInChessBoard(N-1);"
},
{
"code": null,
"e": 1487,
"s": 1484,
"text": "+1"
},
{
"code": null,
"e": 1511,
"s": 1487,
"text": "vravikant813 months ago"
},
{
"code": null,
"e": 1697,
"s": 1511,
"text": "class Solution { public: long long squaresInChessBoard(long long N) { // code here long long square=0,n=N+1; while(n--) square+=n*n; return square; }};"
},
{
"code": null,
"e": 1700,
"s": 1697,
"text": "+1"
},
{
"code": null,
"e": 1728,
"s": 1700,
"text": "sejalbkadamdhad3 months ago"
},
{
"code": null,
"e": 1746,
"s": 1728,
"text": "// C++ Solution:-"
},
{
"code": null,
"e": 1937,
"s": 1746,
"text": "long long squaresInChessBoard(long long N) { // code here long long sum=0; long long i; for(i=1;i<=N;i++) { sum=sum+i*i; } return sum; }"
},
{
"code": null,
"e": 1939,
"s": 1937,
"text": "0"
},
{
"code": null,
"e": 1966,
"s": 1939,
"text": "dishasarna20014 months ago"
},
{
"code": null,
"e": 2041,
"s": 1966,
"text": "Expected Time Complexity: O(1)Expected Auxiliary Space: O(1)//C++ Solution"
},
{
"code": null,
"e": 2175,
"s": 2043,
"text": "class Solution { public: long long squaresInChessBoard(long long N) { // code here return (N*(N+1)*(2*N+1))/6; }}; "
},
{
"code": null,
"e": 2177,
"s": 2175,
"text": "0"
},
{
"code": null,
"e": 2202,
"s": 2177,
"text": "gouravmodi104 months ago"
},
{
"code": null,
"e": 2224,
"s": 2202,
"text": " o(1) time & space"
},
{
"code": null,
"e": 2311,
"s": 2224,
"text": "long long squaresInChessBoard(long long n) {\n return (n*(n+1)*(2*n+1))/6;\n }"
},
{
"code": null,
"e": 2313,
"s": 2311,
"text": "0"
},
{
"code": null,
"e": 2333,
"s": 2313,
"text": "arish824 months ago"
},
{
"code": null,
"e": 2442,
"s": 2333,
"text": "long long squaresInChessBoard(long long N) {\n long long ans=N*(N+1)*(2*N+1)/6;\n return ans;\n }"
},
{
"code": null,
"e": 2444,
"s": 2442,
"text": "0"
},
{
"code": null,
"e": 2470,
"s": 2444,
"text": "manishdoley234 months ago"
},
{
"code": null,
"e": 2490,
"s": 2470,
"text": "Simple C++ solution"
},
{
"code": null,
"e": 2742,
"s": 2490,
"text": "class Solution {\n public:\n long long squaresInChessBoard(long long N) {\n // code here\n long long sum = 0;\n if(N==1) return 1;\n while(N!=0){\n sum += N*N;\n N--;\n }\n return sum;\n }\n};"
},
{
"code": null,
"e": 2888,
"s": 2742,
"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": 2924,
"s": 2888,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2934,
"s": 2924,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2944,
"s": 2934,
"text": "\nContest\n"
},
{
"code": null,
"e": 3007,
"s": 2944,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3155,
"s": 3007,
"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": 3363,
"s": 3155,
"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": 3469,
"s": 3363,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Create Chatbot using Rasa Part-1. Rasa is an open source machine learning... | by Bikash Sundaray | Towards Data Science
|
Rasa is an open source machine learning framework for building AI assistants and chatbots. Mostly you don’t need any programming language experience to work in Rasa. Although there is something called “Rasa Action Server” where you need to write code in Python, that mainly used to trigger External actions like Calling Google API or REST API etc.
Rasa has two main modules:
Rasa NLU for understanding user messagesRasa Core for holding conversations and deciding what to do next
Rasa NLU for understanding user messages
Rasa Core for holding conversations and deciding what to do next
Note — Now Rasa NLU and Rasa Core source code are merged together.
Rasa X is a tool that helps you build, improve, and deploy AI Assistants that are powered by the Rasa framework. Rasa X includes a user interface and a REST API. Rasa X is the latest release from Rasa.
About me: I am official Rasa Contributor.
Rasa X — It’s a Browser based GUI tool which will allow you to train Machine learning model by using GUI based interactive mode. Remember it’s an optional tool in Rasa Software Stack. Sometimes Rasa sends usage statistics information from your browser to rasa — but it never sends training data to outside of your system, it just sends how many times you are using Rasa X Train.
Rasa NLU — This is the place, where rasa tries to understand User messages to detect Intent and Entity in your message. Rasa NLU has different components for recognizing intents and entities, most of which have some additional dependencies.
Spacy (You need to install it separately)Tensorflow (By Default available with Rasa)
Spacy (You need to install it separately)
Tensorflow (By Default available with Rasa)
Rasa Core — This is the place, where Rasa try to help you with contextual message flow. Based on User message, it can predict dialogue as a reply and can trigger Rasa Action Server.
Rasa internally uses Tensorflow, whenever you do “pip install rasa” or “pip install rasa-x”, by default it installs Tensorflow.
Ubuntu 16+, Mac OS and Windows 10 (Visual C++ Build tool)
Note: In case you are working on windows, make sure you have installed the Visual c++ build tool. This is required for some python packages. Definitely use miniconda to avoid the issue with other installed Python packages in your system or conflicting Python Version.
Install MiniConda (Part of Anaconda) in your OS
conda.io
After installing miniconda, Follow below commands to create a virtual environment in conda. This will allow you to run Rasa without errors.
conda install python=3.6conda create -n rasa python=3.6source activate rasapip install rasa-x --extra-index-url https://pypi.rasa.com/simple
By following the above command, both Rasa and Rasa X will be installed in your system.
Open Terminal and activate Conda Virtual Environment. Now go-to one directory and do “rasa init”, it will create a Rasa Project at that location. “rasa x” will start the Rasa X application
source activate rasarasa init
“rasa init” should show above message, in-case you are doing well and your system doesn’t contain any error. Follow the interactive session and continue pressing enter to reach the last step. In the end, it should show this message.
If you do “ls -la” in a terminal, you can see a list of files which are created by Rasa. Now do “rasa x” to start Rasa.
Let me explain about files, which are created as Initial project structure of Rasa.
__init__.pyan empty file that helps python find your actions
actions.pycode for your custom actions. In-case you want Rasa to call external server via REST API or API call, you can define your Custom Actions here. Remember you can create multiple Python Script for Rasa Custom Action.
config.yml ‘*’configuration of your NLU and Core models. In-case you are dealing with Tensorflow or Spacy, you need to define such pipeline here. To handle this file, you show know about Machine Learning and Deep Learning.
credentials.ymldetails for connecting to other services. In case you want to build Bot on Facebook Messenger, Microsoft Bot Framework, you can maintain such credential and token here. So basically you just need to add Facebook, slack and Bot framework related configuration, rasa will automatically do rest for you. Remember that you need to host Rasa over https domain. During development, you can use ngrok as a testing tool.
data/nlu.md ‘*’your NLU training data. Here you can define Intent. Like Order Pizza or Book Uber. You need to add related Sentences for that Intent. Remember if you are using Rasa-X, your training Intent and Data will be added automatically.
data/stories.md ‘*’your stories. This is required for Rasa Core. There is something called “Dialog Flow in Rasa” where Rasa Core controls the flow of the conversation between you and chatbot, so for that flow, you need to train chatbot using these stories. So in case you want your chatbot to be very perfect on different context (stories) you can add those stories here.
domain.yml ‘*’your assistant’s domain. This file combines Different Intent which chatbot can detect and list of Bot replies. Remember you can define your Custom Action Server Python method name here (in underscore format), so that Rasa will call that python method for you.
endpoints.ymldetails for connecting to channels like FB messenger. This is mainly used for production setup. You can configure your Database like Redis so that Rasa can store tracking information.
models/<timestamp>.tar.gzyour initial model
Rasa created a sample Bot for you with default data. So now you can start using it from Shell/Terminal. As a starting point let’s test your Chatbot from a terminal (remember to do this in Terminal)
rasa shell
You can type “hi” and in reply from bot, you will receive some response.
This is the newest addition to Rasa Stack. You can user Rasa-X to Try your chatbot on Browser. You can download training Data. Also, you can correct your training data by guiding your Bot.
rasa x
It will ask for the license Agreement, you can say “y” and proceed.
Open this link on Browser — http://localhost:5002/talk
In the left side, you can try to chat with your bot and on the right side you can see, which intent and reply is getting responded.
Some facts about Rasa-x
When you run Rasa X locally, your training data and stories are read from the files in your project (e.g. data/nlu.md), and any changes you make in the UI are saved back to those files. Conversations and other data are stored in an SQLite database saved in a file called rasa.db.
Watch this video to learn more about Rasa-X
This is the most real-world example of your chatbot. Suppose in your chatbot you want to add a feature where your bot can tell you latest weather report of a specified city, how you will do it? The answer is “Rasa Custom Action”
An action can run any code you want. Custom actions can turn on the lights, add an event to a calendar, check a user’s bank balance, or anything else you can imagine.
Rasa will call an endpoint you can specify when a custom action is predicted. This endpoint should be a web server that reacts to this call, runs the code and optionally returns information to modify the dialogue state.
Open “actions.py” in Editor (Visual Studio Code can be an option)
Step-1 — Define a Method called “ActionCheckWeather” in “actions.py”
from rasa_sdk import Actionfrom rasa_sdk.events import SlotSetclass ActionCheckWeather(Action): def name(self) -> Text: return "action_check_weather" def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message("Hello World! from custom action") return []
Step-2 — Link this custom action with your Chatbot. Open “domain.yml”.
Add “action_check_weather” action in the list of the action. This should look like this
actions:- utter_greet- utter_cheer_up- utter_did_that_help- utter_happy- utter_goodbye- action_check_weather
Now in the stories, add this custom action as your flow. Open “stories.md” file and this new custom action “action_check_weather” as part of happy path flow.
## happy path* greet- utter_greet* mood_great- action_check_weather
Step-3 Tell rasa to use Custom Action Server
Open “endpoints.yml” and add the following line to enable custom action server
action_endpoint: url: "http://localhost:5055/webhook"
Now Re-train your Rasa Chatbot using following command. You need to retrain your machine learning model because you made some changes in “stories.md” and “domain.yml” file. So without re-train, you can’t inform Rasa to use those.
rasa train
Now start Rasa again using
rasa x
Also, start Rasa Action server using the following command. Rasa X and Rasa run actions should run in 2 different terminals.
rasa run actions
You can see, you are getting a reply from custom action which is written in python. In the same python script, you can connect to your backend database and return a response. Also, you can call an external API using additional python packages.
Also, you can develop Custom action Server in C#, NodeJS and Java.
You can build a Chatbot GUI using HTML5 and CSS3. You can use the Library like ReactJS and JQuery. If you want you can use Angular as your frontend JavaScript framework to build Frontend for your Chatbot.
Build GUI in HTML5 and CSS3Call Rasa Rest API from your frontendThat’s it
Build GUI in HTML5 and CSS3
Call Rasa Rest API from your frontend
That’s it
Sample API call from JavaScript to Rasa Backend
As we are heading towards building production-grade Rasa Chatbot setup, the first thing we can simply use the following command to start Rasa.
rasa run
Above command will run Rasa Core and Expose REST API on port 5005.
URL: http://localhost:5005/webhooks/rest/webhookMethod: POSTHeader: Content-Type: application/jsonBody:{ “sender”: “Rasa1”, “message”: “hi”}Response:[ { “recipient_id”: “Rasa1”, “text”: “Hey! How are you?” }]
Now you can parse this response in your frontend application and show this response to the user. Remember Rasa will track your conversation based on a unique id called “Rasa1” which we have passed in the Request body.
In the next part of this Article, we will learn about
Rasa SlotRasa Using DockerRasa-X advanceRasa Production Deployment
Rasa Slot
Rasa Using Docker
Rasa-X advance
Rasa Production Deployment
You can get Entire Code from my Github
github.com
Happy Rasa and Happy Machine learning — Readers. !!!
|
[
{
"code": null,
"e": 520,
"s": 172,
"text": "Rasa is an open source machine learning framework for building AI assistants and chatbots. Mostly you don’t need any programming language experience to work in Rasa. Although there is something called “Rasa Action Server” where you need to write code in Python, that mainly used to trigger External actions like Calling Google API or REST API etc."
},
{
"code": null,
"e": 547,
"s": 520,
"text": "Rasa has two main modules:"
},
{
"code": null,
"e": 652,
"s": 547,
"text": "Rasa NLU for understanding user messagesRasa Core for holding conversations and deciding what to do next"
},
{
"code": null,
"e": 693,
"s": 652,
"text": "Rasa NLU for understanding user messages"
},
{
"code": null,
"e": 758,
"s": 693,
"text": "Rasa Core for holding conversations and deciding what to do next"
},
{
"code": null,
"e": 825,
"s": 758,
"text": "Note — Now Rasa NLU and Rasa Core source code are merged together."
},
{
"code": null,
"e": 1027,
"s": 825,
"text": "Rasa X is a tool that helps you build, improve, and deploy AI Assistants that are powered by the Rasa framework. Rasa X includes a user interface and a REST API. Rasa X is the latest release from Rasa."
},
{
"code": null,
"e": 1069,
"s": 1027,
"text": "About me: I am official Rasa Contributor."
},
{
"code": null,
"e": 1448,
"s": 1069,
"text": "Rasa X — It’s a Browser based GUI tool which will allow you to train Machine learning model by using GUI based interactive mode. Remember it’s an optional tool in Rasa Software Stack. Sometimes Rasa sends usage statistics information from your browser to rasa — but it never sends training data to outside of your system, it just sends how many times you are using Rasa X Train."
},
{
"code": null,
"e": 1689,
"s": 1448,
"text": "Rasa NLU — This is the place, where rasa tries to understand User messages to detect Intent and Entity in your message. Rasa NLU has different components for recognizing intents and entities, most of which have some additional dependencies."
},
{
"code": null,
"e": 1774,
"s": 1689,
"text": "Spacy (You need to install it separately)Tensorflow (By Default available with Rasa)"
},
{
"code": null,
"e": 1816,
"s": 1774,
"text": "Spacy (You need to install it separately)"
},
{
"code": null,
"e": 1860,
"s": 1816,
"text": "Tensorflow (By Default available with Rasa)"
},
{
"code": null,
"e": 2042,
"s": 1860,
"text": "Rasa Core — This is the place, where Rasa try to help you with contextual message flow. Based on User message, it can predict dialogue as a reply and can trigger Rasa Action Server."
},
{
"code": null,
"e": 2170,
"s": 2042,
"text": "Rasa internally uses Tensorflow, whenever you do “pip install rasa” or “pip install rasa-x”, by default it installs Tensorflow."
},
{
"code": null,
"e": 2228,
"s": 2170,
"text": "Ubuntu 16+, Mac OS and Windows 10 (Visual C++ Build tool)"
},
{
"code": null,
"e": 2496,
"s": 2228,
"text": "Note: In case you are working on windows, make sure you have installed the Visual c++ build tool. This is required for some python packages. Definitely use miniconda to avoid the issue with other installed Python packages in your system or conflicting Python Version."
},
{
"code": null,
"e": 2544,
"s": 2496,
"text": "Install MiniConda (Part of Anaconda) in your OS"
},
{
"code": null,
"e": 2553,
"s": 2544,
"text": "conda.io"
},
{
"code": null,
"e": 2693,
"s": 2553,
"text": "After installing miniconda, Follow below commands to create a virtual environment in conda. This will allow you to run Rasa without errors."
},
{
"code": null,
"e": 2834,
"s": 2693,
"text": "conda install python=3.6conda create -n rasa python=3.6source activate rasapip install rasa-x --extra-index-url https://pypi.rasa.com/simple"
},
{
"code": null,
"e": 2921,
"s": 2834,
"text": "By following the above command, both Rasa and Rasa X will be installed in your system."
},
{
"code": null,
"e": 3110,
"s": 2921,
"text": "Open Terminal and activate Conda Virtual Environment. Now go-to one directory and do “rasa init”, it will create a Rasa Project at that location. “rasa x” will start the Rasa X application"
},
{
"code": null,
"e": 3140,
"s": 3110,
"text": "source activate rasarasa init"
},
{
"code": null,
"e": 3373,
"s": 3140,
"text": "“rasa init” should show above message, in-case you are doing well and your system doesn’t contain any error. Follow the interactive session and continue pressing enter to reach the last step. In the end, it should show this message."
},
{
"code": null,
"e": 3493,
"s": 3373,
"text": "If you do “ls -la” in a terminal, you can see a list of files which are created by Rasa. Now do “rasa x” to start Rasa."
},
{
"code": null,
"e": 3577,
"s": 3493,
"text": "Let me explain about files, which are created as Initial project structure of Rasa."
},
{
"code": null,
"e": 3638,
"s": 3577,
"text": "__init__.pyan empty file that helps python find your actions"
},
{
"code": null,
"e": 3862,
"s": 3638,
"text": "actions.pycode for your custom actions. In-case you want Rasa to call external server via REST API or API call, you can define your Custom Actions here. Remember you can create multiple Python Script for Rasa Custom Action."
},
{
"code": null,
"e": 4085,
"s": 3862,
"text": "config.yml ‘*’configuration of your NLU and Core models. In-case you are dealing with Tensorflow or Spacy, you need to define such pipeline here. To handle this file, you show know about Machine Learning and Deep Learning."
},
{
"code": null,
"e": 4513,
"s": 4085,
"text": "credentials.ymldetails for connecting to other services. In case you want to build Bot on Facebook Messenger, Microsoft Bot Framework, you can maintain such credential and token here. So basically you just need to add Facebook, slack and Bot framework related configuration, rasa will automatically do rest for you. Remember that you need to host Rasa over https domain. During development, you can use ngrok as a testing tool."
},
{
"code": null,
"e": 4755,
"s": 4513,
"text": "data/nlu.md ‘*’your NLU training data. Here you can define Intent. Like Order Pizza or Book Uber. You need to add related Sentences for that Intent. Remember if you are using Rasa-X, your training Intent and Data will be added automatically."
},
{
"code": null,
"e": 5127,
"s": 4755,
"text": "data/stories.md ‘*’your stories. This is required for Rasa Core. There is something called “Dialog Flow in Rasa” where Rasa Core controls the flow of the conversation between you and chatbot, so for that flow, you need to train chatbot using these stories. So in case you want your chatbot to be very perfect on different context (stories) you can add those stories here."
},
{
"code": null,
"e": 5401,
"s": 5127,
"text": "domain.yml ‘*’your assistant’s domain. This file combines Different Intent which chatbot can detect and list of Bot replies. Remember you can define your Custom Action Server Python method name here (in underscore format), so that Rasa will call that python method for you."
},
{
"code": null,
"e": 5598,
"s": 5401,
"text": "endpoints.ymldetails for connecting to channels like FB messenger. This is mainly used for production setup. You can configure your Database like Redis so that Rasa can store tracking information."
},
{
"code": null,
"e": 5642,
"s": 5598,
"text": "models/<timestamp>.tar.gzyour initial model"
},
{
"code": null,
"e": 5840,
"s": 5642,
"text": "Rasa created a sample Bot for you with default data. So now you can start using it from Shell/Terminal. As a starting point let’s test your Chatbot from a terminal (remember to do this in Terminal)"
},
{
"code": null,
"e": 5851,
"s": 5840,
"text": "rasa shell"
},
{
"code": null,
"e": 5924,
"s": 5851,
"text": "You can type “hi” and in reply from bot, you will receive some response."
},
{
"code": null,
"e": 6113,
"s": 5924,
"text": "This is the newest addition to Rasa Stack. You can user Rasa-X to Try your chatbot on Browser. You can download training Data. Also, you can correct your training data by guiding your Bot."
},
{
"code": null,
"e": 6120,
"s": 6113,
"text": "rasa x"
},
{
"code": null,
"e": 6188,
"s": 6120,
"text": "It will ask for the license Agreement, you can say “y” and proceed."
},
{
"code": null,
"e": 6243,
"s": 6188,
"text": "Open this link on Browser — http://localhost:5002/talk"
},
{
"code": null,
"e": 6375,
"s": 6243,
"text": "In the left side, you can try to chat with your bot and on the right side you can see, which intent and reply is getting responded."
},
{
"code": null,
"e": 6399,
"s": 6375,
"text": "Some facts about Rasa-x"
},
{
"code": null,
"e": 6679,
"s": 6399,
"text": "When you run Rasa X locally, your training data and stories are read from the files in your project (e.g. data/nlu.md), and any changes you make in the UI are saved back to those files. Conversations and other data are stored in an SQLite database saved in a file called rasa.db."
},
{
"code": null,
"e": 6723,
"s": 6679,
"text": "Watch this video to learn more about Rasa-X"
},
{
"code": null,
"e": 6952,
"s": 6723,
"text": "This is the most real-world example of your chatbot. Suppose in your chatbot you want to add a feature where your bot can tell you latest weather report of a specified city, how you will do it? The answer is “Rasa Custom Action”"
},
{
"code": null,
"e": 7119,
"s": 6952,
"text": "An action can run any code you want. Custom actions can turn on the lights, add an event to a calendar, check a user’s bank balance, or anything else you can imagine."
},
{
"code": null,
"e": 7339,
"s": 7119,
"text": "Rasa will call an endpoint you can specify when a custom action is predicted. This endpoint should be a web server that reacts to this call, runs the code and optionally returns information to modify the dialogue state."
},
{
"code": null,
"e": 7405,
"s": 7339,
"text": "Open “actions.py” in Editor (Visual Studio Code can be an option)"
},
{
"code": null,
"e": 7474,
"s": 7405,
"text": "Step-1 — Define a Method called “ActionCheckWeather” in “actions.py”"
},
{
"code": null,
"e": 7860,
"s": 7474,
"text": "from rasa_sdk import Actionfrom rasa_sdk.events import SlotSetclass ActionCheckWeather(Action): def name(self) -> Text: return \"action_check_weather\" def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dispatcher.utter_message(\"Hello World! from custom action\") return []"
},
{
"code": null,
"e": 7931,
"s": 7860,
"text": "Step-2 — Link this custom action with your Chatbot. Open “domain.yml”."
},
{
"code": null,
"e": 8019,
"s": 7931,
"text": "Add “action_check_weather” action in the list of the action. This should look like this"
},
{
"code": null,
"e": 8128,
"s": 8019,
"text": "actions:- utter_greet- utter_cheer_up- utter_did_that_help- utter_happy- utter_goodbye- action_check_weather"
},
{
"code": null,
"e": 8286,
"s": 8128,
"text": "Now in the stories, add this custom action as your flow. Open “stories.md” file and this new custom action “action_check_weather” as part of happy path flow."
},
{
"code": null,
"e": 8354,
"s": 8286,
"text": "## happy path* greet- utter_greet* mood_great- action_check_weather"
},
{
"code": null,
"e": 8399,
"s": 8354,
"text": "Step-3 Tell rasa to use Custom Action Server"
},
{
"code": null,
"e": 8478,
"s": 8399,
"text": "Open “endpoints.yml” and add the following line to enable custom action server"
},
{
"code": null,
"e": 8534,
"s": 8478,
"text": "action_endpoint: url: \"http://localhost:5055/webhook\""
},
{
"code": null,
"e": 8764,
"s": 8534,
"text": "Now Re-train your Rasa Chatbot using following command. You need to retrain your machine learning model because you made some changes in “stories.md” and “domain.yml” file. So without re-train, you can’t inform Rasa to use those."
},
{
"code": null,
"e": 8775,
"s": 8764,
"text": "rasa train"
},
{
"code": null,
"e": 8802,
"s": 8775,
"text": "Now start Rasa again using"
},
{
"code": null,
"e": 8809,
"s": 8802,
"text": "rasa x"
},
{
"code": null,
"e": 8934,
"s": 8809,
"text": "Also, start Rasa Action server using the following command. Rasa X and Rasa run actions should run in 2 different terminals."
},
{
"code": null,
"e": 8951,
"s": 8934,
"text": "rasa run actions"
},
{
"code": null,
"e": 9195,
"s": 8951,
"text": "You can see, you are getting a reply from custom action which is written in python. In the same python script, you can connect to your backend database and return a response. Also, you can call an external API using additional python packages."
},
{
"code": null,
"e": 9262,
"s": 9195,
"text": "Also, you can develop Custom action Server in C#, NodeJS and Java."
},
{
"code": null,
"e": 9467,
"s": 9262,
"text": "You can build a Chatbot GUI using HTML5 and CSS3. You can use the Library like ReactJS and JQuery. If you want you can use Angular as your frontend JavaScript framework to build Frontend for your Chatbot."
},
{
"code": null,
"e": 9541,
"s": 9467,
"text": "Build GUI in HTML5 and CSS3Call Rasa Rest API from your frontendThat’s it"
},
{
"code": null,
"e": 9569,
"s": 9541,
"text": "Build GUI in HTML5 and CSS3"
},
{
"code": null,
"e": 9607,
"s": 9569,
"text": "Call Rasa Rest API from your frontend"
},
{
"code": null,
"e": 9617,
"s": 9607,
"text": "That’s it"
},
{
"code": null,
"e": 9665,
"s": 9617,
"text": "Sample API call from JavaScript to Rasa Backend"
},
{
"code": null,
"e": 9808,
"s": 9665,
"text": "As we are heading towards building production-grade Rasa Chatbot setup, the first thing we can simply use the following command to start Rasa."
},
{
"code": null,
"e": 9817,
"s": 9808,
"text": "rasa run"
},
{
"code": null,
"e": 9884,
"s": 9817,
"text": "Above command will run Rasa Core and Expose REST API on port 5005."
},
{
"code": null,
"e": 10111,
"s": 9884,
"text": "URL: http://localhost:5005/webhooks/rest/webhookMethod: POSTHeader: Content-Type: application/jsonBody:{ “sender”: “Rasa1”, “message”: “hi”}Response:[ { “recipient_id”: “Rasa1”, “text”: “Hey! How are you?” }]"
},
{
"code": null,
"e": 10329,
"s": 10111,
"text": "Now you can parse this response in your frontend application and show this response to the user. Remember Rasa will track your conversation based on a unique id called “Rasa1” which we have passed in the Request body."
},
{
"code": null,
"e": 10383,
"s": 10329,
"text": "In the next part of this Article, we will learn about"
},
{
"code": null,
"e": 10450,
"s": 10383,
"text": "Rasa SlotRasa Using DockerRasa-X advanceRasa Production Deployment"
},
{
"code": null,
"e": 10460,
"s": 10450,
"text": "Rasa Slot"
},
{
"code": null,
"e": 10478,
"s": 10460,
"text": "Rasa Using Docker"
},
{
"code": null,
"e": 10493,
"s": 10478,
"text": "Rasa-X advance"
},
{
"code": null,
"e": 10520,
"s": 10493,
"text": "Rasa Production Deployment"
},
{
"code": null,
"e": 10559,
"s": 10520,
"text": "You can get Entire Code from my Github"
},
{
"code": null,
"e": 10570,
"s": 10559,
"text": "github.com"
}
] |
Bring your Jupyter Notebook to life with interactive widgets | by Semi Koen | Towards Data Science
|
Traditionally, every time you need to modify the output of your notebook cells, you need to change the code and rerun the affected cells. This can be cumbersome, inefficient and error prone and in the case of a non-technical user it may even be impracticable. This is where the ipywidgets come into play: they can be embedded in the notebook and provide a user friendly interface to collect the user input and see the impact the changes have on the data/results, without having to interact with the code; your notebooks can be transformed from static documents to dynamic dashboards — ideal for showcasing your data story!
⚠️ Scope: There are limited resources on ipywidgets and the very few tutorials out there are either incomplete or focusing on the interact function/decorator. This is a complete tutorial of how you can take full control of the widgets to create powerful dashboards.
We will start with the basics: adding a widget and explaining how the events work and we will progressively develop a dashboard.I will guide you step by step, building on the examples as we go.
If you have ever created a graphical user interface (GUI) then you already know what a widget is. But let’s give a quick definition anyway:A widget is a GUI element, such as a button, dropdown or textbox, which resides in the browser and allows us to control the code and the data by responding to events and invoking specified handlers.
These GUI elements can be assembled and customised to create complex dashboards.
Throughout this article we will see some of them in action.
Ready? 🏁
To start using the library we need to install the ipywidgets extension. If using conda, we type this command in the terminal:
conda install -c conda-forge ipywidgets
For pip, it will be a two-step process: 1. install and 2. enable:
pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension
In order to incorporate widgets in the notebook we have to import the module, as shown below:
import ipywidgets as widgets
To add a slider, we can define the minimum and maximum values, the interval size (step), a description and an initial value:
widgets.IntSlider( min=0, max=10, step=1, description='Slider:', value=3)
The display() function renders a widget object in an input cell.First import:
from IPython.display import display
Then pass the widget as a parameter in the display() function:
slider = widgets.IntSlider()display(slider)
To read the value of a widget, we will query its value property. Similarly, we can set a widget’s value:
We can synchronise the values of two widgets by using the jslink() function.
slider = widgets.IntSlider()text = widgets.IntText()display(slider, text)widgets.jslink((slider, 'value'), (text, 'value'))
For a full list of widgets you can check out the documentation, or run the following command:
print(dir(widgets))
The widgets can respond to events, which are raised when a user interacts with them. A simple example is clicking on a button — we are expecting an action to take place.
Let’s see how this works...
Depending on its specific features, each widget exposes different events. An event handler will be executed every time the event is fired.
Event handler is a callback function in response to an event, that operates asynchronously and handles the inputs received.
Here we will create a simple button called btn. The on_click method is invoked when the button is clicked.
Our event handler, btn_eventhandler, will print a short message with the button’s caption — note that the input argument of the handler, obj, is the button object itself which allows us to access its properties.
To bind the event with the handler, we assign the latter to the button’s on_click method.
btn = widgets.Button(description='Medium')display(btn)def btn_eventhandler(obj): print('Hello from the {} button!'.format(obj.description))btn.on_click(btn_eventhandler)
What will bring us nicely to the next section is that the output appears in the same cell as the button itself. So let’s move on to see how we can add more flexibility to our notebook!
In this section we will explore how to use widgets to control a dataframe. The sample dataset I have chosen is ‘Number of International Visitors to London’ which shows totals of London’s visitors with regards to nights, visits and spend, broken down by year, quarter, purpose, duration, mode and country.
Initially, we will get the data and load it into a dataframe:
import pandas as pdimport numpy as npurl = "https://data.london.gov.uk/download/number-international-visitors-london/b1e0f953-4c8a-4b45-95f5-e0d143d5641e/international-visitors-london-raw.csv"df_london = pd.read_csv(url)
Suppose we would like to filter the dataframe by year. We will first define a dropdown and populate it with the list of unique year values.
In order to do this, we will create a generic function, unique_sorted_values_plus_ALL, which will find the unique values, sort them and then add the ALL item at the start, so the user could remove the filter.
ALL = 'ALL'def unique_sorted_values_plus_ALL(array): unique = array.unique().tolist() unique.sort() unique.insert(0, ALL) return unique
Now we will initialise the dropdown:
dropdown_year = widgets.Dropdown(options = unique_sorted_values_plus_ALL(df_london.year))
The dropdown widget exposes the observe method, which takes a function that will be invoked when the value of the dropdown changes. As such, we will next create the observer handler to filter the dataframe by the selected values — note that the input argument of the handler, change, contains information about the changes that took place which allows us to access the new value (change.new).If the new value is ALL we remove the filter, otherwise we apply it:
def dropdown_year_eventhandler(change): if (change.new == ALL): display(df_london) else: display(df_london[df_london.year == change.new])
We will then bind the handler to the dropdown:
dropdown_year.observe(dropdown_year_eventhandler, names='value')
So far so good, but the output of all the queries is accumulating in this very same cell; i.e. if we select a new year from the dropdown, a new dataframe will render underneath the first one, on the same cell.The desired behaviour though, is to refresh the contents of the dataframe each time.
The solution to this is to capture the cell output in a special kind of widget, namely Output, and then display it in another cell.
We will slightly tweak the code to:
create a new instance of Output
output_year = widgets.Output()
call the clear_output method within the event handler to clear the previous selection on each iteration, and capture the output of the dataframe in a with block.
def dropdown_year_eventhandler(change): output_year.clear_output() with output_year: display(df_london[df_london.year == change.new])
We will then display the output in a new cell:
display(output_year)
This is how it works:
As you can see the output is rendered in a new cell and the filtering is working as expected! 👍
Continuing the previous example, let’s assume we would also like to filter by purpose too.
If we go ahead and add another dropdown, we will quickly realise the dataframe only responds to the filter by the dropdown which was recently changed. What we need to do is to link the two together so it can work on both values (i.e. year and purpose).
Let’s see how it should work:
Firstly we need a common output for both dropdowns:
output = widgets.Output()
Here are the two dropdowns:
dropdown_year = widgets.Dropdown(options = unique_sorted_values_plus_ALL(df_london.year))dropdown_purpose = widgets.Dropdown(options = unique_sorted_values_plus_ALL(df_london.purpose))
Then we create a new function, common_filtering, that will be called by both the event handlers. This function will apply a filter on the dataframe for both year AND purpose:We are clearing the output, then we check if any of the values is ALL, in which case we consider that the respective filter is removed. When both filters are present, in the else statement, we apply the & operation in both filters. Finally we capture the output:
def common_filtering(year, purpose): output.clear_output() if (year == ALL) & (purpose == ALL): common_filter = df_london elif (year == ALL): common_filter = df_london[df_london.purpose == purpose] elif (purpose == ALL): common_filter = df_london[df_london.year == year] else: common_filter = df_london[(df_london.year == year) & (df_london.purpose == purpose)] with output: display(common_filter)
We amend the event handlers to call the common_filtering function and pass the change.new value as well as the current value of the other dropdown:
def dropdown_year_eventhandler(change): common_filtering(change.new, dropdown_purpose.value)def dropdown_purpose_eventhandler(change): common_filtering(dropdown_year.value, change.new)
We bind the handlers to the dropdowns, and that’s it!
dropdown_year.observe(dropdown_year_eventhandler, names='value')dropdown_purpose.observe(dropdown_purpose_eventhandler, names='value')
Code snippet:
Here is the demo:
We have put the basis for our dashboard so far by filtering and displaying the data of the London dataset. We will carry on by colouring the numeric values based on a user selected value.
A useful numeric widget is the BoundedFloatText; we will give it a min, max and initial value, and the incremental step.
bounded_num = widgets.BoundedFloatText(min=0, max=100000, value=5, step=1)
In order to colour the dataframe cells, we will define this function:
def colour_ge_value(value, comparison): if value >= comparison: return 'color: red' else: return 'color: black'
Now we will minimally amend the common_filtering function to:
add new num input parameter:
def common_filtering(year, purpose, num):
apply the styling by calling the colour_ge_value function for the three numeric columns:
with output: display(common_filter .style.applymap( lambda x: colour_ge_value(x, num), subset=['visits','spend', 'nights']))
The existing event handlers need to be adjusted to pass the bounded_num.value:
def dropdown_year_eventhandler(change): common_filtering(change.new, dropdown_purpose.value, bounded_num.value)def dropdown_purpose_eventhandler(change): common_filtering(dropdown_year.value, change.new, bounded_num.value)
And finally we will plug-in the event handler of the new widget:
def bounded_num_eventhandler(change): common_filtering(dropdown_year.value, dropdown_purpose.value, change.new)bounded_num.observe(bounded_num_eventhandler, names='value')
Code snippet:
Here is the demo:
Next we will be adding a new graph to plot a basic univariate density of the number of visits (KDE → Kernel Density Estimation). We will use seaborn, so let’s import the libraries:
import seaborn as snsimport matplotlib.pyplot as plt
Continuing the previous use-case, we will capture the plot in a new output variable:
plot_output = widgets.Output()
We will now amend the common_filtering function to plot the new diagram:
first we clear the output:
plot_output.clear_output()
and then we call the kdeplot method of seaborn by passing the number of visits:
with plot_output: sns.kdeplot(common_filter['visits'], shade=True) plt.show()
Lastly, the only thing we need to do is to display the outputs in a new cell:
display(output)display(plot_output)
Code snippet:
Here is the demo:
Up until now our user interface is functional but is taking up a lot of real estate.
We will first arrange the input widgets horizontally. The HBox will add widgets to it one at a time from left-to-right:
input_widgets = widgets.HBox([dropdown_year, dropdown_purpose, bounded_num])display(input_widgets)
Next we will create a container for the output. Tab is great for this. The 1st tab will host the dataframe and the 2nd one the graph.
tab = widgets.Tab([output, plot_output])tab.set_title(0, 'Dataset Exploration')tab.set_title(1, 'KDE Plot')display(tab)
Finally we will stack the input widgets and the tab on top of each other with a VBox.
dashboard = widgets.VBox([input_widgets, tab])display(dashboard)
It feels a bit ‘jammed’, so as a last step, we will polish our dashboard by adding some space. We will define a Layout giving 50px margin between the items.
item_layout = widgets.Layout(margin='0 0 50px 0')
We will call this layout for each item:
input_widgets = widgets.HBox([dropdown_year, dropdown_purpose, bounded_num],layout=item_layout)tab = widgets.Tab([output, plot_output],layout=item_layout)
and ta da.... Our finished dashboard:
PS: For presentation purposes, in some of these demos I have used a subset of the dataset i.e.: df_london = df_london.sample(250).
There are a few third party widgets you can use too, with most popular ones being:• 2-D charting: bqplot• 3-D visualisation: pythreejs and ipyvolume• Mapping: ipyleaflet and gmaps.
You can also build your own custom widgets! For more info take a look here.
We saw a fairly wide range of widgets in action but we still have only scratched the surface here — we can build really complex and extensive GUIs using ipywidgets. I hope you all agree they deserve a place in any Data Scientist’s toolbox as they enhance our productivity and add a lot of value during data exploration.
Thanks for reading!
I regularly write about Technology & Data on Medium — if you would like to read my future posts then please ‘Follow’ me!
|
[
{
"code": null,
"e": 794,
"s": 171,
"text": "Traditionally, every time you need to modify the output of your notebook cells, you need to change the code and rerun the affected cells. This can be cumbersome, inefficient and error prone and in the case of a non-technical user it may even be impracticable. This is where the ipywidgets come into play: they can be embedded in the notebook and provide a user friendly interface to collect the user input and see the impact the changes have on the data/results, without having to interact with the code; your notebooks can be transformed from static documents to dynamic dashboards — ideal for showcasing your data story!"
},
{
"code": null,
"e": 1060,
"s": 794,
"text": "⚠️ Scope: There are limited resources on ipywidgets and the very few tutorials out there are either incomplete or focusing on the interact function/decorator. This is a complete tutorial of how you can take full control of the widgets to create powerful dashboards."
},
{
"code": null,
"e": 1254,
"s": 1060,
"text": "We will start with the basics: adding a widget and explaining how the events work and we will progressively develop a dashboard.I will guide you step by step, building on the examples as we go."
},
{
"code": null,
"e": 1592,
"s": 1254,
"text": "If you have ever created a graphical user interface (GUI) then you already know what a widget is. But let’s give a quick definition anyway:A widget is a GUI element, such as a button, dropdown or textbox, which resides in the browser and allows us to control the code and the data by responding to events and invoking specified handlers."
},
{
"code": null,
"e": 1673,
"s": 1592,
"text": "These GUI elements can be assembled and customised to create complex dashboards."
},
{
"code": null,
"e": 1733,
"s": 1673,
"text": "Throughout this article we will see some of them in action."
},
{
"code": null,
"e": 1742,
"s": 1733,
"text": "Ready? 🏁"
},
{
"code": null,
"e": 1868,
"s": 1742,
"text": "To start using the library we need to install the ipywidgets extension. If using conda, we type this command in the terminal:"
},
{
"code": null,
"e": 1908,
"s": 1868,
"text": "conda install -c conda-forge ipywidgets"
},
{
"code": null,
"e": 1974,
"s": 1908,
"text": "For pip, it will be a two-step process: 1. install and 2. enable:"
},
{
"code": null,
"e": 2047,
"s": 1974,
"text": "pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension"
},
{
"code": null,
"e": 2141,
"s": 2047,
"text": "In order to incorporate widgets in the notebook we have to import the module, as shown below:"
},
{
"code": null,
"e": 2170,
"s": 2141,
"text": "import ipywidgets as widgets"
},
{
"code": null,
"e": 2295,
"s": 2170,
"text": "To add a slider, we can define the minimum and maximum values, the interval size (step), a description and an initial value:"
},
{
"code": null,
"e": 2384,
"s": 2295,
"text": "widgets.IntSlider( min=0, max=10, step=1, description='Slider:', value=3)"
},
{
"code": null,
"e": 2462,
"s": 2384,
"text": "The display() function renders a widget object in an input cell.First import:"
},
{
"code": null,
"e": 2498,
"s": 2462,
"text": "from IPython.display import display"
},
{
"code": null,
"e": 2561,
"s": 2498,
"text": "Then pass the widget as a parameter in the display() function:"
},
{
"code": null,
"e": 2605,
"s": 2561,
"text": "slider = widgets.IntSlider()display(slider)"
},
{
"code": null,
"e": 2710,
"s": 2605,
"text": "To read the value of a widget, we will query its value property. Similarly, we can set a widget’s value:"
},
{
"code": null,
"e": 2787,
"s": 2710,
"text": "We can synchronise the values of two widgets by using the jslink() function."
},
{
"code": null,
"e": 2911,
"s": 2787,
"text": "slider = widgets.IntSlider()text = widgets.IntText()display(slider, text)widgets.jslink((slider, 'value'), (text, 'value'))"
},
{
"code": null,
"e": 3005,
"s": 2911,
"text": "For a full list of widgets you can check out the documentation, or run the following command:"
},
{
"code": null,
"e": 3025,
"s": 3005,
"text": "print(dir(widgets))"
},
{
"code": null,
"e": 3195,
"s": 3025,
"text": "The widgets can respond to events, which are raised when a user interacts with them. A simple example is clicking on a button — we are expecting an action to take place."
},
{
"code": null,
"e": 3223,
"s": 3195,
"text": "Let’s see how this works..."
},
{
"code": null,
"e": 3362,
"s": 3223,
"text": "Depending on its specific features, each widget exposes different events. An event handler will be executed every time the event is fired."
},
{
"code": null,
"e": 3486,
"s": 3362,
"text": "Event handler is a callback function in response to an event, that operates asynchronously and handles the inputs received."
},
{
"code": null,
"e": 3593,
"s": 3486,
"text": "Here we will create a simple button called btn. The on_click method is invoked when the button is clicked."
},
{
"code": null,
"e": 3805,
"s": 3593,
"text": "Our event handler, btn_eventhandler, will print a short message with the button’s caption — note that the input argument of the handler, obj, is the button object itself which allows us to access its properties."
},
{
"code": null,
"e": 3895,
"s": 3805,
"text": "To bind the event with the handler, we assign the latter to the button’s on_click method."
},
{
"code": null,
"e": 4068,
"s": 3895,
"text": "btn = widgets.Button(description='Medium')display(btn)def btn_eventhandler(obj): print('Hello from the {} button!'.format(obj.description))btn.on_click(btn_eventhandler)"
},
{
"code": null,
"e": 4253,
"s": 4068,
"text": "What will bring us nicely to the next section is that the output appears in the same cell as the button itself. So let’s move on to see how we can add more flexibility to our notebook!"
},
{
"code": null,
"e": 4558,
"s": 4253,
"text": "In this section we will explore how to use widgets to control a dataframe. The sample dataset I have chosen is ‘Number of International Visitors to London’ which shows totals of London’s visitors with regards to nights, visits and spend, broken down by year, quarter, purpose, duration, mode and country."
},
{
"code": null,
"e": 4620,
"s": 4558,
"text": "Initially, we will get the data and load it into a dataframe:"
},
{
"code": null,
"e": 4841,
"s": 4620,
"text": "import pandas as pdimport numpy as npurl = \"https://data.london.gov.uk/download/number-international-visitors-london/b1e0f953-4c8a-4b45-95f5-e0d143d5641e/international-visitors-london-raw.csv\"df_london = pd.read_csv(url)"
},
{
"code": null,
"e": 4981,
"s": 4841,
"text": "Suppose we would like to filter the dataframe by year. We will first define a dropdown and populate it with the list of unique year values."
},
{
"code": null,
"e": 5190,
"s": 4981,
"text": "In order to do this, we will create a generic function, unique_sorted_values_plus_ALL, which will find the unique values, sort them and then add the ALL item at the start, so the user could remove the filter."
},
{
"code": null,
"e": 5338,
"s": 5190,
"text": "ALL = 'ALL'def unique_sorted_values_plus_ALL(array): unique = array.unique().tolist() unique.sort() unique.insert(0, ALL) return unique"
},
{
"code": null,
"e": 5375,
"s": 5338,
"text": "Now we will initialise the dropdown:"
},
{
"code": null,
"e": 5468,
"s": 5375,
"text": "dropdown_year = widgets.Dropdown(options = unique_sorted_values_plus_ALL(df_london.year))"
},
{
"code": null,
"e": 5929,
"s": 5468,
"text": "The dropdown widget exposes the observe method, which takes a function that will be invoked when the value of the dropdown changes. As such, we will next create the observer handler to filter the dataframe by the selected values — note that the input argument of the handler, change, contains information about the changes that took place which allows us to access the new value (change.new).If the new value is ALL we remove the filter, otherwise we apply it:"
},
{
"code": null,
"e": 6087,
"s": 5929,
"text": "def dropdown_year_eventhandler(change): if (change.new == ALL): display(df_london) else: display(df_london[df_london.year == change.new])"
},
{
"code": null,
"e": 6134,
"s": 6087,
"text": "We will then bind the handler to the dropdown:"
},
{
"code": null,
"e": 6199,
"s": 6134,
"text": "dropdown_year.observe(dropdown_year_eventhandler, names='value')"
},
{
"code": null,
"e": 6493,
"s": 6199,
"text": "So far so good, but the output of all the queries is accumulating in this very same cell; i.e. if we select a new year from the dropdown, a new dataframe will render underneath the first one, on the same cell.The desired behaviour though, is to refresh the contents of the dataframe each time."
},
{
"code": null,
"e": 6625,
"s": 6493,
"text": "The solution to this is to capture the cell output in a special kind of widget, namely Output, and then display it in another cell."
},
{
"code": null,
"e": 6661,
"s": 6625,
"text": "We will slightly tweak the code to:"
},
{
"code": null,
"e": 6693,
"s": 6661,
"text": "create a new instance of Output"
},
{
"code": null,
"e": 6724,
"s": 6693,
"text": "output_year = widgets.Output()"
},
{
"code": null,
"e": 6886,
"s": 6724,
"text": "call the clear_output method within the event handler to clear the previous selection on each iteration, and capture the output of the dataframe in a with block."
},
{
"code": null,
"e": 7033,
"s": 6886,
"text": "def dropdown_year_eventhandler(change): output_year.clear_output() with output_year: display(df_london[df_london.year == change.new])"
},
{
"code": null,
"e": 7080,
"s": 7033,
"text": "We will then display the output in a new cell:"
},
{
"code": null,
"e": 7101,
"s": 7080,
"text": "display(output_year)"
},
{
"code": null,
"e": 7123,
"s": 7101,
"text": "This is how it works:"
},
{
"code": null,
"e": 7219,
"s": 7123,
"text": "As you can see the output is rendered in a new cell and the filtering is working as expected! 👍"
},
{
"code": null,
"e": 7310,
"s": 7219,
"text": "Continuing the previous example, let’s assume we would also like to filter by purpose too."
},
{
"code": null,
"e": 7563,
"s": 7310,
"text": "If we go ahead and add another dropdown, we will quickly realise the dataframe only responds to the filter by the dropdown which was recently changed. What we need to do is to link the two together so it can work on both values (i.e. year and purpose)."
},
{
"code": null,
"e": 7593,
"s": 7563,
"text": "Let’s see how it should work:"
},
{
"code": null,
"e": 7645,
"s": 7593,
"text": "Firstly we need a common output for both dropdowns:"
},
{
"code": null,
"e": 7671,
"s": 7645,
"text": "output = widgets.Output()"
},
{
"code": null,
"e": 7699,
"s": 7671,
"text": "Here are the two dropdowns:"
},
{
"code": null,
"e": 7887,
"s": 7699,
"text": "dropdown_year = widgets.Dropdown(options = unique_sorted_values_plus_ALL(df_london.year))dropdown_purpose = widgets.Dropdown(options = unique_sorted_values_plus_ALL(df_london.purpose))"
},
{
"code": null,
"e": 8324,
"s": 7887,
"text": "Then we create a new function, common_filtering, that will be called by both the event handlers. This function will apply a filter on the dataframe for both year AND purpose:We are clearing the output, then we check if any of the values is ALL, in which case we consider that the respective filter is removed. When both filters are present, in the else statement, we apply the & operation in both filters. Finally we capture the output:"
},
{
"code": null,
"e": 8817,
"s": 8324,
"text": "def common_filtering(year, purpose): output.clear_output() if (year == ALL) & (purpose == ALL): common_filter = df_london elif (year == ALL): common_filter = df_london[df_london.purpose == purpose] elif (purpose == ALL): common_filter = df_london[df_london.year == year] else: common_filter = df_london[(df_london.year == year) & (df_london.purpose == purpose)] with output: display(common_filter)"
},
{
"code": null,
"e": 8965,
"s": 8817,
"text": "We amend the event handlers to call the common_filtering function and pass the change.new value as well as the current value of the other dropdown:"
},
{
"code": null,
"e": 9156,
"s": 8965,
"text": "def dropdown_year_eventhandler(change): common_filtering(change.new, dropdown_purpose.value)def dropdown_purpose_eventhandler(change): common_filtering(dropdown_year.value, change.new)"
},
{
"code": null,
"e": 9210,
"s": 9156,
"text": "We bind the handlers to the dropdowns, and that’s it!"
},
{
"code": null,
"e": 9345,
"s": 9210,
"text": "dropdown_year.observe(dropdown_year_eventhandler, names='value')dropdown_purpose.observe(dropdown_purpose_eventhandler, names='value')"
},
{
"code": null,
"e": 9359,
"s": 9345,
"text": "Code snippet:"
},
{
"code": null,
"e": 9377,
"s": 9359,
"text": "Here is the demo:"
},
{
"code": null,
"e": 9565,
"s": 9377,
"text": "We have put the basis for our dashboard so far by filtering and displaying the data of the London dataset. We will carry on by colouring the numeric values based on a user selected value."
},
{
"code": null,
"e": 9686,
"s": 9565,
"text": "A useful numeric widget is the BoundedFloatText; we will give it a min, max and initial value, and the incremental step."
},
{
"code": null,
"e": 9761,
"s": 9686,
"text": "bounded_num = widgets.BoundedFloatText(min=0, max=100000, value=5, step=1)"
},
{
"code": null,
"e": 9831,
"s": 9761,
"text": "In order to colour the dataframe cells, we will define this function:"
},
{
"code": null,
"e": 9963,
"s": 9831,
"text": "def colour_ge_value(value, comparison): if value >= comparison: return 'color: red' else: return 'color: black'"
},
{
"code": null,
"e": 10025,
"s": 9963,
"text": "Now we will minimally amend the common_filtering function to:"
},
{
"code": null,
"e": 10054,
"s": 10025,
"text": "add new num input parameter:"
},
{
"code": null,
"e": 10096,
"s": 10054,
"text": "def common_filtering(year, purpose, num):"
},
{
"code": null,
"e": 10185,
"s": 10096,
"text": "apply the styling by calling the colour_ge_value function for the three numeric columns:"
},
{
"code": null,
"e": 10370,
"s": 10185,
"text": "with output: display(common_filter .style.applymap( lambda x: colour_ge_value(x, num), subset=['visits','spend', 'nights']))"
},
{
"code": null,
"e": 10449,
"s": 10370,
"text": "The existing event handlers need to be adjusted to pass the bounded_num.value:"
},
{
"code": null,
"e": 10719,
"s": 10449,
"text": "def dropdown_year_eventhandler(change): common_filtering(change.new, dropdown_purpose.value, bounded_num.value)def dropdown_purpose_eventhandler(change): common_filtering(dropdown_year.value, change.new, bounded_num.value)"
},
{
"code": null,
"e": 10784,
"s": 10719,
"text": "And finally we will plug-in the event handler of the new widget:"
},
{
"code": null,
"e": 10980,
"s": 10784,
"text": "def bounded_num_eventhandler(change): common_filtering(dropdown_year.value, dropdown_purpose.value, change.new)bounded_num.observe(bounded_num_eventhandler, names='value')"
},
{
"code": null,
"e": 10994,
"s": 10980,
"text": "Code snippet:"
},
{
"code": null,
"e": 11012,
"s": 10994,
"text": "Here is the demo:"
},
{
"code": null,
"e": 11193,
"s": 11012,
"text": "Next we will be adding a new graph to plot a basic univariate density of the number of visits (KDE → Kernel Density Estimation). We will use seaborn, so let’s import the libraries:"
},
{
"code": null,
"e": 11246,
"s": 11193,
"text": "import seaborn as snsimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 11331,
"s": 11246,
"text": "Continuing the previous use-case, we will capture the plot in a new output variable:"
},
{
"code": null,
"e": 11362,
"s": 11331,
"text": "plot_output = widgets.Output()"
},
{
"code": null,
"e": 11435,
"s": 11362,
"text": "We will now amend the common_filtering function to plot the new diagram:"
},
{
"code": null,
"e": 11462,
"s": 11435,
"text": "first we clear the output:"
},
{
"code": null,
"e": 11489,
"s": 11462,
"text": "plot_output.clear_output()"
},
{
"code": null,
"e": 11569,
"s": 11489,
"text": "and then we call the kdeplot method of seaborn by passing the number of visits:"
},
{
"code": null,
"e": 11653,
"s": 11569,
"text": "with plot_output: sns.kdeplot(common_filter['visits'], shade=True) plt.show()"
},
{
"code": null,
"e": 11731,
"s": 11653,
"text": "Lastly, the only thing we need to do is to display the outputs in a new cell:"
},
{
"code": null,
"e": 11767,
"s": 11731,
"text": "display(output)display(plot_output)"
},
{
"code": null,
"e": 11781,
"s": 11767,
"text": "Code snippet:"
},
{
"code": null,
"e": 11799,
"s": 11781,
"text": "Here is the demo:"
},
{
"code": null,
"e": 11884,
"s": 11799,
"text": "Up until now our user interface is functional but is taking up a lot of real estate."
},
{
"code": null,
"e": 12004,
"s": 11884,
"text": "We will first arrange the input widgets horizontally. The HBox will add widgets to it one at a time from left-to-right:"
},
{
"code": null,
"e": 12103,
"s": 12004,
"text": "input_widgets = widgets.HBox([dropdown_year, dropdown_purpose, bounded_num])display(input_widgets)"
},
{
"code": null,
"e": 12237,
"s": 12103,
"text": "Next we will create a container for the output. Tab is great for this. The 1st tab will host the dataframe and the 2nd one the graph."
},
{
"code": null,
"e": 12357,
"s": 12237,
"text": "tab = widgets.Tab([output, plot_output])tab.set_title(0, 'Dataset Exploration')tab.set_title(1, 'KDE Plot')display(tab)"
},
{
"code": null,
"e": 12443,
"s": 12357,
"text": "Finally we will stack the input widgets and the tab on top of each other with a VBox."
},
{
"code": null,
"e": 12508,
"s": 12443,
"text": "dashboard = widgets.VBox([input_widgets, tab])display(dashboard)"
},
{
"code": null,
"e": 12665,
"s": 12508,
"text": "It feels a bit ‘jammed’, so as a last step, we will polish our dashboard by adding some space. We will define a Layout giving 50px margin between the items."
},
{
"code": null,
"e": 12715,
"s": 12665,
"text": "item_layout = widgets.Layout(margin='0 0 50px 0')"
},
{
"code": null,
"e": 12755,
"s": 12715,
"text": "We will call this layout for each item:"
},
{
"code": null,
"e": 12910,
"s": 12755,
"text": "input_widgets = widgets.HBox([dropdown_year, dropdown_purpose, bounded_num],layout=item_layout)tab = widgets.Tab([output, plot_output],layout=item_layout)"
},
{
"code": null,
"e": 12948,
"s": 12910,
"text": "and ta da.... Our finished dashboard:"
},
{
"code": null,
"e": 13079,
"s": 12948,
"text": "PS: For presentation purposes, in some of these demos I have used a subset of the dataset i.e.: df_london = df_london.sample(250)."
},
{
"code": null,
"e": 13260,
"s": 13079,
"text": "There are a few third party widgets you can use too, with most popular ones being:• 2-D charting: bqplot• 3-D visualisation: pythreejs and ipyvolume• Mapping: ipyleaflet and gmaps."
},
{
"code": null,
"e": 13336,
"s": 13260,
"text": "You can also build your own custom widgets! For more info take a look here."
},
{
"code": null,
"e": 13656,
"s": 13336,
"text": "We saw a fairly wide range of widgets in action but we still have only scratched the surface here — we can build really complex and extensive GUIs using ipywidgets. I hope you all agree they deserve a place in any Data Scientist’s toolbox as they enhance our productivity and add a lot of value during data exploration."
},
{
"code": null,
"e": 13676,
"s": 13656,
"text": "Thanks for reading!"
}
] |
C++ Program to Implement Gauss Seidel Method
|
Gauss Seidel method is used to solve linear system of equations in iterative method. This is a C++ Program to Implement Gauss Seidel Method.
Begin
Take the dimensions of the matrix p and its elements as input.
Take the initials values of x and no of iteration q as input.
While q>0
Make a for loop i = 0 to p-1
initialize n[i] = (b[i] / a[i][i]).
Make a for loop i = 0 to p-1
If (j == i)
n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]).
m[i] = n[i].
Decrease q.
/*
Here, a[i][j] = input matrix.
b[i] = this array takes values of the right side of equation.
m[i] = stores initial values of x.
*/
Return 0
End
#include<iostream>
#include<conio.h>
using namespace std;
int main(void) {
float a[10][10], b[10], m[10], n[10];
int p = 0, q = 0, i = 0, j = 0;
cout << "Enter size of 2D array : ";
cin >> p;
for (i = 0; i < p; i++) {
for (j = 0; j < p; j++) {
cout << "a[" << i << ", " << j << " ]=";
cin >> a[i][j];
}
}
cout << "\nEnter values to the right side of equation\n";
for (i = 0; i < p; i++) {
cout << "b[" << i << ", " << j << " ]=";
cin >> b[i];
}
cout << "Enter initial values of x\n";
for (i = 0; i < p; i++) {
cout << "x:[" << i<<"]=";
cin >> m[i];
}
cout << "\nEnter the no. of iteration : ";
cin >> q;
while (q> 0) {
for (i = 0; i < p; i++) {
n[i] = (b[i] / a[i][i]);
for (j = 0; j < p; j++) {
if (j == i)
continue;
n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]);
m[i] = n[i];
}
cout<<"x"<<i + 1 << "="<<n[i]<<" ";
}
cout << "\n";
q--;
}
return 0;
}
Enter size of 2D array : 2
a[0, 0 ]=1
a[0, 1 ]=2
a[1, 0 ]=3
a[1, 1 ]=4
Enter values to the right side of equation
b[0, 2 ]=1
b[1, 2 ]=2
Enter initial values of x
x:[0]=0
x:[1]=0
Enter the no. of iteration : 3
x1 = 1. x2 = -0.25
x1 = 1.5 x2 = -0.625
x1 = 2.25 x2 = -1.1875
|
[
{
"code": null,
"e": 1203,
"s": 1062,
"text": "Gauss Seidel method is used to solve linear system of equations in iterative method. This is a C++ Program to Implement Gauss Seidel Method."
},
{
"code": null,
"e": 1776,
"s": 1203,
"text": "Begin\n Take the dimensions of the matrix p and its elements as input.\n Take the initials values of x and no of iteration q as input.\n While q>0\n Make a for loop i = 0 to p-1\n initialize n[i] = (b[i] / a[i][i]).\n Make a for loop i = 0 to p-1\n If (j == i)\n n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]).\n m[i] = n[i].\n Decrease q.\n /*\n Here, a[i][j] = input matrix.\n b[i] = this array takes values of the right side of equation.\n m[i] = stores initial values of x.\n */\n Return 0\nEnd"
},
{
"code": null,
"e": 2840,
"s": 1776,
"text": "#include<iostream>\n#include<conio.h>\nusing namespace std;\nint main(void) {\n float a[10][10], b[10], m[10], n[10];\n int p = 0, q = 0, i = 0, j = 0;\n cout << \"Enter size of 2D array : \";\n cin >> p;\n for (i = 0; i < p; i++) {\n for (j = 0; j < p; j++) {\n cout << \"a[\" << i << \", \" << j << \" ]=\";\n cin >> a[i][j];\n }\n }\n cout << \"\\nEnter values to the right side of equation\\n\";\n for (i = 0; i < p; i++) {\n cout << \"b[\" << i << \", \" << j << \" ]=\";\n cin >> b[i];\n }\n cout << \"Enter initial values of x\\n\";\n for (i = 0; i < p; i++) {\n cout << \"x:[\" << i<<\"]=\";\n cin >> m[i];\n }\n cout << \"\\nEnter the no. of iteration : \";\n cin >> q;\n while (q> 0) {\n for (i = 0; i < p; i++) {\n n[i] = (b[i] / a[i][i]);\n for (j = 0; j < p; j++) {\n if (j == i)\n continue;\n n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]);\n m[i] = n[i];\n }\n cout<<\"x\"<<i + 1 << \"=\"<<n[i]<<\" \";\n }\n cout << \"\\n\";\n q--;\n }\n return 0;\n}"
},
{
"code": null,
"e": 3114,
"s": 2840,
"text": "Enter size of 2D array : 2\na[0, 0 ]=1\na[0, 1 ]=2\na[1, 0 ]=3\na[1, 1 ]=4\n\nEnter values to the right side of equation\nb[0, 2 ]=1\nb[1, 2 ]=2\nEnter initial values of x\nx:[0]=0\nx:[1]=0\n\nEnter the no. of iteration : 3\nx1 = 1. x2 = -0.25\nx1 = 1.5 x2 = -0.625\nx1 = 2.25 x2 = -1.1875"
}
] |
Phonia - Advanced Toolkits To Scan Phone Numbers - GeeksforGeeks
|
04 Jan, 2022
Phonia tool is an automated tool used in the process of OSINT for getting the information about the target with the help of a phone number. Phonia tools developed in the Python Language and its available on the GitHub platform. It’s free and open-source to use. This tool aims to get accurate results with good performance. This tool can gather information like country, area, carrier, and line type on any international number.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/coredamage/phonia.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd phonia
Step 3: You are in the directory of the phonia. Now you have to install a dependency of the phonia using the following command.
sudo pip install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 phonia.py -h
Example 1: Basic Scan
python3 phonia.py -n +9118002584458
In this example, we are performing a basic number scan on geeksforgeeks customer care number.
We have got the information about the number which we have provided as an input.
Example 2: List Scan
python3 phonia.py -i input.txt -o output.txt
In this example, we are performing multiple number scans from the input.txt file.
We have given the input file location and the results will be stored in the output.txt file.
Our search results are been saved in the output.txt file.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
mv command in Linux with examples
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux
|
[
{
"code": null,
"e": 24326,
"s": 24298,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24756,
"s": 24326,
"text": "Phonia tool is an automated tool used in the process of OSINT for getting the information about the target with the help of a phone number. Phonia tools developed in the Python Language and its available on the GitHub platform. It’s free and open-source to use. This tool aims to get accurate results with good performance. This tool can gather information like country, area, carrier, and line type on any international number. "
},
{
"code": null,
"e": 24922,
"s": 24756,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux"
},
{
"code": null,
"e": 25013,
"s": 24922,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 25064,
"s": 25013,
"text": "git clone https://github.com/coredamage/phonia.git"
},
{
"code": null,
"e": 25202,
"s": 25064,
"text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool."
},
{
"code": null,
"e": 25212,
"s": 25202,
"text": "cd phonia"
},
{
"code": null,
"e": 25340,
"s": 25212,
"text": "Step 3: You are in the directory of the phonia. Now you have to install a dependency of the phonia using the following command."
},
{
"code": null,
"e": 25377,
"s": 25340,
"text": "sudo pip install -r requirements.txt"
},
{
"code": null,
"e": 25537,
"s": 25377,
"text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section."
},
{
"code": null,
"e": 25558,
"s": 25537,
"text": "python3 phonia.py -h"
},
{
"code": null,
"e": 25580,
"s": 25558,
"text": "Example 1: Basic Scan"
},
{
"code": null,
"e": 25616,
"s": 25580,
"text": "python3 phonia.py -n +9118002584458"
},
{
"code": null,
"e": 25710,
"s": 25616,
"text": "In this example, we are performing a basic number scan on geeksforgeeks customer care number."
},
{
"code": null,
"e": 25791,
"s": 25710,
"text": "We have got the information about the number which we have provided as an input."
},
{
"code": null,
"e": 25812,
"s": 25791,
"text": "Example 2: List Scan"
},
{
"code": null,
"e": 25857,
"s": 25812,
"text": "python3 phonia.py -i input.txt -o output.txt"
},
{
"code": null,
"e": 25939,
"s": 25857,
"text": "In this example, we are performing multiple number scans from the input.txt file."
},
{
"code": null,
"e": 26032,
"s": 25939,
"text": "We have given the input file location and the results will be stored in the output.txt file."
},
{
"code": null,
"e": 26090,
"s": 26032,
"text": "Our search results are been saved in the output.txt file."
},
{
"code": null,
"e": 26101,
"s": 26090,
"text": "Kali-Linux"
},
{
"code": null,
"e": 26113,
"s": 26101,
"text": "Linux-Tools"
},
{
"code": null,
"e": 26124,
"s": 26113,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26222,
"s": 26124,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26231,
"s": 26222,
"text": "Comments"
},
{
"code": null,
"e": 26244,
"s": 26231,
"text": "Old Comments"
},
{
"code": null,
"e": 26270,
"s": 26244,
"text": "Thread functions in C/C++"
},
{
"code": null,
"e": 26310,
"s": 26270,
"text": "Array Basics in Shell Scripting | Set 1"
},
{
"code": null,
"e": 26345,
"s": 26310,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 26382,
"s": 26345,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 26419,
"s": 26382,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 26461,
"s": 26419,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 26495,
"s": 26461,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 26524,
"s": 26495,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 26559,
"s": 26524,
"text": "Basic Operators in Shell Scripting"
}
] |
How do I insert a special character such as ' (single quote) into MySQL?
|
To insert a special character such as “ ‘ “ (single quote) into MySQL, you need to use \’ escape character. The syntax is as follows −
insert into yourTableName(yourColumnName) values(' yourValue\’s ');
To understand the above syntax, let us create two tables. The query to create first table is as follows −
mysql> create table AvoidInsertErrorDemo
-> (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Sentence text
-> );
Query OK, 0 rows affected (0.53 sec)
Now you can insert special character such as ‘ in the table using insert command. The query is as follows −
mysql> insert into AvoidInsertErrorDemo(Sentence) values('a woman\'s hat');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AvoidInsertErrorDemo(Sentence) values('Mrs. Chang\'s house');
Query OK, 1 row affected (0.31 sec)
Display all records from the table using select statement:
mysql> select *from AvoidInsertErrorDemo;
The following is the output −
+----+--------------------+
| Id | Sentence |
+----+--------------------+
| 1 | a woman's hat |
| 2 | Mrs. Chang's house |
+----+--------------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1322,
"s": 1187,
"text": "To insert a special character such as “ ‘ “ (single quote) into MySQL, you need to use \\’ escape character. The syntax is as follows −"
},
{
"code": null,
"e": 1390,
"s": 1322,
"text": "insert into yourTableName(yourColumnName) values(' yourValue\\’s ');"
},
{
"code": null,
"e": 1496,
"s": 1390,
"text": "To understand the above syntax, let us create two tables. The query to create first table is as follows −"
},
{
"code": null,
"e": 1649,
"s": 1496,
"text": "mysql> create table AvoidInsertErrorDemo\n-> (\n-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n-> Sentence text\n-> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1757,
"s": 1649,
"text": "Now you can insert special character such as ‘ in the table using insert command. The query is as follows −"
},
{
"code": null,
"e": 1986,
"s": 1757,
"text": "mysql> insert into AvoidInsertErrorDemo(Sentence) values('a woman\\'s hat');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into AvoidInsertErrorDemo(Sentence) values('Mrs. Chang\\'s house');\nQuery OK, 1 row affected (0.31 sec)"
},
{
"code": null,
"e": 2045,
"s": 1986,
"text": "Display all records from the table using select statement:"
},
{
"code": null,
"e": 2087,
"s": 2045,
"text": "mysql> select *from AvoidInsertErrorDemo;"
},
{
"code": null,
"e": 2117,
"s": 2087,
"text": "The following is the output −"
},
{
"code": null,
"e": 2310,
"s": 2117,
"text": "+----+--------------------+\n| Id | Sentence |\n+----+--------------------+\n| 1 | a woman's hat |\n| 2 | Mrs. Chang's house |\n+----+--------------------+\n2 rows in set (0.00 sec)"
}
] |
Implementation of Dynamic Array in Python
|
18 Apr, 2020
What is a dynamic array?
A dynamic array is similar to an array, but with the difference that its size can be dynamically modified at runtime. Don’t need to specify how much large an array beforehand. The elements of an array occupy a contiguous block of memory, and once created, its size cannot be changed. A dynamic array can, once the array is filled, allocate a bigger chunk of memory, copy the contents from the original array to this new space, and continue to fill the available slots.
We’ll be using a built in library called ctypes of python . Check out the documentation for more info, but its basically going to be used here as a raw array from the ctypes module.
A quick note on public vs private methods, we can use an underscore _ before the method name to keep it non-public. For example:
class M(object): def public(self): print 'Use Tab to see me !' def _private(self): print "You won't be able to Tab to see me !"
m = M()m.public()
Output:
Use Tab to see me!
m._private()
Output:
You won't be able to see me!
Dynamic Array Logic Implementation:
The key is to provide means to grows an array A that stores the elements of a list. We can’t actually grow the array, its capacity is fixed. If an element is appended to a list at a time, when the underlying array is full, we need to perform following steps.
Allocate a new array B with larger capacity (A commonly used rule for the new array is to have twice the capacity of the existing array )Set B[i]=A[i], for i=0 to n-1 where n denotes the current no of items.Set A=B that is, we hence forth use B as the array of supporting list.Insert new element in the new array.
Allocate a new array B with larger capacity (A commonly used rule for the new array is to have twice the capacity of the existing array )
Set B[i]=A[i], for i=0 to n-1 where n denotes the current no of items.
Set A=B that is, we hence forth use B as the array of supporting list.
Insert new element in the new array.
Dynamic Array Code Implementation:
import ctypes class DynamicArray(object): ''' DYNAMIC ARRAY CLASS (Similar to Python List) ''' def __init__(self): self.n = 0 # Count actual elements (Default is 0) self.capacity = 1 # Default Capacity self.A = self.make_array(self.capacity) def __len__(self): """ Return number of elements sorted in array """ return self.n def __getitem__(self, k): """ Return element at index k """ if not 0 <= k <self.n: # Check it k index is in bounds of array return IndexError('K is out of bounds !') return self.A[k] # Retrieve from the array at index k def append(self, ele): """ Add element to end of the array """ if self.n == self.capacity: # Double capacity if not enough room self._resize(2 * self.capacity) self.A[self.n] = ele # Set self.n index to element self.n += 1 def insertAt(self,item,index): """ This function inserts the item at any specified index. """ if index<0 or index>self.n: print("please enter appropriate index..") return if self.n==self.capacity: self._resize(2*self.capacity) for i in range(self.n-1,index-1,-1): self.A[i+1]=self.A[i] self.A[index]=item self.n+=1 def delete(self): """ This function deletes item from the end of array """ if self.n==0: print("Array is empty deletion not Possible") return self.A[self.n-1]=0 self.n-=1 def removeAt(self,index): """ This function deletes item from a specified index.. """ if self.n==0: print("Array is empty deletion not Possible") return if index<0 or index>=self.n: return IndexError("Index out of bound....deletion not possible") if index==self.n-1: self.A[index]=0 self.n-=1 return for i in range(index,self.n-1): self.A[i]=self.A[i+1] self.A[self.n-1]=0 self.n-=1 def _resize(self, new_cap): """ Resize internal array to capacity new_cap """ B = self.make_array(new_cap) # New bigger array for k in range(self.n): # Reference all existing values B[k] = self.A[k] self.A = B # Call A the new bigger array self.capacity = new_cap # Reset the capacity def make_array(self, new_cap): """ Returns a new array with new_cap capacity """ return (new_cap * ctypes.py_object)()
# Instantiatearr = DynamicArray()# Append new elementarr.append(1)len(arr)
Output:
1
# Append new elementarr.append(2)# Check lengthlen(arr)
Output:
2
# Indexarr[0]
Output:
1
arr[1]
Output:
2
Awesome, we made our own dynamic array! Play around with it and see how it auto-resizes.
vishalpandey801
Arrays
Python
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Apr, 2020"
},
{
"code": null,
"e": 78,
"s": 53,
"text": "What is a dynamic array?"
},
{
"code": null,
"e": 547,
"s": 78,
"text": "A dynamic array is similar to an array, but with the difference that its size can be dynamically modified at runtime. Don’t need to specify how much large an array beforehand. The elements of an array occupy a contiguous block of memory, and once created, its size cannot be changed. A dynamic array can, once the array is filled, allocate a bigger chunk of memory, copy the contents from the original array to this new space, and continue to fill the available slots."
},
{
"code": null,
"e": 729,
"s": 547,
"text": "We’ll be using a built in library called ctypes of python . Check out the documentation for more info, but its basically going to be used here as a raw array from the ctypes module."
},
{
"code": null,
"e": 858,
"s": 729,
"text": "A quick note on public vs private methods, we can use an underscore _ before the method name to keep it non-public. For example:"
},
{
"code": "class M(object): def public(self): print 'Use Tab to see me !' def _private(self): print \"You won't be able to Tab to see me !\"",
"e": 1022,
"s": 858,
"text": null
},
{
"code": "m = M()m.public()",
"e": 1040,
"s": 1022,
"text": null
},
{
"code": null,
"e": 1068,
"s": 1040,
"text": "Output:\nUse Tab to see me!\n"
},
{
"code": "m._private()",
"e": 1081,
"s": 1068,
"text": null
},
{
"code": null,
"e": 1118,
"s": 1081,
"text": "Output:\nYou won't be able to see me!"
},
{
"code": null,
"e": 1154,
"s": 1118,
"text": "Dynamic Array Logic Implementation:"
},
{
"code": null,
"e": 1413,
"s": 1154,
"text": "The key is to provide means to grows an array A that stores the elements of a list. We can’t actually grow the array, its capacity is fixed. If an element is appended to a list at a time, when the underlying array is full, we need to perform following steps."
},
{
"code": null,
"e": 1727,
"s": 1413,
"text": "Allocate a new array B with larger capacity (A commonly used rule for the new array is to have twice the capacity of the existing array )Set B[i]=A[i], for i=0 to n-1 where n denotes the current no of items.Set A=B that is, we hence forth use B as the array of supporting list.Insert new element in the new array."
},
{
"code": null,
"e": 1865,
"s": 1727,
"text": "Allocate a new array B with larger capacity (A commonly used rule for the new array is to have twice the capacity of the existing array )"
},
{
"code": null,
"e": 1936,
"s": 1865,
"text": "Set B[i]=A[i], for i=0 to n-1 where n denotes the current no of items."
},
{
"code": null,
"e": 2007,
"s": 1936,
"text": "Set A=B that is, we hence forth use B as the array of supporting list."
},
{
"code": null,
"e": 2044,
"s": 2007,
"text": "Insert new element in the new array."
},
{
"code": null,
"e": 2079,
"s": 2044,
"text": "Dynamic Array Code Implementation:"
},
{
"code": "import ctypes class DynamicArray(object): ''' DYNAMIC ARRAY CLASS (Similar to Python List) ''' def __init__(self): self.n = 0 # Count actual elements (Default is 0) self.capacity = 1 # Default Capacity self.A = self.make_array(self.capacity) def __len__(self): \"\"\" Return number of elements sorted in array \"\"\" return self.n def __getitem__(self, k): \"\"\" Return element at index k \"\"\" if not 0 <= k <self.n: # Check it k index is in bounds of array return IndexError('K is out of bounds !') return self.A[k] # Retrieve from the array at index k def append(self, ele): \"\"\" Add element to end of the array \"\"\" if self.n == self.capacity: # Double capacity if not enough room self._resize(2 * self.capacity) self.A[self.n] = ele # Set self.n index to element self.n += 1 def insertAt(self,item,index): \"\"\" This function inserts the item at any specified index. \"\"\" if index<0 or index>self.n: print(\"please enter appropriate index..\") return if self.n==self.capacity: self._resize(2*self.capacity) for i in range(self.n-1,index-1,-1): self.A[i+1]=self.A[i] self.A[index]=item self.n+=1 def delete(self): \"\"\" This function deletes item from the end of array \"\"\" if self.n==0: print(\"Array is empty deletion not Possible\") return self.A[self.n-1]=0 self.n-=1 def removeAt(self,index): \"\"\" This function deletes item from a specified index.. \"\"\" if self.n==0: print(\"Array is empty deletion not Possible\") return if index<0 or index>=self.n: return IndexError(\"Index out of bound....deletion not possible\") if index==self.n-1: self.A[index]=0 self.n-=1 return for i in range(index,self.n-1): self.A[i]=self.A[i+1] self.A[self.n-1]=0 self.n-=1 def _resize(self, new_cap): \"\"\" Resize internal array to capacity new_cap \"\"\" B = self.make_array(new_cap) # New bigger array for k in range(self.n): # Reference all existing values B[k] = self.A[k] self.A = B # Call A the new bigger array self.capacity = new_cap # Reset the capacity def make_array(self, new_cap): \"\"\" Returns a new array with new_cap capacity \"\"\" return (new_cap * ctypes.py_object)()",
"e": 5065,
"s": 2079,
"text": null
},
{
"code": "# Instantiatearr = DynamicArray()# Append new elementarr.append(1)len(arr)",
"e": 5140,
"s": 5065,
"text": null
},
{
"code": null,
"e": 5150,
"s": 5140,
"text": "Output:\n1"
},
{
"code": "# Append new elementarr.append(2)# Check lengthlen(arr)",
"e": 5206,
"s": 5150,
"text": null
},
{
"code": null,
"e": 5216,
"s": 5206,
"text": "Output:\n2"
},
{
"code": "# Indexarr[0]",
"e": 5230,
"s": 5216,
"text": null
},
{
"code": null,
"e": 5240,
"s": 5230,
"text": "Output:\n1"
},
{
"code": "arr[1]",
"e": 5247,
"s": 5240,
"text": null
},
{
"code": null,
"e": 5257,
"s": 5247,
"text": "Output:\n2"
},
{
"code": null,
"e": 5346,
"s": 5257,
"text": "Awesome, we made our own dynamic array! Play around with it and see how it auto-resizes."
},
{
"code": null,
"e": 5362,
"s": 5346,
"text": "vishalpandey801"
},
{
"code": null,
"e": 5369,
"s": 5362,
"text": "Arrays"
},
{
"code": null,
"e": 5376,
"s": 5369,
"text": "Python"
},
{
"code": null,
"e": 5383,
"s": 5376,
"text": "Arrays"
},
{
"code": null,
"e": 5481,
"s": 5383,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5549,
"s": 5481,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5593,
"s": 5549,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 5625,
"s": 5593,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5673,
"s": 5625,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 5687,
"s": 5673,
"text": "Linear Search"
},
{
"code": null,
"e": 5715,
"s": 5687,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5765,
"s": 5715,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5787,
"s": 5765,
"text": "Python map() function"
}
] |
Count numbers upto N which are both perfect square and perfect cube
|
24 Jun, 2022
Given a number N. The task is to count total numbers under N which are both perfect square and cube of some integers.Examples:
Input: N = 100
Output: 2
They are 1 and 64.
Input: N = 100000
Output: 6
Approach: For a given positive number N to be a perfect square, it must satisfy P2 = N Similarly, Q3 = N for a perfect cube where P and Q are some positive integers. N = P2 = Q3 Thus, if N is a 6th power, then this would certainly work. Say N = A6 which can be written as (A3)2 or (A2)3. So, pick 6th power of every positive integers which are less than equal to N.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return required countint SquareCube(long long int N){ int cnt = 0, i = 1; while (int(pow(i, 6)) <= N) { ++cnt; ++i; } return cnt;} int main(){ long long int N = 100000; // function call to print required answer cout << SquareCube(N); return 0;}
// Java implementation of the above approach public class GFG{ // Function to return required count static int SquareCube(long N) { int cnt = 0, i = 1; while ((int)(Math.pow(i, 6)) <= N) { ++cnt; ++i; } return cnt; } public static void main(String []args) { long N = 100000; // function call to print required answer System.out.println(SquareCube(N)) ; } // This code is contributed by Ryuga}
# Python3 implementation of the# above approach # Function to return required countdef SquareCube( N): cnt, i = 0, 1 while (i ** 6 <= N): cnt += 1 i += 1 return cnt # Driver codeN = 100000 # function call to print required# answerprint(SquareCube(N)) # This code is contributed# by saurabh_shukla
// C# implementation of the above approachusing System; public class GFG{ // Function to return required count static int SquareCube(long N) { int cnt = 0, i = 1; while ((int)(Math.Pow(i, 6)) <= N) { ++cnt; ++i; } return cnt; } public static void Main() { long N = 100000; // function call to print required answer Console.WriteLine(SquareCube(N)) ; }} /*This code is contributed by 29AjayKumar*/
<?php// PHP implementation of the// above approach // Function to return required countfunction SquareCube($N){ $cnt = 0; $i = 1; while ((pow($i, 6)) <= $N) { ++$cnt; ++$i; } return $cnt;} // Driver Code$N = 100000; // function call to print required answerecho SquareCube($N); // This code is contributed by ita_c?>
<script>// JavaScript implementation of the above approach // Function to return required countfunction SquareCube(N){ let cnt = 0, i = 1; while (Math.floor(Math.pow(i, 6)) <= N) { ++cnt; ++i; } return cnt;} let N = 100000; // function call to print required answer document.write(SquareCube(N)); // This code is contributed by Surbhi Tyagi.</script>
6
Time Complexity: O(N1/6)
Auxiliary Space: O(1), since no extra space has been taken.
saurabh_shukla
ankthon
29AjayKumar
ukasp
subhammahato348
surbhityagi15
souravmahato348
maths-cube
maths-perfect-square
number-theory
Technical Scripter 2018
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": "\n24 Jun, 2022"
},
{
"code": null,
"e": 182,
"s": 54,
"text": "Given a number N. The task is to count total numbers under N which are both perfect square and cube of some integers.Examples: "
},
{
"code": null,
"e": 255,
"s": 182,
"text": "Input: N = 100\nOutput: 2\nThey are 1 and 64.\n\nInput: N = 100000\nOutput: 6"
},
{
"code": null,
"e": 673,
"s": 255,
"text": "Approach: For a given positive number N to be a perfect square, it must satisfy P2 = N Similarly, Q3 = N for a perfect cube where P and Q are some positive integers. N = P2 = Q3 Thus, if N is a 6th power, then this would certainly work. Say N = A6 which can be written as (A3)2 or (A2)3. So, pick 6th power of every positive integers which are less than equal to N.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 677,
"s": 673,
"text": "C++"
},
{
"code": null,
"e": 682,
"s": 677,
"text": "Java"
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Python3"
},
{
"code": null,
"e": 693,
"s": 690,
"text": "C#"
},
{
"code": null,
"e": 697,
"s": 693,
"text": "PHP"
},
{
"code": null,
"e": 708,
"s": 697,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to return required countint SquareCube(long long int N){ int cnt = 0, i = 1; while (int(pow(i, 6)) <= N) { ++cnt; ++i; } return cnt;} int main(){ long long int N = 100000; // function call to print required answer cout << SquareCube(N); return 0;}",
"e": 1098,
"s": 708,
"text": null
},
{
"code": "// Java implementation of the above approach public class GFG{ // Function to return required count static int SquareCube(long N) { int cnt = 0, i = 1; while ((int)(Math.pow(i, 6)) <= N) { ++cnt; ++i; } return cnt; } public static void main(String []args) { long N = 100000; // function call to print required answer System.out.println(SquareCube(N)) ; } // This code is contributed by Ryuga}",
"e": 1612,
"s": 1098,
"text": null
},
{
"code": "# Python3 implementation of the# above approach # Function to return required countdef SquareCube( N): cnt, i = 0, 1 while (i ** 6 <= N): cnt += 1 i += 1 return cnt # Driver codeN = 100000 # function call to print required# answerprint(SquareCube(N)) # This code is contributed# by saurabh_shukla",
"e": 1935,
"s": 1612,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; public class GFG{ // Function to return required count static int SquareCube(long N) { int cnt = 0, i = 1; while ((int)(Math.Pow(i, 6)) <= N) { ++cnt; ++i; } return cnt; } public static void Main() { long N = 100000; // function call to print required answer Console.WriteLine(SquareCube(N)) ; }} /*This code is contributed by 29AjayKumar*/",
"e": 2456,
"s": 1935,
"text": null
},
{
"code": "<?php// PHP implementation of the// above approach // Function to return required countfunction SquareCube($N){ $cnt = 0; $i = 1; while ((pow($i, 6)) <= $N) { ++$cnt; ++$i; } return $cnt;} // Driver Code$N = 100000; // function call to print required answerecho SquareCube($N); // This code is contributed by ita_c?>",
"e": 2807,
"s": 2456,
"text": null
},
{
"code": "<script>// JavaScript implementation of the above approach // Function to return required countfunction SquareCube(N){ let cnt = 0, i = 1; while (Math.floor(Math.pow(i, 6)) <= N) { ++cnt; ++i; } return cnt;} let N = 100000; // function call to print required answer document.write(SquareCube(N)); // This code is contributed by Surbhi Tyagi.</script>",
"e": 3199,
"s": 2807,
"text": null
},
{
"code": null,
"e": 3201,
"s": 3199,
"text": "6"
},
{
"code": null,
"e": 3228,
"s": 3203,
"text": "Time Complexity: O(N1/6)"
},
{
"code": null,
"e": 3288,
"s": 3228,
"text": "Auxiliary Space: O(1), since no extra space has been taken."
},
{
"code": null,
"e": 3303,
"s": 3288,
"text": "saurabh_shukla"
},
{
"code": null,
"e": 3311,
"s": 3303,
"text": "ankthon"
},
{
"code": null,
"e": 3323,
"s": 3311,
"text": "29AjayKumar"
},
{
"code": null,
"e": 3329,
"s": 3323,
"text": "ukasp"
},
{
"code": null,
"e": 3345,
"s": 3329,
"text": "subhammahato348"
},
{
"code": null,
"e": 3359,
"s": 3345,
"text": "surbhityagi15"
},
{
"code": null,
"e": 3375,
"s": 3359,
"text": "souravmahato348"
},
{
"code": null,
"e": 3386,
"s": 3375,
"text": "maths-cube"
},
{
"code": null,
"e": 3407,
"s": 3386,
"text": "maths-perfect-square"
},
{
"code": null,
"e": 3421,
"s": 3407,
"text": "number-theory"
},
{
"code": null,
"e": 3445,
"s": 3421,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3458,
"s": 3445,
"text": "Mathematical"
},
{
"code": null,
"e": 3472,
"s": 3458,
"text": "number-theory"
},
{
"code": null,
"e": 3485,
"s": 3472,
"text": "Mathematical"
}
] |
Find maximum (or minimum) sum of a subarray of size k
|
08 Jul, 2022
Given an array of integers and a number k, find the maximum sum of a subarray of size k.
Examples:
Input : arr[] = {100, 200, 300, 400}
k = 2
Output : 700
Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}
k = 4
Output : 39
We get maximum sum by adding subarray {4, 2, 10, 23}
of size 4.
Input : arr[] = {2, 3}
k = 3
Output : Invalid
There is no subarray of size 3 as size of whole
array is 2.
A Simple Solution is to generate all subarrays of size k, compute their sums and finally return the maximum of all sums. The time complexity of this solution is O(n*k).
An Efficient Solution is based on the fact that sum of a subarray (or window) of size k can be obtained in O(1) time using the sum of the previous subarray (or window) of size k. Except for the first subarray of size k, for other subarrays, we compute the sum by removing the first element of the last window and adding the last element of the current window.
Below is the implementation of the above idea.
C++
Java
Python3
C#
PHP
Javascript
// O(n) solution for finding maximum sum of// a subarray of size k#include <iostream>using namespace std; // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // k must be smaller than n if (n < k) { cout << "Invalid"; return -1; } // Compute sum of first window of size k int res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = max(res, curr_sum); } return res;} // Driver codeint main(){ int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << maxSum(arr, n, k); return 0;}
// JAVA Code for Find maximum (or minimum)// sum of a subarray of size kimport java.util.*; class GFG { // Returns maximum sum in a subarray of size k. public static int maxSum(int arr[], int n, int k) { // k must be smaller than n if (n < k) { System.out.println("Invalid"); return -1; } // Compute sum of first window of size k int res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = Math.max(res, curr_sum); } return res; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}; int k = 4; int n = arr.length; System.out.println(maxSum(arr, n, k)); }}// This code is contributed by Arnav Kr. Mandal.
# O(n) solution in Python3 for finding# maximum sum of a subarray of size k # Returns maximum sum in# a subarray of size k.def maxSum(arr, n, k): # k must be smaller than n if (n < k): print("Invalid") return -1 # Compute sum of first # window of size k res = 0 for i in range(k): res += arr[i] # Compute sums of remaining windows by # removing first element of previous # window and adding last element of # current window. curr_sum = res for i in range(k, n): curr_sum += arr[i] - arr[i-k] res = max(res, curr_sum) return res # Driver codearr = [1, 4, 2, 10, 2, 3, 1, 0, 20]k = 4n = len(arr)print(maxSum(arr, n, k)) # This code is contributed by Anant Agarwal.
// C# Code for Find maximum (or minimum)// sum of a subarray of size kusing System; class GFG { // Returns maximum sum in // a subarray of size k. public static int maxSum(int []arr, int n, int k) { // k must be smaller than n if (n < k) { Console.Write("Invalid"); return -1; } // Compute sum of first window of size k int res = 0; for (int i = 0; i < k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int curr_sum = res; for (int i = k; i < n; i++) { curr_sum += arr[i] - arr[i - k]; res = Math.Max(res, curr_sum); } return res; } // Driver Code public static void Main() { int []arr = {1, 4, 2, 10, 2, 3, 1, 0, 20}; int k = 4; int n = arr.Length; Console.Write(maxSum(arr, n, k)); }} // This code is contributed by nitin mittal.
<?php// O(n) solution for finding maximum// sum of a subarray of size k // Returns maximum sum in a// subarray of size k.function maxSum($arr, $n, $k){ // k must be smaller than n if ($n < $k) { echo "Invalid"; return -1; } // Compute sum of first // window of size k $res = 0; for($i = 0; $i < $k; $i++) $res += $arr[$i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. $curr_sum = $res; for($i = $k; $i < $n; $i++) { $curr_sum += $arr[$i] - $arr[$i - $k]; $res = max($res, $curr_sum); } return $res;} // Driver Code $arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20); $k = 4; $n = sizeof($arr); echo maxSum($arr, $n, $k); // This code is contributed by nitin mittal.?>
<script> // JAVA SCRIPT Code for Find maximum (or minimum) // sum of a subarray of size k // Returns maximum sum in a subarray of size k. function maxSum(arr,n,k) { // k must be smaller than n if (n < k) { document.write("Invalid"); return -1; } // Compute sum of first window of size k let res = 0; for (let i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. let curr_sum = res; for (let i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = Math.max(res, curr_sum); } return res; } /* Driver program to test above function */ let arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]; let k = 4; let n = arr.length; document.write(maxSum(arr, n, k)); // This code is contributed by sravan kumar Gottumukkala</script>
24
Time Complexity: O(n)Auxiliary Space: O(1)
This article is contributed by Abhishek Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
nitin mittal
tapas139
sravankumar8128
rohitofficial2001
hardikkoriintern
sliding-window
subarray
subarray-sum
Arrays
Misc
Misc
sliding-window
Arrays
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 142,
"s": 52,
"text": "Given an array of integers and a number k, find the maximum sum of a subarray of size k. "
},
{
"code": null,
"e": 153,
"s": 142,
"text": "Examples: "
},
{
"code": null,
"e": 478,
"s": 153,
"text": "Input : arr[] = {100, 200, 300, 400}\n k = 2\nOutput : 700\n\nInput : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}\n k = 4 \nOutput : 39\nWe get maximum sum by adding subarray {4, 2, 10, 23}\nof size 4.\n\nInput : arr[] = {2, 3}\n k = 3\nOutput : Invalid\nThere is no subarray of size 3 as size of whole\narray is 2. "
},
{
"code": null,
"e": 647,
"s": 478,
"text": "A Simple Solution is to generate all subarrays of size k, compute their sums and finally return the maximum of all sums. The time complexity of this solution is O(n*k)."
},
{
"code": null,
"e": 1007,
"s": 647,
"text": "An Efficient Solution is based on the fact that sum of a subarray (or window) of size k can be obtained in O(1) time using the sum of the previous subarray (or window) of size k. Except for the first subarray of size k, for other subarrays, we compute the sum by removing the first element of the last window and adding the last element of the current window."
},
{
"code": null,
"e": 1055,
"s": 1007,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 1059,
"s": 1055,
"text": "C++"
},
{
"code": null,
"e": 1064,
"s": 1059,
"text": "Java"
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Python3"
},
{
"code": null,
"e": 1075,
"s": 1072,
"text": "C#"
},
{
"code": null,
"e": 1079,
"s": 1075,
"text": "PHP"
},
{
"code": null,
"e": 1090,
"s": 1079,
"text": "Javascript"
},
{
"code": "// O(n) solution for finding maximum sum of// a subarray of size k#include <iostream>using namespace std; // Returns maximum sum in a subarray of size k.int maxSum(int arr[], int n, int k){ // k must be smaller than n if (n < k) { cout << \"Invalid\"; return -1; } // Compute sum of first window of size k int res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = max(res, curr_sum); } return res;} // Driver codeint main(){ int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << maxSum(arr, n, k); return 0;}",
"e": 1949,
"s": 1090,
"text": null
},
{
"code": "// JAVA Code for Find maximum (or minimum)// sum of a subarray of size kimport java.util.*; class GFG { // Returns maximum sum in a subarray of size k. public static int maxSum(int arr[], int n, int k) { // k must be smaller than n if (n < k) { System.out.println(\"Invalid\"); return -1; } // Compute sum of first window of size k int res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = Math.max(res, curr_sum); } return res; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {1, 4, 2, 10, 2, 3, 1, 0, 20}; int k = 4; int n = arr.length; System.out.println(maxSum(arr, n, k)); }}// This code is contributed by Arnav Kr. Mandal.",
"e": 3080,
"s": 1949,
"text": null
},
{
"code": "# O(n) solution in Python3 for finding# maximum sum of a subarray of size k # Returns maximum sum in# a subarray of size k.def maxSum(arr, n, k): # k must be smaller than n if (n < k): print(\"Invalid\") return -1 # Compute sum of first # window of size k res = 0 for i in range(k): res += arr[i] # Compute sums of remaining windows by # removing first element of previous # window and adding last element of # current window. curr_sum = res for i in range(k, n): curr_sum += arr[i] - arr[i-k] res = max(res, curr_sum) return res # Driver codearr = [1, 4, 2, 10, 2, 3, 1, 0, 20]k = 4n = len(arr)print(maxSum(arr, n, k)) # This code is contributed by Anant Agarwal.",
"e": 3835,
"s": 3080,
"text": null
},
{
"code": "// C# Code for Find maximum (or minimum)// sum of a subarray of size kusing System; class GFG { // Returns maximum sum in // a subarray of size k. public static int maxSum(int []arr, int n, int k) { // k must be smaller than n if (n < k) { Console.Write(\"Invalid\"); return -1; } // Compute sum of first window of size k int res = 0; for (int i = 0; i < k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. int curr_sum = res; for (int i = k; i < n; i++) { curr_sum += arr[i] - arr[i - k]; res = Math.Max(res, curr_sum); } return res; } // Driver Code public static void Main() { int []arr = {1, 4, 2, 10, 2, 3, 1, 0, 20}; int k = 4; int n = arr.Length; Console.Write(maxSum(arr, n, k)); }} // This code is contributed by nitin mittal.",
"e": 4982,
"s": 3835,
"text": null
},
{
"code": "<?php// O(n) solution for finding maximum// sum of a subarray of size k // Returns maximum sum in a// subarray of size k.function maxSum($arr, $n, $k){ // k must be smaller than n if ($n < $k) { echo \"Invalid\"; return -1; } // Compute sum of first // window of size k $res = 0; for($i = 0; $i < $k; $i++) $res += $arr[$i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. $curr_sum = $res; for($i = $k; $i < $n; $i++) { $curr_sum += $arr[$i] - $arr[$i - $k]; $res = max($res, $curr_sum); } return $res;} // Driver Code $arr = array(1, 4, 2, 10, 2, 3, 1, 0, 20); $k = 4; $n = sizeof($arr); echo maxSum($arr, $n, $k); // This code is contributed by nitin mittal.?>",
"e": 5856,
"s": 4982,
"text": null
},
{
"code": "<script> // JAVA SCRIPT Code for Find maximum (or minimum) // sum of a subarray of size k // Returns maximum sum in a subarray of size k. function maxSum(arr,n,k) { // k must be smaller than n if (n < k) { document.write(\"Invalid\"); return -1; } // Compute sum of first window of size k let res = 0; for (let i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. let curr_sum = res; for (let i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = Math.max(res, curr_sum); } return res; } /* Driver program to test above function */ let arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]; let k = 4; let n = arr.length; document.write(maxSum(arr, n, k)); // This code is contributed by sravan kumar Gottumukkala</script>",
"e": 6917,
"s": 5856,
"text": null
},
{
"code": null,
"e": 6920,
"s": 6917,
"text": "24"
},
{
"code": null,
"e": 6964,
"s": 6920,
"text": "Time Complexity: O(n)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 7233,
"s": 6964,
"text": "This article is contributed by Abhishek Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7246,
"s": 7233,
"text": "nitin mittal"
},
{
"code": null,
"e": 7255,
"s": 7246,
"text": "tapas139"
},
{
"code": null,
"e": 7271,
"s": 7255,
"text": "sravankumar8128"
},
{
"code": null,
"e": 7289,
"s": 7271,
"text": "rohitofficial2001"
},
{
"code": null,
"e": 7306,
"s": 7289,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 7321,
"s": 7306,
"text": "sliding-window"
},
{
"code": null,
"e": 7330,
"s": 7321,
"text": "subarray"
},
{
"code": null,
"e": 7343,
"s": 7330,
"text": "subarray-sum"
},
{
"code": null,
"e": 7350,
"s": 7343,
"text": "Arrays"
},
{
"code": null,
"e": 7355,
"s": 7350,
"text": "Misc"
},
{
"code": null,
"e": 7360,
"s": 7355,
"text": "Misc"
},
{
"code": null,
"e": 7375,
"s": 7360,
"text": "sliding-window"
},
{
"code": null,
"e": 7382,
"s": 7375,
"text": "Arrays"
},
{
"code": null,
"e": 7387,
"s": 7382,
"text": "Misc"
}
] |
DATENAME() Function in SQL Server
|
18 Jan, 2021
DATENAME() function :
This function in SQL Server is used to find a given part of the specified date. Moreover, it returns the output value as a string.
Features :
This function is used to find a given part of the specified date.
This function comes under Date Functions.
This function accepts two parameters namely interval and date.
This function can also include time in the date section.
This function returns the output in string form.
Syntax :
DATENAME(interval, date)
Parameter :
This method accepts two parameters as given below.
interval –It is the specified part that is to be returned. Moreover, the values of the interval can be as given below.
year, yyyy, yy = Year, which is the specified year.
quarter, qq, q = Quarter, which is the specified quarter.
month, mm, m = month, which is the specified month.
dayofyear, dy, y = Day of the year, which is the specified day of the year.
day, dd, d = Day, which is the specified day.
week, ww, wk = Week, which is the specified week.
weekday, dw, w = Weekday, which is the specified week day.
hour, hh = hour, which is the specified hour.
minute, mi, n = Minute, which is the specified minute.
second, ss, s = Second, which is the specified second.
millisecond, ms = Millisecond, which is the specified millisecond.
date –It is the specified date which is to be used.
Returns :
It returns a given part of the specified date.
Example-1 :
Using DATENAME() function and getting the year part of the specified date.
SELECT DATENAME(year, '2021/01/06');
Output :
2021
Example-2 :
Using DATENAME() function and getting the month part of the specified date.
SELECT DATENAME(month, '2021/01/06');
Output :
January
Example-3 :
Using DATENAME() function and getting the day part of the specified date.
SELECT DATENAME(day, '2021/01/06');
Output :
6
Example-4 :
Using DATENAME() function and getting the hour part of the specified date which includes time as well.
SELECT DATENAME(hour, '2021/01/06 05:30');
Output :
5
Example-5 :
Using DATENAME() function and getting the second part of the specified date which includes time as well using a variable.
DECLARE @date VARCHAR(50);
SET @date = '2019/06/05 07:37:54';
SELECT DATENAME(second, @date);
Output :
54
Application :
This function is used to find the given part of the specified date.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "DATENAME() function :"
},
{
"code": null,
"e": 181,
"s": 50,
"text": "This function in SQL Server is used to find a given part of the specified date. Moreover, it returns the output value as a string."
},
{
"code": null,
"e": 192,
"s": 181,
"text": "Features :"
},
{
"code": null,
"e": 258,
"s": 192,
"text": "This function is used to find a given part of the specified date."
},
{
"code": null,
"e": 300,
"s": 258,
"text": "This function comes under Date Functions."
},
{
"code": null,
"e": 363,
"s": 300,
"text": "This function accepts two parameters namely interval and date."
},
{
"code": null,
"e": 420,
"s": 363,
"text": "This function can also include time in the date section."
},
{
"code": null,
"e": 469,
"s": 420,
"text": "This function returns the output in string form."
},
{
"code": null,
"e": 478,
"s": 469,
"text": "Syntax :"
},
{
"code": null,
"e": 503,
"s": 478,
"text": "DATENAME(interval, date)"
},
{
"code": null,
"e": 515,
"s": 503,
"text": "Parameter :"
},
{
"code": null,
"e": 566,
"s": 515,
"text": "This method accepts two parameters as given below."
},
{
"code": null,
"e": 685,
"s": 566,
"text": "interval –It is the specified part that is to be returned. Moreover, the values of the interval can be as given below."
},
{
"code": null,
"e": 1336,
"s": 685,
"text": "year, yyyy, yy = Year, which is the specified year.\nquarter, qq, q = Quarter, which is the specified quarter.\nmonth, mm, m = month, which is the specified month.\ndayofyear, dy, y = Day of the year, which is the specified day of the year.\nday, dd, d = Day, which is the specified day.\nweek, ww, wk = Week, which is the specified week.\nweekday, dw, w = Weekday, which is the specified week day.\nhour, hh = hour, which is the specified hour.\nminute, mi, n = Minute, which is the specified minute.\nsecond, ss, s = Second, which is the specified second.\nmillisecond, ms = Millisecond, which is the specified millisecond."
},
{
"code": null,
"e": 1388,
"s": 1336,
"text": "date –It is the specified date which is to be used."
},
{
"code": null,
"e": 1398,
"s": 1388,
"text": "Returns :"
},
{
"code": null,
"e": 1445,
"s": 1398,
"text": "It returns a given part of the specified date."
},
{
"code": null,
"e": 1457,
"s": 1445,
"text": "Example-1 :"
},
{
"code": null,
"e": 1532,
"s": 1457,
"text": "Using DATENAME() function and getting the year part of the specified date."
},
{
"code": null,
"e": 1569,
"s": 1532,
"text": "SELECT DATENAME(year, '2021/01/06');"
},
{
"code": null,
"e": 1578,
"s": 1569,
"text": "Output :"
},
{
"code": null,
"e": 1583,
"s": 1578,
"text": "2021"
},
{
"code": null,
"e": 1595,
"s": 1583,
"text": "Example-2 :"
},
{
"code": null,
"e": 1671,
"s": 1595,
"text": "Using DATENAME() function and getting the month part of the specified date."
},
{
"code": null,
"e": 1709,
"s": 1671,
"text": "SELECT DATENAME(month, '2021/01/06');"
},
{
"code": null,
"e": 1718,
"s": 1709,
"text": "Output :"
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "January"
},
{
"code": null,
"e": 1738,
"s": 1726,
"text": "Example-3 :"
},
{
"code": null,
"e": 1812,
"s": 1738,
"text": "Using DATENAME() function and getting the day part of the specified date."
},
{
"code": null,
"e": 1848,
"s": 1812,
"text": "SELECT DATENAME(day, '2021/01/06');"
},
{
"code": null,
"e": 1857,
"s": 1848,
"text": "Output :"
},
{
"code": null,
"e": 1859,
"s": 1857,
"text": "6"
},
{
"code": null,
"e": 1871,
"s": 1859,
"text": "Example-4 :"
},
{
"code": null,
"e": 1974,
"s": 1871,
"text": "Using DATENAME() function and getting the hour part of the specified date which includes time as well."
},
{
"code": null,
"e": 2017,
"s": 1974,
"text": "SELECT DATENAME(hour, '2021/01/06 05:30');"
},
{
"code": null,
"e": 2026,
"s": 2017,
"text": "Output :"
},
{
"code": null,
"e": 2028,
"s": 2026,
"text": "5"
},
{
"code": null,
"e": 2040,
"s": 2028,
"text": "Example-5 :"
},
{
"code": null,
"e": 2162,
"s": 2040,
"text": "Using DATENAME() function and getting the second part of the specified date which includes time as well using a variable."
},
{
"code": null,
"e": 2256,
"s": 2162,
"text": "DECLARE @date VARCHAR(50);\nSET @date = '2019/06/05 07:37:54';\nSELECT DATENAME(second, @date);"
},
{
"code": null,
"e": 2265,
"s": 2256,
"text": "Output :"
},
{
"code": null,
"e": 2268,
"s": 2265,
"text": "54"
},
{
"code": null,
"e": 2282,
"s": 2268,
"text": "Application :"
},
{
"code": null,
"e": 2350,
"s": 2282,
"text": "This function is used to find the given part of the specified date."
},
{
"code": null,
"e": 2359,
"s": 2350,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2370,
"s": 2359,
"text": "SQL-Server"
},
{
"code": null,
"e": 2374,
"s": 2370,
"text": "SQL"
},
{
"code": null,
"e": 2378,
"s": 2374,
"text": "SQL"
},
{
"code": null,
"e": 2476,
"s": 2378,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2542,
"s": 2476,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2566,
"s": 2542,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2598,
"s": 2566,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2615,
"s": 2598,
"text": "SQL using Python"
},
{
"code": null,
"e": 2648,
"s": 2615,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2726,
"s": 2648,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2756,
"s": 2726,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2792,
"s": 2756,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2823,
"s": 2792,
"text": "SQL Query to Compare Two Dates"
}
] |
PHP | Change strings in an array to uppercase
|
06 Mar, 2018
You are given an array of strings. You have to change all of the strings present in the given array to uppercase no matter in which case they are currently. Print the resultant array.
Examples:
Input : arr[] = ("geeks", "For", "GEEks")
Output : Array ([0]=>GEEKS [1]=>FOR [2]=>GEEKS)
Input : arr[] = ("geeks")
Output : Array ([0]=>GEEKS)
To solve this problem one of the basic approach is to iterate over all string of input array and then change them to uppercase on by one and print them. Iterating over array makes a quite use of for loop in program which can be avoided by using some smart methods like array_change_key_case() and array_flip(). What we have to do is just flip the array keys to value and vice-versa after that change the case of new keys of array which actually changes the case of original strings value and then again flip the key and values by array_flip().
Below is the step by step process:
use array_flip() function swap keys with the values present in the array.That is, the keys will now become values and their respective values will be their new keys.use array_change_key_case() function to change case of current keys(original values).use array_flip() function again to flip key and values of array to obtainoriginal array where strings value are in upper case.
use array_flip() function swap keys with the values present in the array.That is, the keys will now become values and their respective values will be their new keys.
use array_change_key_case() function to change case of current keys(original values).
use array_flip() function again to flip key and values of array to obtainoriginal array where strings value are in upper case.
Below is the implementation of above approach in PHP:
<?php // Program to change strings in an array to upper case $input = array("Practice", "ON", "GeeKs", "is best"); // print array before conversion of stringprint"Array before string conversion:\n";print_r($input); // Step 1: flip array key => value$input = array_flip($input); // Step 2: change case of new keys to upper$input = array_change_key_case($input, CASE_UPPER); // Step 3: reverse the flip process to // regain strings as value$input = array_flip($input); // print array after conversion of stringprint"\nArray after string conversion:\n";print_r($input); ?>
Output :
Array before string conversion:
Array
(
[0] => Practice
[1] => ON
[2] => GeeKs
[3] => is best
)
Array after string conversion:
Array
(
[0] => PRACTICE
[1] => ON
[2] => GEEKS
[3] => IS BEST
)
PHP-array
PHP-basics
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Mar, 2018"
},
{
"code": null,
"e": 212,
"s": 28,
"text": "You are given an array of strings. You have to change all of the strings present in the given array to uppercase no matter in which case they are currently. Print the resultant array."
},
{
"code": null,
"e": 222,
"s": 212,
"text": "Examples:"
},
{
"code": null,
"e": 369,
"s": 222,
"text": "Input : arr[] = (\"geeks\", \"For\", \"GEEks\")\nOutput : Array ([0]=>GEEKS [1]=>FOR [2]=>GEEKS)\n\nInput : arr[] = (\"geeks\")\nOutput : Array ([0]=>GEEKS)\n"
},
{
"code": null,
"e": 913,
"s": 369,
"text": "To solve this problem one of the basic approach is to iterate over all string of input array and then change them to uppercase on by one and print them. Iterating over array makes a quite use of for loop in program which can be avoided by using some smart methods like array_change_key_case() and array_flip(). What we have to do is just flip the array keys to value and vice-versa after that change the case of new keys of array which actually changes the case of original strings value and then again flip the key and values by array_flip()."
},
{
"code": null,
"e": 948,
"s": 913,
"text": "Below is the step by step process:"
},
{
"code": null,
"e": 1325,
"s": 948,
"text": "use array_flip() function swap keys with the values present in the array.That is, the keys will now become values and their respective values will be their new keys.use array_change_key_case() function to change case of current keys(original values).use array_flip() function again to flip key and values of array to obtainoriginal array where strings value are in upper case."
},
{
"code": null,
"e": 1491,
"s": 1325,
"text": "use array_flip() function swap keys with the values present in the array.That is, the keys will now become values and their respective values will be their new keys."
},
{
"code": null,
"e": 1577,
"s": 1491,
"text": "use array_change_key_case() function to change case of current keys(original values)."
},
{
"code": null,
"e": 1704,
"s": 1577,
"text": "use array_flip() function again to flip key and values of array to obtainoriginal array where strings value are in upper case."
},
{
"code": null,
"e": 1758,
"s": 1704,
"text": "Below is the implementation of above approach in PHP:"
},
{
"code": "<?php // Program to change strings in an array to upper case $input = array(\"Practice\", \"ON\", \"GeeKs\", \"is best\"); // print array before conversion of stringprint\"Array before string conversion:\\n\";print_r($input); // Step 1: flip array key => value$input = array_flip($input); // Step 2: change case of new keys to upper$input = array_change_key_case($input, CASE_UPPER); // Step 3: reverse the flip process to // regain strings as value$input = array_flip($input); // print array after conversion of stringprint\"\\nArray after string conversion:\\n\";print_r($input); ?>",
"e": 2336,
"s": 1758,
"text": null
},
{
"code": null,
"e": 2345,
"s": 2336,
"text": "Output :"
},
{
"code": null,
"e": 2570,
"s": 2345,
"text": "Array before string conversion:\nArray\n(\n [0] => Practice\n [1] => ON\n [2] => GeeKs\n [3] => is best\n)\n\nArray after string conversion:\nArray\n(\n [0] => PRACTICE\n [1] => ON\n [2] => GEEKS\n [3] => IS BEST\n)\n"
},
{
"code": null,
"e": 2580,
"s": 2570,
"text": "PHP-array"
},
{
"code": null,
"e": 2591,
"s": 2580,
"text": "PHP-basics"
},
{
"code": null,
"e": 2602,
"s": 2591,
"text": "PHP-string"
},
{
"code": null,
"e": 2606,
"s": 2602,
"text": "PHP"
},
{
"code": null,
"e": 2623,
"s": 2606,
"text": "Web Technologies"
},
{
"code": null,
"e": 2627,
"s": 2623,
"text": "PHP"
},
{
"code": null,
"e": 2725,
"s": 2627,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2770,
"s": 2725,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2820,
"s": 2770,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2844,
"s": 2820,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 2896,
"s": 2844,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2936,
"s": 2896,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2998,
"s": 2936,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3031,
"s": 2998,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3092,
"s": 3031,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3142,
"s": 3092,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to iterate LinkedHashMap in Java?
|
19 Jan, 2021
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted.
There are basically two ways to iterate over LinkedHashMap:
Using keySet() and get() MethodUsing entrySet() and Iterator
Using keySet() and get() Method
Using entrySet() and Iterator
Method 1: Iterating LinkedHashMap using keySet() and get() Method
Syntax:
linked_hash_map.keySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having the keys of the LinkedHashMap.
Through keySet() method we will obtain a set having keys of the map.
And then after running a loop over this set, we can obtain each key and its value using get() method.
Java
// Java Program to iterate through LinkedHashMap using // keySet() and get() Method import java.util.LinkedHashMap;import java.util.Set; public class GFG { public static void main(String a[]) { // making the object of LinkedHashMap LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>(); // adding the elements in linkedHashMap linkedHashMap.put("One", "First element"); linkedHashMap.put("Two", "Second element"); linkedHashMap.put("Three", "Third element"); Set<String> keys = linkedHashMap.keySet(); // printing the elements of LinkedHashMap for (String key : keys) { System.out.println(key + " -- " + linkedHashMap.get(key)); } }}
One -- First element
Two -- Second element
Three -- Third element
Method 2: Iterating LinkedHashMap using entrySet() and Iterator
Syntax:
Linkedhash_map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the LinkedHashMap.
Java
// Java Program to iterate over linkedHashMap using// entrySet() and iterator import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Set; public class GFG { public static void main(String[] args) { // Create a LinkedHashMap and populate it with // elements LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>(); // adding the elements to the linkedHashMap linkedHashMap.put("One", "First element"); linkedHashMap.put("Two", "Second element"); linkedHashMap.put("Three", "Third element"); // Get a set of all the entries (key - value pairs) // contained in the LinkesHashMap Set entrySet = linkedHashMap.entrySet(); // Obtain an Iterator for the entries Set Iterator it = entrySet.iterator(); // Iterate through LinkedHashMap entries System.out.println("LinkedHashMap entries : "); while (it.hasNext()) // iterating over each element using it.next() // method System.out.println(it.next()); }}
LinkedHashMap entries :
One=First element
Two=Second element
Three=Third element
Java-Collections
Java-LinkedHashMap
Picked
Technical Scripter 2020
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jan, 2021"
},
{
"code": null,
"e": 326,
"s": 28,
"text": "LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted."
},
{
"code": null,
"e": 386,
"s": 326,
"text": "There are basically two ways to iterate over LinkedHashMap:"
},
{
"code": null,
"e": 447,
"s": 386,
"text": "Using keySet() and get() MethodUsing entrySet() and Iterator"
},
{
"code": null,
"e": 479,
"s": 447,
"text": "Using keySet() and get() Method"
},
{
"code": null,
"e": 509,
"s": 479,
"text": "Using entrySet() and Iterator"
},
{
"code": null,
"e": 575,
"s": 509,
"text": "Method 1: Iterating LinkedHashMap using keySet() and get() Method"
},
{
"code": null,
"e": 583,
"s": 575,
"text": "Syntax:"
},
{
"code": null,
"e": 608,
"s": 583,
"text": "linked_hash_map.keySet()"
},
{
"code": null,
"e": 660,
"s": 608,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 737,
"s": 660,
"text": "Return Value: The method returns a set having the keys of the LinkedHashMap."
},
{
"code": null,
"e": 806,
"s": 737,
"text": "Through keySet() method we will obtain a set having keys of the map."
},
{
"code": null,
"e": 908,
"s": 806,
"text": "And then after running a loop over this set, we can obtain each key and its value using get() method."
},
{
"code": null,
"e": 913,
"s": 908,
"text": "Java"
},
{
"code": "// Java Program to iterate through LinkedHashMap using // keySet() and get() Method import java.util.LinkedHashMap;import java.util.Set; public class GFG { public static void main(String a[]) { // making the object of LinkedHashMap LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>(); // adding the elements in linkedHashMap linkedHashMap.put(\"One\", \"First element\"); linkedHashMap.put(\"Two\", \"Second element\"); linkedHashMap.put(\"Three\", \"Third element\"); Set<String> keys = linkedHashMap.keySet(); // printing the elements of LinkedHashMap for (String key : keys) { System.out.println(key + \" -- \" + linkedHashMap.get(key)); } }}",
"e": 1741,
"s": 913,
"text": null
},
{
"code": null,
"e": 1808,
"s": 1741,
"text": "One -- First element\nTwo -- Second element\nThree -- Third element\n"
},
{
"code": null,
"e": 1872,
"s": 1808,
"text": "Method 2: Iterating LinkedHashMap using entrySet() and Iterator"
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "Syntax:"
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "Linkedhash_map.entrySet()"
},
{
"code": null,
"e": 1958,
"s": 1906,
"text": "Parameters: The method does not take any parameter."
},
{
"code": null,
"e": 2040,
"s": 1958,
"text": "Return Value: The method returns a set having same elements as the LinkedHashMap."
},
{
"code": null,
"e": 2045,
"s": 2040,
"text": "Java"
},
{
"code": "// Java Program to iterate over linkedHashMap using// entrySet() and iterator import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Set; public class GFG { public static void main(String[] args) { // Create a LinkedHashMap and populate it with // elements LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>(); // adding the elements to the linkedHashMap linkedHashMap.put(\"One\", \"First element\"); linkedHashMap.put(\"Two\", \"Second element\"); linkedHashMap.put(\"Three\", \"Third element\"); // Get a set of all the entries (key - value pairs) // contained in the LinkesHashMap Set entrySet = linkedHashMap.entrySet(); // Obtain an Iterator for the entries Set Iterator it = entrySet.iterator(); // Iterate through LinkedHashMap entries System.out.println(\"LinkedHashMap entries : \"); while (it.hasNext()) // iterating over each element using it.next() // method System.out.println(it.next()); }}",
"e": 3159,
"s": 2045,
"text": null
},
{
"code": null,
"e": 3242,
"s": 3159,
"text": "LinkedHashMap entries : \nOne=First element\nTwo=Second element\nThree=Third element\n"
},
{
"code": null,
"e": 3259,
"s": 3242,
"text": "Java-Collections"
},
{
"code": null,
"e": 3278,
"s": 3259,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 3285,
"s": 3278,
"text": "Picked"
},
{
"code": null,
"e": 3309,
"s": 3285,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3314,
"s": 3309,
"text": "Java"
},
{
"code": null,
"e": 3328,
"s": 3314,
"text": "Java Programs"
},
{
"code": null,
"e": 3333,
"s": 3328,
"text": "Java"
},
{
"code": null,
"e": 3350,
"s": 3333,
"text": "Java-Collections"
}
] |
Plotting graph For IRIS Dataset Using Seaborn And Matplotlib
|
04 Mar, 2021
Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand and classify the dataset.
Seaborn provides a beautiful with different styled graph plotting that make our dataset more distinguishable and attractive.
To install the package write the below code in terminal of ubuntu/Linux or Window Command prompt.
pip install matplotlib
pip install seaborn
Attribute Information about data set:
Attribute Information:
-> sepal length in cm
-> sepal width in cm
-> petal length in cm
-> petal width in cm
-> class:
Iris Setosa
Iris Versicolour
Iris Virginica
Number of Instances: 150
Summary Statistics:
Min Max Mean SD Class Correlation
sepal length: 4.3 7.9 5.84 0.83 0.7826
sepal width: 2.0 4.4 3.05 0.43 -0.4194
petal length: 1.0 6.9 3.76 1.76 0.9490 (high!)
petal width: 0.1 2.5 1.20 0.76 0.9565 (high!)
Class Distribution: 33.3% for each of 3 classes.
To get the Iris Data click here.
Loading data
Python3
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv("Iris.csv") print (data.head(10))
Output:
Plotting Using Matplotlib
Python3
import pandas as pdimport matplotlib.pyplot as pltiris = pd.read_csv("Iris.csv") plt.plot(iris.Id, iris["SepalLengthCm"], "r--")plt.show
Scatter Plot
Python3
iris.plot(kind ="scatter", x ='SepalLengthCm', y ='PetalLengthCm')plt.grid()
Plotting using Seaborn
Python3
import seaborn as sns iris = sns.load_dataset('iris') # style used as a theme of graph# for example if we want black# graph with grid then write "darkgrid"sns.set_style("whitegrid") # sepal_length, petal_length are iris# feature data height used to define# Height of graph whereas hue store the# class of iris dataset.sns.FacetGrid(iris, hue ="species", height = 6).map(plt.scatter, 'sepal_length', 'petal_length').add_legend()
ced18i039
Python-matplotlib
python-modules
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Mar, 2021"
},
{
"code": null,
"e": 431,
"s": 53,
"text": "Matplotlib.pyplot library is most commonly used in Python in the field of machine learning. It helps in plotting the graph of large dataset. Not only this also helps in classifying different dataset. It can plot graph both in 2d and 3d format. It has a feature of legend, label, grid, graph shape, grid and many more that make it easier to understand and classify the dataset. "
},
{
"code": null,
"e": 557,
"s": 431,
"text": "Seaborn provides a beautiful with different styled graph plotting that make our dataset more distinguishable and attractive. "
},
{
"code": null,
"e": 656,
"s": 557,
"text": "To install the package write the below code in terminal of ubuntu/Linux or Window Command prompt. "
},
{
"code": null,
"e": 699,
"s": 656,
"text": "pip install matplotlib\npip install seaborn"
},
{
"code": null,
"e": 738,
"s": 699,
"text": "Attribute Information about data set: "
},
{
"code": null,
"e": 1329,
"s": 738,
"text": "Attribute Information:\n -> sepal length in cm\n -> sepal width in cm\n -> petal length in cm\n -> petal width in cm\n -> class: \n Iris Setosa\n Iris Versicolour\n Iris Virginica\n\nNumber of Instances: 150 \n\nSummary Statistics:\n Min Max Mean SD Class Correlation\n sepal length: 4.3 7.9 5.84 0.83 0.7826 \n sepal width: 2.0 4.4 3.05 0.43 -0.4194\n petal length: 1.0 6.9 3.76 1.76 0.9490 (high!)\n petal width: 0.1 2.5 1.20 0.76 0.9565 (high!)\n\nClass Distribution: 33.3% for each of 3 classes."
},
{
"code": null,
"e": 1363,
"s": 1329,
"text": "To get the Iris Data click here. "
},
{
"code": null,
"e": 1377,
"s": 1363,
"text": "Loading data "
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Python3"
},
{
"code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as plt data = pd.read_csv(\"Iris.csv\") print (data.head(10))",
"e": 1509,
"s": 1385,
"text": null
},
{
"code": null,
"e": 1518,
"s": 1509,
"text": "Output: "
},
{
"code": null,
"e": 1545,
"s": 1518,
"text": "Plotting Using Matplotlib "
},
{
"code": null,
"e": 1553,
"s": 1545,
"text": "Python3"
},
{
"code": "import pandas as pdimport matplotlib.pyplot as pltiris = pd.read_csv(\"Iris.csv\") plt.plot(iris.Id, iris[\"SepalLengthCm\"], \"r--\")plt.show",
"e": 1690,
"s": 1553,
"text": null
},
{
"code": null,
"e": 1704,
"s": 1690,
"text": "Scatter Plot "
},
{
"code": null,
"e": 1712,
"s": 1704,
"text": "Python3"
},
{
"code": "iris.plot(kind =\"scatter\", x ='SepalLengthCm', y ='PetalLengthCm')plt.grid()",
"e": 1807,
"s": 1712,
"text": null
},
{
"code": null,
"e": 1831,
"s": 1807,
"text": "Plotting using Seaborn "
},
{
"code": null,
"e": 1839,
"s": 1831,
"text": "Python3"
},
{
"code": "import seaborn as sns iris = sns.load_dataset('iris') # style used as a theme of graph# for example if we want black# graph with grid then write \"darkgrid\"sns.set_style(\"whitegrid\") # sepal_length, petal_length are iris# feature data height used to define# Height of graph whereas hue store the# class of iris dataset.sns.FacetGrid(iris, hue =\"species\", height = 6).map(plt.scatter, 'sepal_length', 'petal_length').add_legend()",
"e": 2338,
"s": 1839,
"text": null
},
{
"code": null,
"e": 2348,
"s": 2338,
"text": "ced18i039"
},
{
"code": null,
"e": 2366,
"s": 2348,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2381,
"s": 2366,
"text": "python-modules"
},
{
"code": null,
"e": 2388,
"s": 2381,
"text": "Python"
},
{
"code": null,
"e": 2404,
"s": 2388,
"text": "Write From Home"
}
] |
dplyr Package in R Programming
|
29 Nov, 2021
The dplyr package in R Programming Language is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.
By limiting the choices the focus can now be more on data manipulation difficulties.
There are uncomplicated “verbs”, functions present for tackling every common data manipulation and the thoughts can be translated into code faster.
There are valuable backends and hence waiting time for the computer reduces.
dplyr package provides various important functions that can be used for Data Manipulation. These are:
filter() Function: For choosing cases and using their values as a base for doing so.
R
# Create a data frame with missing datad < - data.frame(name=c("Abhi", "Bhavesh", "Chaman", "Dimri"), age=c(7, 5, 9, 16), ht=c(46, NA, NA, 69), school=c("yes", "yes", "no", "no"))d # Finding rows with NA valued % > % filter(is.na(ht)) # Finding rows with no NA valued % > % filter(! is.na(ht))
Output:
# A tibble: 4 x 4
name age ht school
1 Abhi 7 46 yes
2 Bhavesh 5 NA yes
3 Chaman 9 NA no
4 Dimri 16 69 no
# A tibble: 2 x 4
name age ht school
1 Bhavesh 5 NA yes
2 Chaman 9 NA no
# A tibble: 2 x 4
name age ht school
1 Abhi 7 46 yes
2 Dimri 16 69 no
arrange(): For reordering of the cases.
R
# Create a data frame with missing datad <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Arranging name according to the aged.name<- arrange(d, age)print(d.name)
Output:
# A tibble: 4 x 4
name age ht school
1 Bhavesh 5 NA yes
2 Abhi 7 46 yes
3 Chaman 9 NA no
4 Dimri 16 69 no
select() and rename(): For choosing variables and using their names as a base for doing so.
R
# Create a data frame with missing datad < - data.frame(name=c("Abhi", "Bhavesh", "Chaman", "Dimri"), age=c(7, 5, 9, 16), ht=c(46, NA, NA, 69), school=c("yes", "yes", "no", "no")) # startswith() function to print only ht dataselect(d, starts_with("ht")) # -startswith() function to print# everything except ht dataselect(d, -starts_with("ht")) # Printing column 1 to 2select(d, 1: 2) # Printing data of column# heading containing 'a'select(d, contains("a")) # Printing data of column# heading which matches 'na'select(d, matches("na"))
Output:
# A tibble: 4 x 1
ht
1 46
2 NA
3 NA
4 69
# A tibble: 4 x 3
name age school
1 Abhi 7 yes
2 Bhavesh 5 yes
3 Chaman 9 no
4 Dimri 16 no
# A tibble: 4 x 2
name age
1 Abhi 7
2 Bhavesh 5
3 Chaman 9
4 Dimri 16
# A tibble: 4 x 2
name age
1 Abhi 7
2 Bhavesh 5
3 Chaman 9
4 Dimri 16
# A tibble: 4 x 1
name
1 Abhi
2 Bhavesh
3 Chaman
4 Dimri
mutate() and transmute(): Addition of new variables which are the functions of prevailing variables.
R
# Create a data frame with missing datad <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Calculating a variable x3 which is sum of height# and age printing with ht and agemutate(d, x3 = ht + age) # Calculating a variable x3 which is sum of height# and age printing without ht and agetransmute(d, x3 = ht + age)
Output:
# A tibble: 4 x 5
name age ht school x3
1 Abhi 7 46 yes 53
2 Bhavesh 5 NA yes NA
3 Chaman 9 NA no NA
4 Dimri 16 69 no 85
# A tibble: 4 x 1
x3
1 53
2 NA
3 NA
4 85
>
summarise(): Condensing various values to one value.
R
# Create a data frame with missing datad <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Calculating mean of agesummarise(d, mean = mean(age)) # Calculating min of agesummarise(d, med = min(age)) # Calculating max of agesummarise(d, med = max(age)) # Calculating median of agesummarise(d, med = median(age))
Output:
# A tibble: 1 x 1
mean
1 9.25
# A tibble: 1 x 1
med
1 5
# A tibble: 1 x 1
med
1 16
# A tibble: 1 x 1
med
1 8
sample_n() and sample_frac(): For taking random specimens.
R
# Create a data frame with missing datad <- data.frame( name = c("Abhi", "Bhavesh", "Chaman", "Dimri"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c("yes", "yes", "no", "no") ) # Printing three rowssample_n(d, 3) # Printing 50 % of the rowssample_frac(d, 0.50)
Output:
# A tibble: 3 x 4
name age ht school
1 Abhi 7 46 yes
2 Bhavesh 5 NA yes
3 Chaman 9 NA no
# A tibble: 2 x 4
name age ht school
1 Dimri 16 69 no
2 Bhavesh 5 NA yes
kumar_satyam
R-Packages
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "The dplyr package in R Programming Language is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles."
},
{
"code": null,
"e": 295,
"s": 210,
"text": "By limiting the choices the focus can now be more on data manipulation difficulties."
},
{
"code": null,
"e": 443,
"s": 295,
"text": "There are uncomplicated “verbs”, functions present for tackling every common data manipulation and the thoughts can be translated into code faster."
},
{
"code": null,
"e": 520,
"s": 443,
"text": "There are valuable backends and hence waiting time for the computer reduces."
},
{
"code": null,
"e": 623,
"s": 520,
"text": "dplyr package provides various important functions that can be used for Data Manipulation. These are: "
},
{
"code": null,
"e": 708,
"s": 623,
"text": "filter() Function: For choosing cases and using their values as a base for doing so."
},
{
"code": null,
"e": 710,
"s": 708,
"text": "R"
},
{
"code": "# Create a data frame with missing datad < - data.frame(name=c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age=c(7, 5, 9, 16), ht=c(46, NA, NA, 69), school=c(\"yes\", \"yes\", \"no\", \"no\"))d # Finding rows with NA valued % > % filter(is.na(ht)) # Finding rows with no NA valued % > % filter(! is.na(ht))",
"e": 1075,
"s": 710,
"text": null
},
{
"code": null,
"e": 1084,
"s": 1075,
"text": "Output: "
},
{
"code": null,
"e": 1466,
"s": 1084,
"text": "# A tibble: 4 x 4\n name age ht school\n \n1 Abhi 7 46 yes \n2 Bhavesh 5 NA yes \n3 Chaman 9 NA no \n4 Dimri 16 69 no\n\n# A tibble: 2 x 4\n name age ht school\n \n1 Bhavesh 5 NA yes \n2 Chaman 9 NA no\n\n# A tibble: 2 x 4\n name age ht school\n \n1 Abhi 7 46 yes \n2 Dimri 16 69 no"
},
{
"code": null,
"e": 1506,
"s": 1466,
"text": "arrange(): For reordering of the cases."
},
{
"code": null,
"e": 1508,
"s": 1506,
"text": "R"
},
{
"code": "# Create a data frame with missing datad <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Arranging name according to the aged.name<- arrange(d, age)print(d.name)",
"e": 1820,
"s": 1508,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1820,
"text": "Output: "
},
{
"code": null,
"e": 2000,
"s": 1829,
"text": "# A tibble: 4 x 4\n name age ht school\n \n1 Bhavesh 5 NA yes \n2 Abhi 7 46 yes \n3 Chaman 9 NA no \n4 Dimri 16 69 no "
},
{
"code": null,
"e": 2092,
"s": 2000,
"text": "select() and rename(): For choosing variables and using their names as a base for doing so."
},
{
"code": null,
"e": 2094,
"s": 2092,
"text": "R"
},
{
"code": "# Create a data frame with missing datad < - data.frame(name=c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age=c(7, 5, 9, 16), ht=c(46, NA, NA, 69), school=c(\"yes\", \"yes\", \"no\", \"no\")) # startswith() function to print only ht dataselect(d, starts_with(\"ht\")) # -startswith() function to print# everything except ht dataselect(d, -starts_with(\"ht\")) # Printing column 1 to 2select(d, 1: 2) # Printing data of column# heading containing 'a'select(d, contains(\"a\")) # Printing data of column# heading which matches 'na'select(d, matches(\"na\"))",
"e": 2701,
"s": 2094,
"text": null
},
{
"code": null,
"e": 2710,
"s": 2701,
"text": "Output: "
},
{
"code": null,
"e": 3191,
"s": 2710,
"text": "# A tibble: 4 x 1\n ht\n \n1 46\n2 NA\n3 NA\n4 69\n\n# A tibble: 4 x 3\n name age school\n \n1 Abhi 7 yes \n2 Bhavesh 5 yes \n3 Chaman 9 no \n4 Dimri 16 no\n\n# A tibble: 4 x 2\n name age\n \n1 Abhi 7\n2 Bhavesh 5\n3 Chaman 9\n4 Dimri 16\n\n# A tibble: 4 x 2\n name age\n \n1 Abhi 7\n2 Bhavesh 5\n3 Chaman 9\n4 Dimri 16\n\n# A tibble: 4 x 1\n name \n \n1 Abhi \n2 Bhavesh\n3 Chaman \n4 Dimri"
},
{
"code": null,
"e": 3292,
"s": 3191,
"text": "mutate() and transmute(): Addition of new variables which are the functions of prevailing variables."
},
{
"code": null,
"e": 3294,
"s": 3292,
"text": "R"
},
{
"code": "# Create a data frame with missing datad <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Calculating a variable x3 which is sum of height# and age printing with ht and agemutate(d, x3 = ht + age) # Calculating a variable x3 which is sum of height# and age printing without ht and agetransmute(d, x3 = ht + age)",
"e": 3780,
"s": 3294,
"text": null
},
{
"code": null,
"e": 3789,
"s": 3780,
"text": "Output: "
},
{
"code": null,
"e": 4059,
"s": 3789,
"text": " \n# A tibble: 4 x 5\n name age ht school x3\n \n1 Abhi 7 46 yes 53\n2 Bhavesh 5 NA yes NA\n3 Chaman 9 NA no NA\n4 Dimri 16 69 no 85\n\n# A tibble: 4 x 1\n x3\n \n1 53\n2 NA\n3 NA\n4 85\n> "
},
{
"code": null,
"e": 4112,
"s": 4059,
"text": "summarise(): Condensing various values to one value."
},
{
"code": null,
"e": 4114,
"s": 4112,
"text": "R"
},
{
"code": "# Create a data frame with missing datad <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Calculating mean of agesummarise(d, mean = mean(age)) # Calculating min of agesummarise(d, med = min(age)) # Calculating max of agesummarise(d, med = max(age)) # Calculating median of agesummarise(d, med = median(age))",
"e": 4597,
"s": 4114,
"text": null
},
{
"code": null,
"e": 4606,
"s": 4597,
"text": "Output: "
},
{
"code": null,
"e": 4766,
"s": 4606,
"text": "# A tibble: 1 x 1\n mean\n \n1 9.25\n\n# A tibble: 1 x 1\n med\n \n1 5\n\n# A tibble: 1 x 1\n med\n \n1 16\n\n# A tibble: 1 x 1\n med\n \n1 8"
},
{
"code": null,
"e": 4825,
"s": 4766,
"text": "sample_n() and sample_frac(): For taking random specimens."
},
{
"code": null,
"e": 4827,
"s": 4825,
"text": "R"
},
{
"code": "# Create a data frame with missing datad <- data.frame( name = c(\"Abhi\", \"Bhavesh\", \"Chaman\", \"Dimri\"), age = c(7, 5, 9, 16), ht = c(46, NA, NA, 69), school = c(\"yes\", \"yes\", \"no\", \"no\") ) # Printing three rowssample_n(d, 3) # Printing 50 % of the rowssample_frac(d, 0.50)",
"e": 5173,
"s": 4827,
"text": null
},
{
"code": null,
"e": 5182,
"s": 5173,
"text": "Output: "
},
{
"code": null,
"e": 5436,
"s": 5182,
"text": "# A tibble: 3 x 4\n name age ht school\n \n1 Abhi 7 46 yes \n2 Bhavesh 5 NA yes \n3 Chaman 9 NA no \n\n# A tibble: 2 x 4\n name age ht school\n \n1 Dimri 16 69 no \n2 Bhavesh 5 NA yes "
},
{
"code": null,
"e": 5449,
"s": 5436,
"text": "kumar_satyam"
},
{
"code": null,
"e": 5460,
"s": 5449,
"text": "R-Packages"
},
{
"code": null,
"e": 5471,
"s": 5460,
"text": "R Language"
},
{
"code": null,
"e": 5569,
"s": 5471,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5614,
"s": 5569,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 5666,
"s": 5614,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5724,
"s": 5666,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 5776,
"s": 5724,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 5834,
"s": 5776,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 5866,
"s": 5834,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 5929,
"s": 5866,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 5964,
"s": 5929,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 6008,
"s": 5964,
"text": "How to change Row Names of DataFrame in R ?"
}
] |
GATE | GATE-CS-2005 | Question 73
|
28 Jun, 2021
In a packet switching network, packets are routed from source to destination along a single path having two intermediate nodes. If the message size is 24 bytes and each packet contains a header of 3 bytes, then the optimum packet size is:(A) 4(B) 6(C) 7(D) 9Answer: (D)Explanation: Dividing a message into packets may decrease the transmission time due to parallelism as shown in the following figure.
But after a certain limit reducing the packet size may increase the transmission time also.
Following figure shows the situation given in question.
Let transmission time to transfer 1 byte for all nodes be t. The first packet will take time = (packet size)*3*t. After the first packet reaches the destination, remaining packets will take time equal to (packet size)*t due to parallelism.
If we use 4 bytes as packet size, there will be 24 packets
Total Transmission time = Time taken by first packet +
Time taken by remaining packets
= 3*4*t + 23*4*t = 104t
If we use 6 bytes as packet size, there will be 8 packets
Total Transmission time = 3*6*t + 7*6*t = 60t
If we use 7 bytes as packet size, there will be 6 packets
Total Transmission time = 3*7*t + 5*7*t = 56t
If we use 9 bytes as packet size, there will be 4 packets
Total Transmission time = 3*9*t + 3*9*t = 54t
Source: question 2 of https://www.geeksforgeeks.org/computer-networks-set-6/
Related Articles:
Circuit Switching Vs Packet SwitchingQuiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE IT 2006 | Question 20
GATE | GATE-CS-2016 (Set 1) | Question 45
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 454,
"s": 52,
"text": "In a packet switching network, packets are routed from source to destination along a single path having two intermediate nodes. If the message size is 24 bytes and each packet contains a header of 3 bytes, then the optimum packet size is:(A) 4(B) 6(C) 7(D) 9Answer: (D)Explanation: Dividing a message into packets may decrease the transmission time due to parallelism as shown in the following figure."
},
{
"code": null,
"e": 546,
"s": 454,
"text": "But after a certain limit reducing the packet size may increase the transmission time also."
},
{
"code": null,
"e": 602,
"s": 546,
"text": "Following figure shows the situation given in question."
},
{
"code": null,
"e": 842,
"s": 602,
"text": "Let transmission time to transfer 1 byte for all nodes be t. The first packet will take time = (packet size)*3*t. After the first packet reaches the destination, remaining packets will take time equal to (packet size)*t due to parallelism."
},
{
"code": null,
"e": 1379,
"s": 842,
"text": "If we use 4 bytes as packet size, there will be 24 packets\nTotal Transmission time = Time taken by first packet + \n Time taken by remaining packets \n = 3*4*t + 23*4*t = 104t\n\nIf we use 6 bytes as packet size, there will be 8 packets\nTotal Transmission time = 3*6*t + 7*6*t = 60t\n\nIf we use 7 bytes as packet size, there will be 6 packets\nTotal Transmission time = 3*7*t + 5*7*t = 56t\n\nIf we use 9 bytes as packet size, there will be 4 packets\nTotal Transmission time = 3*9*t + 3*9*t = 54t\n"
},
{
"code": null,
"e": 1456,
"s": 1379,
"text": "Source: question 2 of https://www.geeksforgeeks.org/computer-networks-set-6/"
},
{
"code": null,
"e": 1474,
"s": 1456,
"text": "Related Articles:"
},
{
"code": null,
"e": 1533,
"s": 1474,
"text": "Circuit Switching Vs Packet SwitchingQuiz of this Question"
},
{
"code": null,
"e": 1546,
"s": 1533,
"text": "GATE-CS-2005"
},
{
"code": null,
"e": 1564,
"s": 1546,
"text": "GATE-GATE-CS-2005"
},
{
"code": null,
"e": 1569,
"s": 1564,
"text": "GATE"
},
{
"code": null,
"e": 1667,
"s": 1569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1709,
"s": 1667,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1771,
"s": 1709,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1805,
"s": 1771,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 1847,
"s": 1805,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1889,
"s": 1847,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1923,
"s": 1889,
"text": "GATE | GATE CS 2011 | Question 49"
},
{
"code": null,
"e": 1957,
"s": 1923,
"text": "GATE | GATE CS 1996 | Question 38"
},
{
"code": null,
"e": 1991,
"s": 1957,
"text": "GATE | GATE-CS-2004 | Question 31"
},
{
"code": null,
"e": 2025,
"s": 1991,
"text": "GATE | GATE IT 2006 | Question 20"
}
] |
Scala Set contains() method with example
|
18 Oct, 2019
The contains() method is utilized to check if an element is present in the set of not.
Method Definition: def contains(elem: A): Boolean
Return Type: It returns true if the element is present in the set else it returns false.
Example #1:
// Scala program of contains() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(41, 12, 23, 43, 1, 72) // Applying contains() method val result = s1.contains(1) // Display output print(result) } }
true
Example #2:
// Scala program of contains() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(41, 12, 23, 43, 1, 72) // Applying contains() method val result = s1.contains(10) // Display output print(result) } }
false
Scala
scala-collection
Scala-Method
Scala-Set
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Lambda Expression in Scala
How to Install Scala with VSCode?
Inheritance in Scala
Enumeration in Scala
Scala Singleton and Companion Objects
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 115,
"s": 28,
"text": "The contains() method is utilized to check if an element is present in the set of not."
},
{
"code": null,
"e": 165,
"s": 115,
"text": "Method Definition: def contains(elem: A): Boolean"
},
{
"code": null,
"e": 254,
"s": 165,
"text": "Return Type: It returns true if the element is present in the set else it returns false."
},
{
"code": null,
"e": 266,
"s": 254,
"text": "Example #1:"
},
{
"code": "// Scala program of contains() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(41, 12, 23, 43, 1, 72) // Applying contains() method val result = s1.contains(1) // Display output print(result) } } ",
"e": 636,
"s": 266,
"text": null
},
{
"code": null,
"e": 642,
"s": 636,
"text": "true\n"
},
{
"code": null,
"e": 654,
"s": 642,
"text": "Example #2:"
},
{
"code": "// Scala program of contains() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a set val s1 = Set(41, 12, 23, 43, 1, 72) // Applying contains() method val result = s1.contains(10) // Display output print(result) } } ",
"e": 1025,
"s": 654,
"text": null
},
{
"code": null,
"e": 1032,
"s": 1025,
"text": "false\n"
},
{
"code": null,
"e": 1038,
"s": 1032,
"text": "Scala"
},
{
"code": null,
"e": 1055,
"s": 1038,
"text": "scala-collection"
},
{
"code": null,
"e": 1068,
"s": 1055,
"text": "Scala-Method"
},
{
"code": null,
"e": 1078,
"s": 1068,
"text": "Scala-Set"
},
{
"code": null,
"e": 1084,
"s": 1078,
"text": "Scala"
},
{
"code": null,
"e": 1182,
"s": 1084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1208,
"s": 1182,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1220,
"s": 1208,
"text": "Scala Lists"
},
{
"code": null,
"e": 1239,
"s": 1220,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1254,
"s": 1239,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1273,
"s": 1254,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1300,
"s": 1273,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 1334,
"s": 1300,
"text": "How to Install Scala with VSCode?"
},
{
"code": null,
"e": 1355,
"s": 1334,
"text": "Inheritance in Scala"
},
{
"code": null,
"e": 1376,
"s": 1355,
"text": "Enumeration in Scala"
}
] |
Progressbar widget in Tkinter | Python
|
01 May, 2019
The purpose of this widget is to reassure the user that something is happening. It can operate in one of two modes –In determinate mode, the widget shows an indicator that moves from beginning to end under program control.In indeterminate mode, the widget is animated so the user will believe that something is in progress. In this mode, the indicator bounces back and forth between the ends of the widget.
Syntax:
widget_object = Progressbar(parent, **options)
Code #1 In determinate mode
# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Progress bar widgetprogress = Progressbar(root, orient = HORIZONTAL, length = 100, mode = 'determinate') # Function responsible for the updation# of the progress bar valuedef bar(): import time progress['value'] = 20 root.update_idletasks() time.sleep(1) progress['value'] = 40 root.update_idletasks() time.sleep(1) progress['value'] = 50 root.update_idletasks() time.sleep(1) progress['value'] = 60 root.update_idletasks() time.sleep(1) progress['value'] = 80 root.update_idletasks() time.sleep(1) progress['value'] = 100 progress.pack(pady = 10) # This button will initialize# the progress barButton(root, text = 'Start', command = bar).pack(pady = 10) # infinite loopmainloop()
Output:
# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Progress bar widgetprogress = Progressbar(root, orient = HORIZONTAL, length = 100, mode = 'indeterminate') # Function responsible for the updation# of the progress bar valuedef bar(): import time progress['value'] = 20 root.update_idletasks() time.sleep(0.5) progress['value'] = 40 root.update_idletasks() time.sleep(0.5) progress['value'] = 50 root.update_idletasks() time.sleep(0.5) progress['value'] = 60 root.update_idletasks() time.sleep(0.5) progress['value'] = 80 root.update_idletasks() time.sleep(0.5) progress['value'] = 100 root.update_idletasks() time.sleep(0.5) progress['value'] = 80 root.update_idletasks() time.sleep(0.5) progress['value'] = 60 root.update_idletasks() time.sleep(0.5) progress['value'] = 50 root.update_idletasks() time.sleep(0.5) progress['value'] = 40 root.update_idletasks() time.sleep(0.5) progress['value'] = 20 root.update_idletasks() time.sleep(0.5) progress['value'] = 0 progress.pack(pady = 10) # This button will initialize# the progress barButton(root, text = 'Start', command = bar).pack(pady = 10) # infinite loopmainloop()
Output:
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 May, 2019"
},
{
"code": null,
"e": 460,
"s": 53,
"text": "The purpose of this widget is to reassure the user that something is happening. It can operate in one of two modes –In determinate mode, the widget shows an indicator that moves from beginning to end under program control.In indeterminate mode, the widget is animated so the user will believe that something is in progress. In this mode, the indicator bounces back and forth between the ends of the widget."
},
{
"code": null,
"e": 468,
"s": 460,
"text": "Syntax:"
},
{
"code": null,
"e": 516,
"s": 468,
"text": "widget_object = Progressbar(parent, **options)\n"
},
{
"code": null,
"e": 545,
"s": 516,
"text": " Code #1 In determinate mode"
},
{
"code": "# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Progress bar widgetprogress = Progressbar(root, orient = HORIZONTAL, length = 100, mode = 'determinate') # Function responsible for the updation# of the progress bar valuedef bar(): import time progress['value'] = 20 root.update_idletasks() time.sleep(1) progress['value'] = 40 root.update_idletasks() time.sleep(1) progress['value'] = 50 root.update_idletasks() time.sleep(1) progress['value'] = 60 root.update_idletasks() time.sleep(1) progress['value'] = 80 root.update_idletasks() time.sleep(1) progress['value'] = 100 progress.pack(pady = 10) # This button will initialize# the progress barButton(root, text = 'Start', command = bar).pack(pady = 10) # infinite loopmainloop()",
"e": 1417,
"s": 545,
"text": null
},
{
"code": null,
"e": 1425,
"s": 1417,
"text": "Output:"
},
{
"code": "# importing tkinter modulefrom tkinter import * from tkinter.ttk import * # creating tkinter windowroot = Tk() # Progress bar widgetprogress = Progressbar(root, orient = HORIZONTAL, length = 100, mode = 'indeterminate') # Function responsible for the updation# of the progress bar valuedef bar(): import time progress['value'] = 20 root.update_idletasks() time.sleep(0.5) progress['value'] = 40 root.update_idletasks() time.sleep(0.5) progress['value'] = 50 root.update_idletasks() time.sleep(0.5) progress['value'] = 60 root.update_idletasks() time.sleep(0.5) progress['value'] = 80 root.update_idletasks() time.sleep(0.5) progress['value'] = 100 root.update_idletasks() time.sleep(0.5) progress['value'] = 80 root.update_idletasks() time.sleep(0.5) progress['value'] = 60 root.update_idletasks() time.sleep(0.5) progress['value'] = 50 root.update_idletasks() time.sleep(0.5) progress['value'] = 40 root.update_idletasks() time.sleep(0.5) progress['value'] = 20 root.update_idletasks() time.sleep(0.5) progress['value'] = 0 progress.pack(pady = 10) # This button will initialize# the progress barButton(root, text = 'Start', command = bar).pack(pady = 10) # infinite loopmainloop()",
"e": 2756,
"s": 1425,
"text": null
},
{
"code": null,
"e": 2764,
"s": 2756,
"text": "Output:"
},
{
"code": null,
"e": 2775,
"s": 2764,
"text": "Python-gui"
},
{
"code": null,
"e": 2790,
"s": 2775,
"text": "Python-tkinter"
},
{
"code": null,
"e": 2797,
"s": 2790,
"text": "Python"
}
] |
File list() method in Java with Examples
|
30 Jan, 2019
The list() method is a part of File class.The function returns an array of string denoting the files in a given abstract pathname if the path name is a directory else returns null. The function is an overloaded function. One of the function does not have any parameter and the other function takes FilenameFilter object as parameter
Function Signature:
public String[] list()
public String[] list(FilenameFilter f)
Function Syntax:
file.list()
file.list(filter)
Parameters: The function is an overloaded function. One of the function does not have any parameter and the other function takes FilenameFilter object as a parameter
Return value: The function returns a string array, or null value if the file object is file.
Exception: This method throws Security Exception if the function is not allowed write access to the file.
Below programs will illustrate the use of the list() function
Example 1: We will try to find all the files and directories in a given directory
// Java program to demonstrate the// use of list() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File("f:\\program"); // Get all the names of the files present // in the given directory String[] files = f.list(); System.out.println("Files are:"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i]); } } catch (Exception e) { System.err.println(e.getMessage()); } }}
Output:
Files are:
1232.txt
1245.txt
5671.txt
program1
Example 2: We will try to find all the files and directories in a given directory whose names start with “12”
// Java program to demonstrate the// use of list() function import java.io.*; public class solution { public static void main(String atry-catch { // try catch block to handle exceptions try { // Create a file object File f = new File("f:\\program"); // Create a FilenameFilter FilenameFilter filter = new FilenameFilter() { public boolean accept(File f, String name) { return name.startsWith("12"); } }; // Get all the names of the files present // in the given directory // and whose names start with "12" String[] files = f.list(filter); System.out.println("Files are:"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i]); } } catch (Exception e) { System.err.println(e.getMessage()); } }
Output:
Files are:
1232.txt
1245.txt
The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file
Java-File Class
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Queue Interface In Java
Multidimensional Arrays in Java
HashMap in Java with Examples
Math pow() method in Java with Example
PriorityQueue in Java
Stack Class in Java
List Interface in Java with Examples
Initialize an ArrayList in Java
ArrayList in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jan, 2019"
},
{
"code": null,
"e": 385,
"s": 52,
"text": "The list() method is a part of File class.The function returns an array of string denoting the files in a given abstract pathname if the path name is a directory else returns null. The function is an overloaded function. One of the function does not have any parameter and the other function takes FilenameFilter object as parameter"
},
{
"code": null,
"e": 405,
"s": 385,
"text": "Function Signature:"
},
{
"code": null,
"e": 467,
"s": 405,
"text": "public String[] list()\npublic String[] list(FilenameFilter f)"
},
{
"code": null,
"e": 484,
"s": 467,
"text": "Function Syntax:"
},
{
"code": null,
"e": 514,
"s": 484,
"text": "file.list()\nfile.list(filter)"
},
{
"code": null,
"e": 680,
"s": 514,
"text": "Parameters: The function is an overloaded function. One of the function does not have any parameter and the other function takes FilenameFilter object as a parameter"
},
{
"code": null,
"e": 773,
"s": 680,
"text": "Return value: The function returns a string array, or null value if the file object is file."
},
{
"code": null,
"e": 879,
"s": 773,
"text": "Exception: This method throws Security Exception if the function is not allowed write access to the file."
},
{
"code": null,
"e": 941,
"s": 879,
"text": "Below programs will illustrate the use of the list() function"
},
{
"code": null,
"e": 1023,
"s": 941,
"text": "Example 1: We will try to find all the files and directories in a given directory"
},
{
"code": "// Java program to demonstrate the// use of list() function import java.io.*; public class solution { public static void main(String args[]) { // try-catch block to handle exceptions try { // Create a file object File f = new File(\"f:\\\\program\"); // Get all the names of the files present // in the given directory String[] files = f.list(); System.out.println(\"Files are:\"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i]); } } catch (Exception e) { System.err.println(e.getMessage()); } }}",
"e": 1752,
"s": 1023,
"text": null
},
{
"code": null,
"e": 1760,
"s": 1752,
"text": "Output:"
},
{
"code": null,
"e": 1808,
"s": 1760,
"text": "Files are:\n1232.txt\n1245.txt\n5671.txt\nprogram1\n"
},
{
"code": null,
"e": 1918,
"s": 1808,
"text": "Example 2: We will try to find all the files and directories in a given directory whose names start with “12”"
},
{
"code": "// Java program to demonstrate the// use of list() function import java.io.*; public class solution { public static void main(String atry-catch { // try catch block to handle exceptions try { // Create a file object File f = new File(\"f:\\\\program\"); // Create a FilenameFilter FilenameFilter filter = new FilenameFilter() { public boolean accept(File f, String name) { return name.startsWith(\"12\"); } }; // Get all the names of the files present // in the given directory // and whose names start with \"12\" String[] files = f.list(filter); System.out.println(\"Files are:\"); // Display the names of the files for (int i = 0; i < files.length; i++) { System.out.println(files[i]); } } catch (Exception e) { System.err.println(e.getMessage()); } }",
"e": 2954,
"s": 1918,
"text": null
},
{
"code": null,
"e": 2962,
"s": 2954,
"text": "Output:"
},
{
"code": null,
"e": 2992,
"s": 2962,
"text": "Files are:\n1232.txt\n1245.txt\n"
},
{
"code": null,
"e": 3099,
"s": 2992,
"text": "The programs might not run in an online IDE. please use an offline IDE and set the Parent file of the file"
},
{
"code": null,
"e": 3115,
"s": 3099,
"text": "Java-File Class"
},
{
"code": null,
"e": 3130,
"s": 3115,
"text": "Java-Functions"
},
{
"code": null,
"e": 3146,
"s": 3130,
"text": "Java-IO package"
},
{
"code": null,
"e": 3151,
"s": 3146,
"text": "Java"
},
{
"code": null,
"e": 3156,
"s": 3151,
"text": "Java"
},
{
"code": null,
"e": 3254,
"s": 3156,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3273,
"s": 3254,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3297,
"s": 3273,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 3329,
"s": 3297,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3359,
"s": 3329,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3398,
"s": 3359,
"text": "Math pow() method in Java with Example"
},
{
"code": null,
"e": 3420,
"s": 3398,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 3440,
"s": 3420,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3477,
"s": 3440,
"text": "List Interface in Java with Examples"
},
{
"code": null,
"e": 3509,
"s": 3477,
"text": "Initialize an ArrayList in Java"
}
] |
Java | Class and Object | Question 4
|
28 Jun, 2021
Predict the output of following Java program.
class demoClass{ int a = 1; void func() { demo obj = new demo(); obj.display(); } class demo { int b = 2; void display() { System.out.println("\na = " + a); } } void get() { System.out.println("\nb = " + b); }} class Test{ public static void main(String[] args) { demoClass obj = new demoClass(); obj.func(); obj.get(); }}
(A)
a = 1
b = 2
(B) Compilation error
(C)
b = 2
a = 1
Answer: (B)Explanation:Members of inner class ‘demo’ can not be used in the outer class ‘Test’. Thus, get() of outer class can not access variable ‘b’ of inner class.Quiz of this Question
Class and Object
Java-Class and Object
Java Quiz
Java-Class and Object
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java | Functions | Question 1
Java | Exception Handling | Question 3
Java | Exception Handling | Question 8
Java | Exception Handling | Question 4
Java | Abstract Class and Interface | Question 2
Java | Exception Handling | Question 7
Java | Exception Handling | Question 6
Java | Exception Handling | Question 8
Java | Java Packages | Question 3
Java | Operators | Question 9
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 100,
"s": 54,
"text": "Predict the output of following Java program."
},
{
"code": "class demoClass{ int a = 1; void func() { demo obj = new demo(); obj.display(); } class demo { int b = 2; void display() { System.out.println(\"\\na = \" + a); } } void get() { System.out.println(\"\\nb = \" + b); }} class Test{ public static void main(String[] args) { demoClass obj = new demoClass(); obj.func(); obj.get(); }}",
"e": 558,
"s": 100,
"text": null
},
{
"code": null,
"e": 562,
"s": 558,
"text": "(A)"
},
{
"code": null,
"e": 574,
"s": 562,
"text": "a = 1\nb = 2"
},
{
"code": null,
"e": 596,
"s": 574,
"text": "(B) Compilation error"
},
{
"code": null,
"e": 600,
"s": 596,
"text": "(C)"
},
{
"code": null,
"e": 612,
"s": 600,
"text": "b = 2\na = 1"
},
{
"code": null,
"e": 800,
"s": 612,
"text": "Answer: (B)Explanation:Members of inner class ‘demo’ can not be used in the outer class ‘Test’. Thus, get() of outer class can not access variable ‘b’ of inner class.Quiz of this Question"
},
{
"code": null,
"e": 817,
"s": 800,
"text": "Class and Object"
},
{
"code": null,
"e": 839,
"s": 817,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 849,
"s": 839,
"text": "Java Quiz"
},
{
"code": null,
"e": 871,
"s": 849,
"text": "Java-Class and Object"
},
{
"code": null,
"e": 969,
"s": 871,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 999,
"s": 969,
"text": "Java | Functions | Question 1"
},
{
"code": null,
"e": 1038,
"s": 999,
"text": "Java | Exception Handling | Question 3"
},
{
"code": null,
"e": 1077,
"s": 1038,
"text": "Java | Exception Handling | Question 8"
},
{
"code": null,
"e": 1116,
"s": 1077,
"text": "Java | Exception Handling | Question 4"
},
{
"code": null,
"e": 1165,
"s": 1116,
"text": "Java | Abstract Class and Interface | Question 2"
},
{
"code": null,
"e": 1204,
"s": 1165,
"text": "Java | Exception Handling | Question 7"
},
{
"code": null,
"e": 1243,
"s": 1204,
"text": "Java | Exception Handling | Question 6"
},
{
"code": null,
"e": 1282,
"s": 1243,
"text": "Java | Exception Handling | Question 8"
},
{
"code": null,
"e": 1316,
"s": 1282,
"text": "Java | Java Packages | Question 3"
}
] |
Querying maximum number of divisors that a number in a given range has
|
06 Apr, 2021
Given Q queries, of type: L R, for each query you must print the maximum number of divisors that a number x (L <= x <= R) has. Examples:
L = 1 R = 10:
1 has 1 divisor.
2 has 2 divisors.
3 has 2 divisors.
4 has 3 divisors.
5 has 2 divisors.
6 has 4 divisors.
7 has 2 divisors.
8 has 4 divisors.
9 has 3 divisors.
10 has 4 divisors.
So the answer for above query is 4, as it is the maximum number of
divisors a number has in [1, 10].
Pre-requisites : Eratosthenes Sieve, Segment TreeBelow are steps to solve the problem.
Firstly, let’s see how many number of divisors does a number n = p1k1 * p2k2 * ... * pnkn (where p1, p2, ..., pn are prime numbers) has; the answer is (k1 + 1)*(k2 + 1)*...*(kn + 1). How? For each prime number in the prime factorization, we can have its ki + 1 possible powers in a divisor (0, 1, 2,..., ki).Now let’s see how can we find the prime factorization of a number, we firstly build an array, smallest_prime[], which stores the smallest prime divisor of i at ith index, we divide a number by its smallest prime divisor to obtain a new number (we also have the smallest prime divisor of this new number stored), we keep doing it until the smallest prime of the number changes, when the smallest prime factor of the new number is different from the previous number’s, we have ki for the ith prime number in the prime factorization of the given number.Finally, we obtain the number of divisors for all the numbers and store these in a segment tree that maintains the maximum numbers in the segments. We respond to each query by querying the segment tree.
Firstly, let’s see how many number of divisors does a number n = p1k1 * p2k2 * ... * pnkn (where p1, p2, ..., pn are prime numbers) has; the answer is (k1 + 1)*(k2 + 1)*...*(kn + 1). How? For each prime number in the prime factorization, we can have its ki + 1 possible powers in a divisor (0, 1, 2,..., ki).
Now let’s see how can we find the prime factorization of a number, we firstly build an array, smallest_prime[], which stores the smallest prime divisor of i at ith index, we divide a number by its smallest prime divisor to obtain a new number (we also have the smallest prime divisor of this new number stored), we keep doing it until the smallest prime of the number changes, when the smallest prime factor of the new number is different from the previous number’s, we have ki for the ith prime number in the prime factorization of the given number.
Finally, we obtain the number of divisors for all the numbers and store these in a segment tree that maintains the maximum numbers in the segments. We respond to each query by querying the segment tree.
C++
Java
Python 3
C#
Javascript
// A C++ implementation of the above idea to process// queries of finding a number with maximum divisors.#include <bits/stdc++.h>using namespace std; #define maxn 1000005#define INF 99999999 int smallest_prime[maxn];int divisors[maxn];int segmentTree[4 * maxn]; // Finds smallest prime factor of all numbers in// range[1, maxn) and stores them in smallest_prime[],// smallest_prime[i] should contain the smallest prime// that divides ivoid findSmallestPrimeFactors(){ // Initialize the smallest_prime factors of all // to infinity for (int i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (long long i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its smallest_prime // equal to itself smallest_prime[i] = i; for (long long j = i * i; j < maxn; j += i) // if 'i' is the first prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } }} // number of divisors of n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn)// are equal to (k1+1) * (k2+1) ... (kn+1)// this function finds the number of divisors of all numbers// in range [1, maxn) and stores it in divisors[]// divisors[i] stores the number of divisors i hasvoid buildDivisorsArray(){ for (int i = 1; i < maxn; i++) { divisors[i] = 1; int n = i, p = smallest_prime[i], k = 0; // we can obtain the prime factorization of the number n // n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) using the // smallest_prime[] array, we keep dividing n by its // smallest_prime until it becomes 1, whilst we check // if we have need to set k zero while (n > 1) { n = n / p; k ++; if (smallest_prime[n] != p) { //use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } }} // builds segment tree for divisors[] arrayvoid buildSegtmentTree(int node, int a, int b){ // leaf node if (a == b) { segmentTree[node] = divisors[a]; return ; } //build left and right subtree buildSegtmentTree(2 * node, a, (a + b) / 2); buildSegtmentTree(2 * node + 1, ((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = max(segmentTree[2 * node], segmentTree[2 *node + 1]);} //returns the maximum number of divisors in [l, r]int query(int node, int a, int b, int l, int r){ // If current node's range is disjoint with query range if (l > b || a > r) return -1; // If the current node stores information for the range // that is completely inside the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return max(query(2 * node, a, (a + b) / 2, l, r), query(2 * node + 1, ((a + b) / 2) + 1, b,l,r));} // driver codeint main(){ // First find smallest prime divisors for all // the numbers findSmallestPrimeFactors(); // Then build the divisors[] array to store // the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); cout << "Maximum divisors that a number has " << " in [1, 100] are " << query(1, 1, maxn - 1, 1, 100) << endl; cout << "Maximum divisors that a number has" << " in [10, 48] are " << query(1, 1, maxn - 1, 10, 48) << endl; cout << "Maximum divisors that a number has" << " in [1, 10] are " << query(1, 1, maxn - 1, 1, 10) << endl; return 0;}
// Java implementation of the above idea to process// queries of finding a number with maximum divisors.import java.util.*; class GFG{static int maxn = 10005;static int INF = 999999; static int []smallest_prime = new int[maxn];static int []divisors = new int[maxn];static int []segmentTree = new int[4 * maxn]; // Finds smallest prime factor of all numbers// in range[1, maxn) and stores them in// smallest_prime[], smallest_prime[i] should// contain the smallest prime that divides istatic void findSmallestPrimeFactors(){ // Initialize the smallest_prime factors // of all to infinity for (int i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (int i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its // smallest_prime equal to itself smallest_prime[i] = i; for (int j = i * i; j < maxn; j += i) // if 'i' is the first // prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } }} // number of divisors of n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn)// are equal to (k1+1) * (k2+1) ... (kn+1)// this function finds the number of divisors of all numbers// in range [1, maxn) and stores it in divisors[]// divisors[i] stores the number of divisors i hasstatic void buildDivisorsArray(){ for (int i = 1; i < maxn; i++) { divisors[i] = 1; int n = i, p = smallest_prime[i], k = 0; // we can obtain the prime factorization of // the number n, n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // using the smallest_prime[] array, we keep dividing n // by its smallest_prime until it becomes 1, // whilst we check if we have need to set k zero while (n > 1) { n = n / p; k ++; if (smallest_prime[n] != p) { // use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } }} // builds segment tree for divisors[] arraystatic void buildSegtmentTree(int node, int a, int b){ // leaf node if (a == b) { segmentTree[node] = divisors[a]; return ; } //build left and right subtree buildSegtmentTree(2 * node, a, (a + b) / 2); buildSegtmentTree(2 * node + 1, ((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = Math.max(segmentTree[2 * node], segmentTree[2 *node + 1]);} // returns the maximum number of divisors in [l, r]static int query(int node, int a, int b, int l, int r){ // If current node's range is disjoint // with query range if (l > b || a > r) return -1; // If the current node stores information // for the range that is completely inside // the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return Math.max(query(2 * node, a, (a + b) / 2, l, r), query(2 * node + 1, ((a + b) / 2) + 1, b, l, r));} // Driver Codepublic static void main(String[] args){ // First find smallest prime divisors // for all the numbers findSmallestPrimeFactors(); // Then build the divisors[] array to store // the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); System.out.println("Maximum divisors that a number " + "has in [1, 100] are " + query(1, 1, maxn - 1, 1, 100)); System.out.println("Maximum divisors that a number " + "has in [10, 48] are " + query(1, 1, maxn - 1, 10, 48)); System.out.println("Maximum divisors that a number " + "has in [1, 10] are " + query(1, 1, maxn - 1, 1, 10)); }} // This code is contributed by PrinciRaj1992
# Python 3 implementation of the above# idea to process queries of finding a# number with maximum divisors.maxn = 1000005INF = 99999999 smallest_prime = [0] * maxndivisors = [0] * maxnsegmentTree = [0] * (4 * maxn) # Finds smallest prime factor of all# numbers in range[1, maxn) and stores# them in smallest_prime[], smallest_prime[i]# should contain the smallest prime that divides idef findSmallestPrimeFactors(): # Initialize the smallest_prime # factors of all to infinity for i in range(maxn ): smallest_prime[i] = INF # to be built like eratosthenes sieve for i in range(2, maxn): if (smallest_prime[i] == INF): # prime number will have its # smallest_prime equal to itself smallest_prime[i] = i for j in range(i * i, maxn , i): # if 'i' is the first prime # number reaching 'j' if (smallest_prime[j] > i): smallest_prime[j] = i # number of divisors of n = (p1 ^ k1) *# (p2 ^ k2) ... (pn ^ kn) are equal to# (k1+1) * (k2+1) ... (kn+1). This function# finds the number of divisors of all numbers# in range [1, maxn) and stores it in divisors[]# divisors[i] stores the number of divisors i hasdef buildDivisorsArray(): for i in range(1, maxn): divisors[i] = 1 n = i p = smallest_prime[i] k = 0 # we can obtain the prime factorization # of the number n n = (p1 ^ k1) * (p2 ^ k2) # ... (pn ^ kn) using the smallest_prime[] # array, we keep dividing n by its # smallest_prime until it becomes 1, whilst # we check if we have need to set k zero while (n > 1): n = n // p k += 1 if (smallest_prime[n] != p): # use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1) k = 0 p = smallest_prime[n] # builds segment tree for divisors[] arraydef buildSegtmentTree( node, a, b): # leaf node if (a == b): segmentTree[node] = divisors[a] return #build left and right subtree buildSegtmentTree(2 * node, a, (a + b) // 2) buildSegtmentTree(2 * node + 1, ((a + b) // 2) + 1, b) #combine the information from left #and right subtree at current node segmentTree[node] = max(segmentTree[2 * node], segmentTree[2 * node + 1]) # returns the maximum number of# divisors in [l, r]def query(node, a, b, l, r): # If current node's range is disjoint # with query range if (l > b or a > r): return -1 # If the current node stores information # for the range that is completely inside # the query range if (a >= l and b <= r): return segmentTree[node] # Returns maximum number of divisors # from left or right subtree return max(query(2 * node, a, (a + b) // 2, l, r), query(2 * node + 1, ((a + b) // 2) + 1, b, l, r)) # Driver codeif __name__ == "__main__": # First find smallest prime divisors # for all the numbers findSmallestPrimeFactors() # Then build the divisors[] array to # store the number of divisors buildDivisorsArray() # Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1) print("Maximum divisors that a number has ", " in [1, 100] are ", query(1, 1, maxn - 1, 1, 100)) print("Maximum divisors that a number has", " in [10, 48] are ", query(1, 1, maxn - 1, 10, 48)) print( "Maximum divisors that a number has", " in [1, 10] are ", query(1, 1, maxn - 1, 1, 10)) # This code is contributed by ita_c
// C# implementation of the above idea// to process queries of finding a number// with maximum divisors.using System; class GFG{static int maxn = 10005;static int INF = 999999; static int []smallest_prime = new int[maxn];static int []divisors = new int[maxn];static int []segmentTree = new int[4 * maxn]; // Finds smallest prime factor of all numbers// in range[1, maxn) and stores them in// smallest_prime[], smallest_prime[i] should// contain the smallest prime that divides istatic void findSmallestPrimeFactors(){ // Initialize the smallest_prime // factors of all to infinity for (int i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (int i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its // smallest_prime equal to itself smallest_prime[i] = i; for (int j = i * i; j < maxn; j += i) // if 'i' is the first // prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } }} // number of divisors of// n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn)// are equal to (k1+1) * (k2+1) ... (kn+1)// this function finds the number of divisors// of all numbers in range [1, maxn) and stores// it in divisors[] divisors[i] stores the// number of divisors i hasstatic void buildDivisorsArray(){ for (int i = 1; i < maxn; i++) { divisors[i] = 1; int n = i, p = smallest_prime[i], k = 0; // we can obtain the prime factorization of // the number n, // n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // using the smallest_prime[] array, // we keep dividing n by its smallest_prime // until it becomes 1, whilst we check if // we have need to set k zero while (n > 1) { n = n / p; k ++; if (smallest_prime[n] != p) { // use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } }} // builds segment tree for divisors[] arraystatic void buildSegtmentTree(int node, int a, int b){ // leaf node if (a == b) { segmentTree[node] = divisors[a]; return; } //build left and right subtree buildSegtmentTree(2 * node, a, (a + b) / 2); buildSegtmentTree(2 * node + 1, ((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = Math.Max(segmentTree[2 * node], segmentTree[2 *node + 1]);} // returns the maximum number of divisors in [l, r]static int query(int node, int a, int b, int l, int r){ // If current node's range is disjoint // with query range if (l > b || a > r) return -1; // If the current node stores information // for the range that is completely inside // the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return Math.Max(query(2 * node, a, (a + b) / 2, l, r), query(2 * node + 1, ((a + b) / 2) + 1, b, l, r));} // Driver Codepublic static void Main(String[] args){ // First find smallest prime divisors // for all the numbers findSmallestPrimeFactors(); // Then build the divisors[] array // to store the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); Console.WriteLine("Maximum divisors that a number " + "has in [1, 100] are " + query(1, 1, maxn - 1, 1, 100)); Console.WriteLine("Maximum divisors that a number " + "has in [10, 48] are " + query(1, 1, maxn - 1, 10, 48)); Console.WriteLine("Maximum divisors that a number " + "has in [1, 10] are " + query(1, 1, maxn - 1, 1, 10)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript implementation of the above idea to process// queries of finding a number with maximum divisors. let maxn = 10005; let INF = 999999; let smallest_prime = new Array(maxn); for(let i=0;i<maxn;i++) { smallest_prime[i]=0; } let divisors = new Array(maxn); for(let i=0;i<maxn;i++) { divisors[i]=0; } let segmentTree = new Array(4 * maxn); for(let i=0;i<4*maxn;i++) { segmentTree[i]=0; } // Finds smallest prime factor of all numbers // in range[1, maxn) and stores them in // smallest_prime[], smallest_prime[i] should // contain the smallest prime that divides i function findSmallestPrimeFactors() { // Initialize the smallest_prime factors // of all to infinity for (let i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (let i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its // smallest_prime equal to itself smallest_prime[i] = i; for (let j = i * i; j < maxn; j += i) { // if 'i' is the first // prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } } } } // number of divisors of n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // are equal to (k1+1) * (k2+1) ... (kn+1) // this function finds the number of divisors of all numbers // in range [1, maxn) and stores it in divisors[] // divisors[i] stores the number of divisors i has function buildDivisorsArray() { for (let i = 1; i < maxn; i++) { divisors[i] = 1; let n = i; let p = smallest_prime[i] let k = 0; // we can obtain the prime factorization of // the number n, n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // using the smallest_prime[] array, we keep dividing n // by its smallest_prime until it becomes 1, // whilst we check if we have need to set k zero while (n > 1) { n = Math.floor(n / p); k++; if (smallest_prime[n] != p) { // use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } } } // builds segment tree for divisors[] array function buildSegtmentTree(node,a,b) { // leaf node if (a == b) { segmentTree[node] = divisors[a]; return ; } //build left and right subtree buildSegtmentTree(2 * node, a, Math.floor((a + b) / 2)); buildSegtmentTree((2 * node) + 1, Math.floor((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = Math.max(segmentTree[2 * node], segmentTree[(2 *node) + 1]); } // returns the maximum number of divisors in [l, r] function query(node,a,b,l,r) { // If current node's range is disjoint // with query range if (l > b || a > r) return -1; // If the current node stores information // for the range that is completely inside // the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return Math.max(query(2 * node, a, Math.floor((a + b) / 2), l, r), query(2 * node + 1, Math.floor((a + b) / 2) + 1, b, l, r)); } // Driver Code // First find smallest prime divisors // for all the numbers findSmallestPrimeFactors(); // Then build the divisors[] array to store // the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); document.write("Maximum divisors that a number " + "has in [1, 100] are " + query(1, 1, maxn - 1, 1, 100)+"<br>"); document.write("Maximum divisors that a number " + "has in [10, 48] are " + query(1, 1, maxn - 1, 10, 48)+"<br>"); document.write("Maximum divisors that a number " + "has in [1, 10] are " + query(1, 1, maxn - 1, 1, 10)+"<br>"); // This code is contributed by avanitrachhadiya2155 </script>
Output:
Maximum divisors that a number has in [1, 100] are 12
Maximum divisors that a number has in [10, 48] are 10
Maximum divisors that a number has in [1, 10] are 4
Time Complexity:
For sieve: O(maxn * log(log(maxn)) )
For calculating divisors of each number: O(k1 + k2 + ... + kn) < O(log(maxn))
For querying each range: O(log(maxn))
Total: O((maxn + Q) * log(maxn))
This article is contributed by Saumye Malhotra. 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.
ukasp
princiraj1992
29AjayKumar
avanitrachhadiya2155
divisors
Segment-Tree
sieve
Mathematical
Mathematical
sieve
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Apr, 2021"
},
{
"code": null,
"e": 191,
"s": 52,
"text": "Given Q queries, of type: L R, for each query you must print the maximum number of divisors that a number x (L <= x <= R) has. Examples: "
},
{
"code": null,
"e": 528,
"s": 191,
"text": "L = 1 R = 10:\n 1 has 1 divisor.\n 2 has 2 divisors.\n 3 has 2 divisors.\n 4 has 3 divisors.\n 5 has 2 divisors.\n 6 has 4 divisors.\n 7 has 2 divisors.\n 8 has 4 divisors.\n 9 has 3 divisors.\n 10 has 4 divisors.\n\nSo the answer for above query is 4, as it is the maximum number of \ndivisors a number has in [1, 10]."
},
{
"code": null,
"e": 618,
"s": 530,
"text": "Pre-requisites : Eratosthenes Sieve, Segment TreeBelow are steps to solve the problem. "
},
{
"code": null,
"e": 1679,
"s": 618,
"text": "Firstly, let’s see how many number of divisors does a number n = p1k1 * p2k2 * ... * pnkn (where p1, p2, ..., pn are prime numbers) has; the answer is (k1 + 1)*(k2 + 1)*...*(kn + 1). How? For each prime number in the prime factorization, we can have its ki + 1 possible powers in a divisor (0, 1, 2,..., ki).Now let’s see how can we find the prime factorization of a number, we firstly build an array, smallest_prime[], which stores the smallest prime divisor of i at ith index, we divide a number by its smallest prime divisor to obtain a new number (we also have the smallest prime divisor of this new number stored), we keep doing it until the smallest prime of the number changes, when the smallest prime factor of the new number is different from the previous number’s, we have ki for the ith prime number in the prime factorization of the given number.Finally, we obtain the number of divisors for all the numbers and store these in a segment tree that maintains the maximum numbers in the segments. We respond to each query by querying the segment tree."
},
{
"code": null,
"e": 1988,
"s": 1679,
"text": "Firstly, let’s see how many number of divisors does a number n = p1k1 * p2k2 * ... * pnkn (where p1, p2, ..., pn are prime numbers) has; the answer is (k1 + 1)*(k2 + 1)*...*(kn + 1). How? For each prime number in the prime factorization, we can have its ki + 1 possible powers in a divisor (0, 1, 2,..., ki)."
},
{
"code": null,
"e": 2539,
"s": 1988,
"text": "Now let’s see how can we find the prime factorization of a number, we firstly build an array, smallest_prime[], which stores the smallest prime divisor of i at ith index, we divide a number by its smallest prime divisor to obtain a new number (we also have the smallest prime divisor of this new number stored), we keep doing it until the smallest prime of the number changes, when the smallest prime factor of the new number is different from the previous number’s, we have ki for the ith prime number in the prime factorization of the given number."
},
{
"code": null,
"e": 2742,
"s": 2539,
"text": "Finally, we obtain the number of divisors for all the numbers and store these in a segment tree that maintains the maximum numbers in the segments. We respond to each query by querying the segment tree."
},
{
"code": null,
"e": 2748,
"s": 2744,
"text": "C++"
},
{
"code": null,
"e": 2753,
"s": 2748,
"text": "Java"
},
{
"code": null,
"e": 2762,
"s": 2753,
"text": "Python 3"
},
{
"code": null,
"e": 2765,
"s": 2762,
"text": "C#"
},
{
"code": null,
"e": 2776,
"s": 2765,
"text": "Javascript"
},
{
"code": "// A C++ implementation of the above idea to process// queries of finding a number with maximum divisors.#include <bits/stdc++.h>using namespace std; #define maxn 1000005#define INF 99999999 int smallest_prime[maxn];int divisors[maxn];int segmentTree[4 * maxn]; // Finds smallest prime factor of all numbers in// range[1, maxn) and stores them in smallest_prime[],// smallest_prime[i] should contain the smallest prime// that divides ivoid findSmallestPrimeFactors(){ // Initialize the smallest_prime factors of all // to infinity for (int i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (long long i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its smallest_prime // equal to itself smallest_prime[i] = i; for (long long j = i * i; j < maxn; j += i) // if 'i' is the first prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } }} // number of divisors of n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn)// are equal to (k1+1) * (k2+1) ... (kn+1)// this function finds the number of divisors of all numbers// in range [1, maxn) and stores it in divisors[]// divisors[i] stores the number of divisors i hasvoid buildDivisorsArray(){ for (int i = 1; i < maxn; i++) { divisors[i] = 1; int n = i, p = smallest_prime[i], k = 0; // we can obtain the prime factorization of the number n // n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) using the // smallest_prime[] array, we keep dividing n by its // smallest_prime until it becomes 1, whilst we check // if we have need to set k zero while (n > 1) { n = n / p; k ++; if (smallest_prime[n] != p) { //use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } }} // builds segment tree for divisors[] arrayvoid buildSegtmentTree(int node, int a, int b){ // leaf node if (a == b) { segmentTree[node] = divisors[a]; return ; } //build left and right subtree buildSegtmentTree(2 * node, a, (a + b) / 2); buildSegtmentTree(2 * node + 1, ((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = max(segmentTree[2 * node], segmentTree[2 *node + 1]);} //returns the maximum number of divisors in [l, r]int query(int node, int a, int b, int l, int r){ // If current node's range is disjoint with query range if (l > b || a > r) return -1; // If the current node stores information for the range // that is completely inside the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return max(query(2 * node, a, (a + b) / 2, l, r), query(2 * node + 1, ((a + b) / 2) + 1, b,l,r));} // driver codeint main(){ // First find smallest prime divisors for all // the numbers findSmallestPrimeFactors(); // Then build the divisors[] array to store // the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); cout << \"Maximum divisors that a number has \" << \" in [1, 100] are \" << query(1, 1, maxn - 1, 1, 100) << endl; cout << \"Maximum divisors that a number has\" << \" in [10, 48] are \" << query(1, 1, maxn - 1, 10, 48) << endl; cout << \"Maximum divisors that a number has\" << \" in [1, 10] are \" << query(1, 1, maxn - 1, 1, 10) << endl; return 0;}",
"e": 6638,
"s": 2776,
"text": null
},
{
"code": "// Java implementation of the above idea to process// queries of finding a number with maximum divisors.import java.util.*; class GFG{static int maxn = 10005;static int INF = 999999; static int []smallest_prime = new int[maxn];static int []divisors = new int[maxn];static int []segmentTree = new int[4 * maxn]; // Finds smallest prime factor of all numbers// in range[1, maxn) and stores them in// smallest_prime[], smallest_prime[i] should// contain the smallest prime that divides istatic void findSmallestPrimeFactors(){ // Initialize the smallest_prime factors // of all to infinity for (int i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (int i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its // smallest_prime equal to itself smallest_prime[i] = i; for (int j = i * i; j < maxn; j += i) // if 'i' is the first // prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } }} // number of divisors of n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn)// are equal to (k1+1) * (k2+1) ... (kn+1)// this function finds the number of divisors of all numbers// in range [1, maxn) and stores it in divisors[]// divisors[i] stores the number of divisors i hasstatic void buildDivisorsArray(){ for (int i = 1; i < maxn; i++) { divisors[i] = 1; int n = i, p = smallest_prime[i], k = 0; // we can obtain the prime factorization of // the number n, n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // using the smallest_prime[] array, we keep dividing n // by its smallest_prime until it becomes 1, // whilst we check if we have need to set k zero while (n > 1) { n = n / p; k ++; if (smallest_prime[n] != p) { // use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } }} // builds segment tree for divisors[] arraystatic void buildSegtmentTree(int node, int a, int b){ // leaf node if (a == b) { segmentTree[node] = divisors[a]; return ; } //build left and right subtree buildSegtmentTree(2 * node, a, (a + b) / 2); buildSegtmentTree(2 * node + 1, ((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = Math.max(segmentTree[2 * node], segmentTree[2 *node + 1]);} // returns the maximum number of divisors in [l, r]static int query(int node, int a, int b, int l, int r){ // If current node's range is disjoint // with query range if (l > b || a > r) return -1; // If the current node stores information // for the range that is completely inside // the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return Math.max(query(2 * node, a, (a + b) / 2, l, r), query(2 * node + 1, ((a + b) / 2) + 1, b, l, r));} // Driver Codepublic static void main(String[] args){ // First find smallest prime divisors // for all the numbers findSmallestPrimeFactors(); // Then build the divisors[] array to store // the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); System.out.println(\"Maximum divisors that a number \" + \"has in [1, 100] are \" + query(1, 1, maxn - 1, 1, 100)); System.out.println(\"Maximum divisors that a number \" + \"has in [10, 48] are \" + query(1, 1, maxn - 1, 10, 48)); System.out.println(\"Maximum divisors that a number \" + \"has in [1, 10] are \" + query(1, 1, maxn - 1, 1, 10)); }} // This code is contributed by PrinciRaj1992",
"e": 10804,
"s": 6638,
"text": null
},
{
"code": "# Python 3 implementation of the above# idea to process queries of finding a# number with maximum divisors.maxn = 1000005INF = 99999999 smallest_prime = [0] * maxndivisors = [0] * maxnsegmentTree = [0] * (4 * maxn) # Finds smallest prime factor of all# numbers in range[1, maxn) and stores# them in smallest_prime[], smallest_prime[i]# should contain the smallest prime that divides idef findSmallestPrimeFactors(): # Initialize the smallest_prime # factors of all to infinity for i in range(maxn ): smallest_prime[i] = INF # to be built like eratosthenes sieve for i in range(2, maxn): if (smallest_prime[i] == INF): # prime number will have its # smallest_prime equal to itself smallest_prime[i] = i for j in range(i * i, maxn , i): # if 'i' is the first prime # number reaching 'j' if (smallest_prime[j] > i): smallest_prime[j] = i # number of divisors of n = (p1 ^ k1) *# (p2 ^ k2) ... (pn ^ kn) are equal to# (k1+1) * (k2+1) ... (kn+1). This function# finds the number of divisors of all numbers# in range [1, maxn) and stores it in divisors[]# divisors[i] stores the number of divisors i hasdef buildDivisorsArray(): for i in range(1, maxn): divisors[i] = 1 n = i p = smallest_prime[i] k = 0 # we can obtain the prime factorization # of the number n n = (p1 ^ k1) * (p2 ^ k2) # ... (pn ^ kn) using the smallest_prime[] # array, we keep dividing n by its # smallest_prime until it becomes 1, whilst # we check if we have need to set k zero while (n > 1): n = n // p k += 1 if (smallest_prime[n] != p): # use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1) k = 0 p = smallest_prime[n] # builds segment tree for divisors[] arraydef buildSegtmentTree( node, a, b): # leaf node if (a == b): segmentTree[node] = divisors[a] return #build left and right subtree buildSegtmentTree(2 * node, a, (a + b) // 2) buildSegtmentTree(2 * node + 1, ((a + b) // 2) + 1, b) #combine the information from left #and right subtree at current node segmentTree[node] = max(segmentTree[2 * node], segmentTree[2 * node + 1]) # returns the maximum number of# divisors in [l, r]def query(node, a, b, l, r): # If current node's range is disjoint # with query range if (l > b or a > r): return -1 # If the current node stores information # for the range that is completely inside # the query range if (a >= l and b <= r): return segmentTree[node] # Returns maximum number of divisors # from left or right subtree return max(query(2 * node, a, (a + b) // 2, l, r), query(2 * node + 1, ((a + b) // 2) + 1, b, l, r)) # Driver codeif __name__ == \"__main__\": # First find smallest prime divisors # for all the numbers findSmallestPrimeFactors() # Then build the divisors[] array to # store the number of divisors buildDivisorsArray() # Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1) print(\"Maximum divisors that a number has \", \" in [1, 100] are \", query(1, 1, maxn - 1, 1, 100)) print(\"Maximum divisors that a number has\", \" in [10, 48] are \", query(1, 1, maxn - 1, 10, 48)) print( \"Maximum divisors that a number has\", \" in [1, 10] are \", query(1, 1, maxn - 1, 1, 10)) # This code is contributed by ita_c",
"e": 14617,
"s": 10804,
"text": null
},
{
"code": "// C# implementation of the above idea// to process queries of finding a number// with maximum divisors.using System; class GFG{static int maxn = 10005;static int INF = 999999; static int []smallest_prime = new int[maxn];static int []divisors = new int[maxn];static int []segmentTree = new int[4 * maxn]; // Finds smallest prime factor of all numbers// in range[1, maxn) and stores them in// smallest_prime[], smallest_prime[i] should// contain the smallest prime that divides istatic void findSmallestPrimeFactors(){ // Initialize the smallest_prime // factors of all to infinity for (int i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (int i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its // smallest_prime equal to itself smallest_prime[i] = i; for (int j = i * i; j < maxn; j += i) // if 'i' is the first // prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } }} // number of divisors of// n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn)// are equal to (k1+1) * (k2+1) ... (kn+1)// this function finds the number of divisors// of all numbers in range [1, maxn) and stores// it in divisors[] divisors[i] stores the// number of divisors i hasstatic void buildDivisorsArray(){ for (int i = 1; i < maxn; i++) { divisors[i] = 1; int n = i, p = smallest_prime[i], k = 0; // we can obtain the prime factorization of // the number n, // n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // using the smallest_prime[] array, // we keep dividing n by its smallest_prime // until it becomes 1, whilst we check if // we have need to set k zero while (n > 1) { n = n / p; k ++; if (smallest_prime[n] != p) { // use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } }} // builds segment tree for divisors[] arraystatic void buildSegtmentTree(int node, int a, int b){ // leaf node if (a == b) { segmentTree[node] = divisors[a]; return; } //build left and right subtree buildSegtmentTree(2 * node, a, (a + b) / 2); buildSegtmentTree(2 * node + 1, ((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = Math.Max(segmentTree[2 * node], segmentTree[2 *node + 1]);} // returns the maximum number of divisors in [l, r]static int query(int node, int a, int b, int l, int r){ // If current node's range is disjoint // with query range if (l > b || a > r) return -1; // If the current node stores information // for the range that is completely inside // the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return Math.Max(query(2 * node, a, (a + b) / 2, l, r), query(2 * node + 1, ((a + b) / 2) + 1, b, l, r));} // Driver Codepublic static void Main(String[] args){ // First find smallest prime divisors // for all the numbers findSmallestPrimeFactors(); // Then build the divisors[] array // to store the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); Console.WriteLine(\"Maximum divisors that a number \" + \"has in [1, 100] are \" + query(1, 1, maxn - 1, 1, 100)); Console.WriteLine(\"Maximum divisors that a number \" + \"has in [10, 48] are \" + query(1, 1, maxn - 1, 10, 48)); Console.WriteLine(\"Maximum divisors that a number \" + \"has in [1, 10] are \" + query(1, 1, maxn - 1, 1, 10)); }} // This code is contributed by 29AjayKumar",
"e": 18882,
"s": 14617,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above idea to process// queries of finding a number with maximum divisors. let maxn = 10005; let INF = 999999; let smallest_prime = new Array(maxn); for(let i=0;i<maxn;i++) { smallest_prime[i]=0; } let divisors = new Array(maxn); for(let i=0;i<maxn;i++) { divisors[i]=0; } let segmentTree = new Array(4 * maxn); for(let i=0;i<4*maxn;i++) { segmentTree[i]=0; } // Finds smallest prime factor of all numbers // in range[1, maxn) and stores them in // smallest_prime[], smallest_prime[i] should // contain the smallest prime that divides i function findSmallestPrimeFactors() { // Initialize the smallest_prime factors // of all to infinity for (let i = 0 ; i < maxn ; i ++ ) smallest_prime[i] = INF; // to be built like eratosthenes sieve for (let i = 2; i < maxn; i++) { if (smallest_prime[i] == INF) { // prime number will have its // smallest_prime equal to itself smallest_prime[i] = i; for (let j = i * i; j < maxn; j += i) { // if 'i' is the first // prime number reaching 'j' if (smallest_prime[j] > i) smallest_prime[j] = i; } } } } // number of divisors of n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // are equal to (k1+1) * (k2+1) ... (kn+1) // this function finds the number of divisors of all numbers // in range [1, maxn) and stores it in divisors[] // divisors[i] stores the number of divisors i has function buildDivisorsArray() { for (let i = 1; i < maxn; i++) { divisors[i] = 1; let n = i; let p = smallest_prime[i] let k = 0; // we can obtain the prime factorization of // the number n, n = (p1 ^ k1) * (p2 ^ k2) ... (pn ^ kn) // using the smallest_prime[] array, we keep dividing n // by its smallest_prime until it becomes 1, // whilst we check if we have need to set k zero while (n > 1) { n = Math.floor(n / p); k++; if (smallest_prime[n] != p) { // use p^k, initialize k to 0 divisors[i] = divisors[i] * (k + 1); k = 0; } p = smallest_prime[n]; } } } // builds segment tree for divisors[] array function buildSegtmentTree(node,a,b) { // leaf node if (a == b) { segmentTree[node] = divisors[a]; return ; } //build left and right subtree buildSegtmentTree(2 * node, a, Math.floor((a + b) / 2)); buildSegtmentTree((2 * node) + 1, Math.floor((a + b) / 2) + 1, b); //combine the information from left //and right subtree at current node segmentTree[node] = Math.max(segmentTree[2 * node], segmentTree[(2 *node) + 1]); } // returns the maximum number of divisors in [l, r] function query(node,a,b,l,r) { // If current node's range is disjoint // with query range if (l > b || a > r) return -1; // If the current node stores information // for the range that is completely inside // the query range if (a >= l && b <= r) return segmentTree[node]; // Returns maximum number of divisors from left // or right subtree return Math.max(query(2 * node, a, Math.floor((a + b) / 2), l, r), query(2 * node + 1, Math.floor((a + b) / 2) + 1, b, l, r)); } // Driver Code // First find smallest prime divisors // for all the numbers findSmallestPrimeFactors(); // Then build the divisors[] array to store // the number of divisors buildDivisorsArray(); // Build segment tree for the divisors[] array buildSegtmentTree(1, 1, maxn - 1); document.write(\"Maximum divisors that a number \" + \"has in [1, 100] are \" + query(1, 1, maxn - 1, 1, 100)+\"<br>\"); document.write(\"Maximum divisors that a number \" + \"has in [10, 48] are \" + query(1, 1, maxn - 1, 10, 48)+\"<br>\"); document.write(\"Maximum divisors that a number \" + \"has in [1, 10] are \" + query(1, 1, maxn - 1, 1, 10)+\"<br>\"); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 23680,
"s": 18882,
"text": null
},
{
"code": null,
"e": 23690,
"s": 23680,
"text": "Output: "
},
{
"code": null,
"e": 23850,
"s": 23690,
"text": "Maximum divisors that a number has in [1, 100] are 12\nMaximum divisors that a number has in [10, 48] are 10\nMaximum divisors that a number has in [1, 10] are 4"
},
{
"code": null,
"e": 23869,
"s": 23850,
"text": "Time Complexity: "
},
{
"code": null,
"e": 24055,
"s": 23869,
"text": "For sieve: O(maxn * log(log(maxn)) )\nFor calculating divisors of each number: O(k1 + k2 + ... + kn) < O(log(maxn))\nFor querying each range: O(log(maxn))\nTotal: O((maxn + Q) * log(maxn))"
},
{
"code": null,
"e": 24483,
"s": 24055,
"text": "This article is contributed by Saumye Malhotra. 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. "
},
{
"code": null,
"e": 24489,
"s": 24483,
"text": "ukasp"
},
{
"code": null,
"e": 24503,
"s": 24489,
"text": "princiraj1992"
},
{
"code": null,
"e": 24515,
"s": 24503,
"text": "29AjayKumar"
},
{
"code": null,
"e": 24536,
"s": 24515,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 24545,
"s": 24536,
"text": "divisors"
},
{
"code": null,
"e": 24558,
"s": 24545,
"text": "Segment-Tree"
},
{
"code": null,
"e": 24564,
"s": 24558,
"text": "sieve"
},
{
"code": null,
"e": 24577,
"s": 24564,
"text": "Mathematical"
},
{
"code": null,
"e": 24590,
"s": 24577,
"text": "Mathematical"
},
{
"code": null,
"e": 24596,
"s": 24590,
"text": "sieve"
},
{
"code": null,
"e": 24609,
"s": 24596,
"text": "Segment-Tree"
},
{
"code": null,
"e": 24707,
"s": 24609,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24731,
"s": 24707,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 24752,
"s": 24731,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 24766,
"s": 24752,
"text": "Prime Numbers"
},
{
"code": null,
"e": 24803,
"s": 24766,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 24856,
"s": 24803,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 24899,
"s": 24856,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 24931,
"s": 24899,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 24972,
"s": 24931,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 24999,
"s": 24972,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
Java 9 features with examples
|
13 Apr, 2022
Java is a general purpose, high-level programming language developed by Sun Microsystems. It is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Java was meant to follow the “Write Once Run Anywhere” (WORA) principle, i.e., Java is meant to be platform independent.To learn more about the Java programming language in details, click here.Like any other software, Java also comes with many different versions as it develops and gets improved, with new features getting added in every major upgrade.Java 9 was a major upgrade from Java 8 that has brought us a lot of features for developers. Java 9 was released on Sep 21, 2017. In this article, we will look into Java 9 features in detail:
Java 9 update came with an updated Java documentation. We no longer need to use Google to find the right documentation. The new Javadoc came with search right in the API documentation itself. Moreover, the Javadoc output was HTML5 compliant. Every Javadoc page includes information on which JDK module the class or interface comes from.
Many a times, you want to create a collection (e.g., a List or Set) in your Java program and fill it with some elements. That leads to repetitive coding where you instantiate the collection, followed by several ‘add’ calls. With Java 9, several so-called collection factory methods have been added.List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:Empty List example:
List immutableList = List.of();
Non-Empty List example:
List immutableList = List.of("one", "two", "three");
Map has two set of methods: of() methods and ofEntries() methods to create an Immutable Map object and an Immutable Map.Entry object respectively.Empty Map Example:
jshell> Map emptyImmutableMap = Map.of()
emptyImmutableMap ==> {}
Non-Empty Map Example:
jshell> Map nonemptyImmutableMap = Map.of(1, "one", 2, "two", 3, "three")
nonemptyImmutableMap ==> {2=two, 3=three, 1=one}
Oracle Corp. has introduced a new tool called “jshell”. It stands for Java Shell and also known as REPL (Read Evaluate Print Loop). Many languages already feature an interactive Read-Eval-Print-Loop, and Java now joins this club. It is used to execute and test any Java Constructs like class, interface, enum, object, statements etc. very easily. You can launch jshell from the console and directly start typing and executing Java code. The immediate feedback of jshell makes it a great tool to explore APIs and try out language features.
In Java SE 9, Oracle Corp. has added four useful new methods to java.util.Stream interface. As Stream is an interface, all those new implemented methods are default methods. It allows you to create declarative pipelines of transformations on collections. There are four new methods added to the Stream interface: dropWhile, takeWhile, ofNullable. The iterate method gets a new overload, allowing you to provide a Predicate on when to stop iterating.
In Java 8, we can provide method implementation in Interfaces using Default and Static methods. However we cannot create private methods in Interfaces. To avoid redundant code and more re-usability, Oracle Corp. introduced private methods in Java SE 9 Interfaces. From Java SE 9 on-wards, we can write private and private static methods too in an interface using ‘private’ keyword.
public interface Card{
private Long createCardID(){
// Method implementation goes here.
}
private static void displayCardDetails(){
// Method implementation goes here.
}
}
In Java SE 9, Oracle Corp. introduced a new Multi-Resolution Image API. Important interface in this API is MultiResolutionImage . It is available in java.awt.image package. MultiResolutionImage encapsulates a set of images with different Height and Widths and allows us to query them with our requirements.
One of the big changes or java 9 feature is the Module System. Oracle Corp. introduced the following features as part of Jigsaw Project:
Modular JDK
Modular Java Source Code
Modular Run-time Images
Encapsulate Java Internal APIs
Java Platform Module System
Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications. This architecture has lot of limitations and drawbacks. To avoid all these shortcomings, Java SE 9 comes with the Module System.
Java SE 9 is coming with some improvements in Process API. They have added couple new classes and methods to ease the controlling and managing of OS processes.Two new interface in Process API:
java.lang.ProcessHandle
java.lang.ProcessHandle.Info
A new way of performing HTTP calls arrives with Java 9. As existing or Legacy HTTP Client API has numerous issues (like supports HTTP/1.1 protocol and does not support HTTP/2 protocol and WebSocket, works only in Blocking mode and lot of performance issues.), they are replacing this HttpURLConnection API with new HTTP client. They are going to introduce new HTTP 2 Client API under “java.net.http” package. It supports both HTTP/1.1 and HTTP/2 protocols. It supports both Synchronous (Blocking Mode) and Asynchronous Modes. It supports Asynchronous Mode using WebSocket API.
HttpClient client = HttpClient.newHttpClient();
HttpRequest req =
HttpRequest.newBuilder(URI.create("http://www.google.com"))
.header("User-Agent", "Java")
.GET()
.build();
HttpResponse resp = client.send(req, HttpResponse.BodyHandler.asString());
GC (Garbage Collector) Improvements
Stack-Walking API
Filter Incoming Serialization Data
Deprecate the Applet API
Indify String Concatenation
Enhanced Method Handles
Java Platform Logging API and Service
Compact Strings
Parser API for Nashorn
Javadoc Search
___________________________________________________________________________________________________________________P.S.: Java SE 9 has reached end of support. Users of Java SE 9 should switch to Java SE 10 or later.Useful links to learn more about Java:1. Wikipedia2. Oracle Documentation
rkbhola5
girishpathak
Picked
Technical Scripter 2018
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Set in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Apr, 2022"
},
{
"code": null,
"e": 816,
"s": 52,
"text": "Java is a general purpose, high-level programming language developed by Sun Microsystems. It is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. Java was meant to follow the “Write Once Run Anywhere” (WORA) principle, i.e., Java is meant to be platform independent.To learn more about the Java programming language in details, click here.Like any other software, Java also comes with many different versions as it develops and gets improved, with new features getting added in every major upgrade.Java 9 was a major upgrade from Java 8 that has brought us a lot of features for developers. Java 9 was released on Sep 21, 2017. In this article, we will look into Java 9 features in detail:"
},
{
"code": null,
"e": 1153,
"s": 816,
"text": "Java 9 update came with an updated Java documentation. We no longer need to use Google to find the right documentation. The new Javadoc came with search right in the API documentation itself. Moreover, the Javadoc output was HTML5 compliant. Every Javadoc page includes information on which JDK module the class or interface comes from."
},
{
"code": null,
"e": 1591,
"s": 1153,
"text": "Many a times, you want to create a collection (e.g., a List or Set) in your Java program and fill it with some elements. That leads to repetitive coding where you instantiate the collection, followed by several ‘add’ calls. With Java 9, several so-called collection factory methods have been added.List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:Empty List example:"
},
{
"code": null,
"e": 1624,
"s": 1591,
"text": "List immutableList = List.of();\n"
},
{
"code": null,
"e": 1648,
"s": 1624,
"text": "Non-Empty List example:"
},
{
"code": null,
"e": 1702,
"s": 1648,
"text": "List immutableList = List.of(\"one\", \"two\", \"three\");\n"
},
{
"code": null,
"e": 1867,
"s": 1702,
"text": "Map has two set of methods: of() methods and ofEntries() methods to create an Immutable Map object and an Immutable Map.Entry object respectively.Empty Map Example:"
},
{
"code": null,
"e": 1934,
"s": 1867,
"text": "jshell> Map emptyImmutableMap = Map.of()\nemptyImmutableMap ==> {}\n"
},
{
"code": null,
"e": 1957,
"s": 1934,
"text": "Non-Empty Map Example:"
},
{
"code": null,
"e": 2081,
"s": 1957,
"text": "jshell> Map nonemptyImmutableMap = Map.of(1, \"one\", 2, \"two\", 3, \"three\")\nnonemptyImmutableMap ==> {2=two, 3=three, 1=one}\n"
},
{
"code": null,
"e": 2620,
"s": 2081,
"text": "Oracle Corp. has introduced a new tool called “jshell”. It stands for Java Shell and also known as REPL (Read Evaluate Print Loop). Many languages already feature an interactive Read-Eval-Print-Loop, and Java now joins this club. It is used to execute and test any Java Constructs like class, interface, enum, object, statements etc. very easily. You can launch jshell from the console and directly start typing and executing Java code. The immediate feedback of jshell makes it a great tool to explore APIs and try out language features."
},
{
"code": null,
"e": 3070,
"s": 2620,
"text": "In Java SE 9, Oracle Corp. has added four useful new methods to java.util.Stream interface. As Stream is an interface, all those new implemented methods are default methods. It allows you to create declarative pipelines of transformations on collections. There are four new methods added to the Stream interface: dropWhile, takeWhile, ofNullable. The iterate method gets a new overload, allowing you to provide a Predicate on when to stop iterating."
},
{
"code": null,
"e": 3452,
"s": 3070,
"text": "In Java 8, we can provide method implementation in Interfaces using Default and Static methods. However we cannot create private methods in Interfaces. To avoid redundant code and more re-usability, Oracle Corp. introduced private methods in Java SE 9 Interfaces. From Java SE 9 on-wards, we can write private and private static methods too in an interface using ‘private’ keyword."
},
{
"code": null,
"e": 3644,
"s": 3452,
"text": "public interface Card{\n\n private Long createCardID(){\n // Method implementation goes here.\n }\n\n private static void displayCardDetails(){\n // Method implementation goes here.\n }\n\n}\n"
},
{
"code": null,
"e": 3951,
"s": 3644,
"text": "In Java SE 9, Oracle Corp. introduced a new Multi-Resolution Image API. Important interface in this API is MultiResolutionImage . It is available in java.awt.image package. MultiResolutionImage encapsulates a set of images with different Height and Widths and allows us to query them with our requirements."
},
{
"code": null,
"e": 4088,
"s": 3951,
"text": "One of the big changes or java 9 feature is the Module System. Oracle Corp. introduced the following features as part of Jigsaw Project:"
},
{
"code": null,
"e": 4100,
"s": 4088,
"text": "Modular JDK"
},
{
"code": null,
"e": 4125,
"s": 4100,
"text": "Modular Java Source Code"
},
{
"code": null,
"e": 4149,
"s": 4125,
"text": "Modular Run-time Images"
},
{
"code": null,
"e": 4180,
"s": 4149,
"text": "Encapsulate Java Internal APIs"
},
{
"code": null,
"e": 4208,
"s": 4180,
"text": "Java Platform Module System"
},
{
"code": null,
"e": 4429,
"s": 4208,
"text": "Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications. This architecture has lot of limitations and drawbacks. To avoid all these shortcomings, Java SE 9 comes with the Module System."
},
{
"code": null,
"e": 4622,
"s": 4429,
"text": "Java SE 9 is coming with some improvements in Process API. They have added couple new classes and methods to ease the controlling and managing of OS processes.Two new interface in Process API:"
},
{
"code": null,
"e": 4646,
"s": 4622,
"text": "java.lang.ProcessHandle"
},
{
"code": null,
"e": 4675,
"s": 4646,
"text": "java.lang.ProcessHandle.Info"
},
{
"code": null,
"e": 5252,
"s": 4675,
"text": "A new way of performing HTTP calls arrives with Java 9. As existing or Legacy HTTP Client API has numerous issues (like supports HTTP/1.1 protocol and does not support HTTP/2 protocol and WebSocket, works only in Blocking mode and lot of performance issues.), they are replacing this HttpURLConnection API with new HTTP client. They are going to introduce new HTTP 2 Client API under “java.net.http” package. It supports both HTTP/1.1 and HTTP/2 protocols. It supports both Synchronous (Blocking Mode) and Asynchronous Modes. It supports Asynchronous Mode using WebSocket API."
},
{
"code": null,
"e": 5549,
"s": 5252,
"text": "HttpClient client = HttpClient.newHttpClient();\n\nHttpRequest req =\n HttpRequest.newBuilder(URI.create(\"http://www.google.com\"))\n .header(\"User-Agent\", \"Java\")\n .GET()\n .build();\n\n\nHttpResponse resp = client.send(req, HttpResponse.BodyHandler.asString());\n"
},
{
"code": null,
"e": 5585,
"s": 5549,
"text": "GC (Garbage Collector) Improvements"
},
{
"code": null,
"e": 5603,
"s": 5585,
"text": "Stack-Walking API"
},
{
"code": null,
"e": 5638,
"s": 5603,
"text": "Filter Incoming Serialization Data"
},
{
"code": null,
"e": 5663,
"s": 5638,
"text": "Deprecate the Applet API"
},
{
"code": null,
"e": 5691,
"s": 5663,
"text": "Indify String Concatenation"
},
{
"code": null,
"e": 5715,
"s": 5691,
"text": "Enhanced Method Handles"
},
{
"code": null,
"e": 5753,
"s": 5715,
"text": "Java Platform Logging API and Service"
},
{
"code": null,
"e": 5769,
"s": 5753,
"text": "Compact Strings"
},
{
"code": null,
"e": 5792,
"s": 5769,
"text": "Parser API for Nashorn"
},
{
"code": null,
"e": 5807,
"s": 5792,
"text": "Javadoc Search"
},
{
"code": null,
"e": 6096,
"s": 5807,
"text": "___________________________________________________________________________________________________________________P.S.: Java SE 9 has reached end of support. Users of Java SE 9 should switch to Java SE 10 or later.Useful links to learn more about Java:1. Wikipedia2. Oracle Documentation"
},
{
"code": null,
"e": 6105,
"s": 6096,
"text": "rkbhola5"
},
{
"code": null,
"e": 6118,
"s": 6105,
"text": "girishpathak"
},
{
"code": null,
"e": 6125,
"s": 6118,
"text": "Picked"
},
{
"code": null,
"e": 6149,
"s": 6125,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 6154,
"s": 6149,
"text": "Java"
},
{
"code": null,
"e": 6173,
"s": 6154,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6178,
"s": 6173,
"text": "Java"
},
{
"code": null,
"e": 6276,
"s": 6178,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6327,
"s": 6276,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 6358,
"s": 6327,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 6377,
"s": 6358,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6407,
"s": 6377,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 6425,
"s": 6407,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6445,
"s": 6425,
"text": "Collections in Java"
},
{
"code": null,
"e": 6477,
"s": 6445,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6501,
"s": 6477,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6521,
"s": 6501,
"text": "Stack Class in Java"
}
] |
Python program to print Calendar without calendar or datetime module
|
10 Jul, 2020
Given the month and year. The task is to show the calendar of that month and in the given year without using any module or pre-defined functions.
Examples:
Input :
mm(1-12) :9
yy :2010
Output :
September 2010
Su Mo Tu We Th Fr Sa
01 02 03 04
05 06 07 08 09 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
Approach:
In the program below, we first calculate the number of odd days to find the day of the date 01-mm-yyyy.Then, we take in the year(yy) and the month(mm) as input and displays the calendar for that month of the year.
Below is the implementation of the given approach.
# Python code to print Calendar# Without use of Calendar module mm = 2yy = 2020 month ={1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'} # code below for calculation of odd daysday =(yy-1)% 400day = (day//100)*5 + ((day % 100) - (day % 100)//4) + ((day % 100)//4)*2day = day % 7 nly =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]ly =[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]s = 0 if yy % 4 == 0: for i in range(mm-1): s+= ly[i]else: for i in range(mm-1): s+= nly[i] day += s % 7day = day % 7 # variable used for white space filling # where date not presentspace =''space = space.rjust(2, ' ') # code below is to print the calendarprint(month[mm], yy)print('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa') if mm == 9 or mm == 4 or mm == 6 or mm == 11: for i in range(31 + day): if i<= day: print(space, end =' ') else: print("{:02d}".format(i-day), end =' ') if (i + 1)% 7 == 0: print()elif mm == 2: if yy % 4 == 0: p = 30 else: p = 29 for i in range(p + day): if i<= day: print(space, end =' ') else: print("{:02d}".format(i-day), end =' ') if (i + 1)% 7 == 0: print() else: for i in range(32 + day): if i<= day: print(space, end =' ') else: print("{:02d}".format(i-day), end =' ') if (i + 1)% 7 == 0: print()
Output:
February 2020
Su Mo Tu We Th Fr Sa
01
02 03 04 05 06 07 08
09 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
Python datetime-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 200,
"s": 54,
"text": "Given the month and year. The task is to show the calendar of that month and in the given year without using any module or pre-defined functions."
},
{
"code": null,
"e": 210,
"s": 200,
"text": "Examples:"
},
{
"code": null,
"e": 395,
"s": 210,
"text": "Input : \nmm(1-12) :9\nyy :2010\n\nOutput : \nSeptember 2010\nSu Mo Tu We Th Fr Sa\n 01 02 03 04 \n05 06 07 08 09 10 11 \n12 13 14 15 16 17 18 \n19 20 21 22 23 24 25 \n26 27 28 29 30 \n"
},
{
"code": null,
"e": 405,
"s": 395,
"text": "Approach:"
},
{
"code": null,
"e": 619,
"s": 405,
"text": "In the program below, we first calculate the number of odd days to find the day of the date 01-mm-yyyy.Then, we take in the year(yy) and the month(mm) as input and displays the calendar for that month of the year."
},
{
"code": null,
"e": 670,
"s": 619,
"text": "Below is the implementation of the given approach."
},
{
"code": "# Python code to print Calendar# Without use of Calendar module mm = 2yy = 2020 month ={1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December'} # code below for calculation of odd daysday =(yy-1)% 400day = (day//100)*5 + ((day % 100) - (day % 100)//4) + ((day % 100)//4)*2day = day % 7 nly =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]ly =[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]s = 0 if yy % 4 == 0: for i in range(mm-1): s+= ly[i]else: for i in range(mm-1): s+= nly[i] day += s % 7day = day % 7 # variable used for white space filling # where date not presentspace =''space = space.rjust(2, ' ') # code below is to print the calendarprint(month[mm], yy)print('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa') if mm == 9 or mm == 4 or mm == 6 or mm == 11: for i in range(31 + day): if i<= day: print(space, end =' ') else: print(\"{:02d}\".format(i-day), end =' ') if (i + 1)% 7 == 0: print()elif mm == 2: if yy % 4 == 0: p = 30 else: p = 29 for i in range(p + day): if i<= day: print(space, end =' ') else: print(\"{:02d}\".format(i-day), end =' ') if (i + 1)% 7 == 0: print() else: for i in range(32 + day): if i<= day: print(space, end =' ') else: print(\"{:02d}\".format(i-day), end =' ') if (i + 1)% 7 == 0: print()",
"e": 2294,
"s": 670,
"text": null
},
{
"code": null,
"e": 2302,
"s": 2294,
"text": "Output:"
},
{
"code": null,
"e": 2447,
"s": 2302,
"text": "February 2020\nSu Mo Tu We Th Fr Sa\n 01 \n02 03 04 05 06 07 08 \n09 10 11 12 13 14 15 \n16 17 18 19 20 21 22 \n23 24 25 26 27 28 29\n"
},
{
"code": null,
"e": 2471,
"s": 2447,
"text": "Python datetime-program"
},
{
"code": null,
"e": 2478,
"s": 2471,
"text": "Python"
},
{
"code": null,
"e": 2494,
"s": 2478,
"text": "Python Programs"
},
{
"code": null,
"e": 2592,
"s": 2494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2610,
"s": 2592,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2652,
"s": 2610,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2674,
"s": 2652,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2709,
"s": 2674,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2735,
"s": 2709,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2778,
"s": 2735,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2800,
"s": 2778,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2839,
"s": 2800,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2877,
"s": 2839,
"text": "Python | Convert a list to dictionary"
}
] |
Integrating Django with Reactjs using Django REST Framework
|
06 Jul, 2022
In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django.
Reactjs in a nutshell is a Javascript library for developing Single Page Applications(SPA) with very detailed and well-structured documentation. For this project, React will serve as the Frontend, handling the User Interface(UI) through the Request to Django’s backend.
Let’s take a look first at what we will be building. The below images shows the UI of the Task Manager.
This task manager application is a sort of to-do list. Here we will have three buttons as “Completed”, “Incomplete” and a button to add the task named “Add task” as shown in the above image.
In order to add a task, you click on the Add task button which will open up a window within the app to add the task as shown below. Here we can add the “Title” for the task and give it a description inside the “Description” section. Finally, you can check or uncheck depending upon the status of the task(ie, Completed or Incomplete) as shown in the below image:
After you “Save” the task, you can navigate between the Completed and Incomplete tabs to keep track of the tasks as shown below:
Here you will also have the option to “Delete” or “Edit” and existing task as shown below:
All of the operations performed above are managed by the Django REST Framework.
So the following are the prerequisites for the project:
Python 3 (preferably Python 3.5 and above)
Node js
VS Code( or, IDE of your choice)
To verify if you have python 3 installed, use the following command in your command prompt( Since this project is developed on a Windows machine, we will be using the command prompt but depending upon your operating system you can use the terminal):
python -V
This will show up the current python version on your system as shown below:
To check if the Node module is installed, use the below command:
node --version
This will show you the node version on your system as shown below:
At this point, we are good to go as we have Python and Node js installed in our system.
Let’s start with the Backend.
Now let’s open up our command prompt. Now follow the below steps in the same order to follow along with this article.
Step 1: Create a directory named “Django-react-app” using the below command(the command may change slightly depending upon your OS):
mkdir django-react-app
Step 2: Moved into the directory that we just created using the below command:
cd django-react-project
Step 3: Now create a virtual environment using the below command:
python -m venv dar
We have named our virtual environment “dar”, short for Django and react. This is necessary as we don’t have to install packages and dependencies globally. It is also a good programming practice.
Step 4: Activate the virtual environment that we just created using the below command:
dar\Scripts\activate.bat
This will activate our virtual machine as shown below:
Step 5: Now install Django inside the virtual machine using the below command:
pip install django
You will get a similar message as your installation gets completed:
Step 6: Now let’s create our project named “backend” for our Django backend. To do so use the below command:
django-admin startproject backend
The Django-react app will be our main folder and inside it, we will have two folders, one for the backend and one for the frontend that we will create later.
Step 7: Now navigate to the backend folder using the below command:
cd backend
Step 8: Now we will start our app and call it “todo” using the below command:
python manage.py startapp todo
The app gets created using the above command as shown below:
Now let’s go ahead and start up the VS code and open the project folder inside it. At this stage our project structure will look like below:
Step 9: Now use the below command to migrate the project:
python manage.py migrate
The migrations will be applied as shown below:
Step 10: Now let’s run the server using the below command:
python manage.py runserver
Now you can visit the local host to check if the project has started properly. As you can see in the below image the project is up and running:
Step 11: Now we need to take some configuration steps inside the settings.py file. In the INSTALLED_APPS section add the name of the app that we created (ie, todo) as shown below:
Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo',]
At this point, the settings.py file would look like below:
Python3
from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'.BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'django-insecure-_c3!4)8+yce2l-ju@gz@b6(e0$00y@xhx7+lxk1p==k+pyqko3' # SECURITY WARNING: don't run with debug turned on in production!DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] WSGI_APPLICATION = 'backend.wsgi.application' # Database# https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }} # Password validation# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] # Internationalization# https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Step 12: Next, we will need to create a Model. The Model will determine how the to-do items are stored in the database. We will have three properties in the model:
Title: This will be the title of the task with a maximum length of 150 characters.
Description: This will be the description of the task with a maximum length of 500 characters.
Completed: This will be a boolean value, that will be used to determine the current status of the task. By default, it will be set to false.
So go ahead and open the models.py file and the following code:
Python3
class Todo(models.Model): title=models.CharField(max_length=150) description=models.CharField(max_length=500) completed=models.BooleanField(default=False)
We will also create a string representation of the title inside the Todo class as follows:
Python3
def __str__(self): #it will return the title return self.title G")
At this point, our models.py file will look like this:
Python3
from django.db import models class Todo(models.Model): title=models.CharField(max_length=150) description=models.CharField(max_length=500) completed=models.BooleanField(default=False) # string representation of the class def __str__(self): #it will return the title return self.title
Step 13: Now let’s go ahead and make migrations. Note that every time you make changes to the models.py file, we will need to make migrations. Use the below command to do so:
python manage.py makemigrations
The following message will be generated when your migration is ready:
Step 14: Now let’s apply all migrations using the below command:
python manage.py migrate
This will apply our migrations as shown below:
Now we can test to see that the CRUD operations work on the todo model file using the Admin site (or, the interface). For this, we will need to register the models in the admin.py file.
Step 15: Open up the admin.py file and add up the following code in it:
Python3
from django.contrib import admin # import the model Todofrom .models import Todo # create a class for the admin-model integrationclass TodoAdmin(admin.ModelAdmin): # add the fields of the model here list_display = ("title","description","completed") # we will need to register the# model class and the Admin model class# using the register() method# of admin.site classadmin.site.register(Todo,TodoAdmin)
Step 16: Now let’s create a superuser using the below command:
python manage.py createsuperuser
Here we will be using the following credentials:
Username: Geeks
Email address: geeks@geeksforgeeks.org
Password:12345
Note: You can set up your credentials as per your need. The above credentials need not be the same.
We would get the following message when the superuser gets created:
Step 17: Now let’s run the server and check everything is going as intended so far using the below command:
python manage.py runserver
Navigate to the following link:
http://127.0.0.1:8000/admin/login/?next=/admin/
This will show us the admin page as shown below:
Here fill up your credentials and log in. We will use the credentials that we used while creating the superuser:
This will lead us to the following page. Here we can see our users, the app, and the groups as shown below:
Users:
Todo:
Let’s add some task to it and save it as shown below:
We can see this task listed on the todo section as shown below:
To create the API we will need to install the Django REST Framework for Serializers. We also need Django-cors-headers for whitelisting port 3000, which is the default port for React.
Now follow the below steps to create the Django REST framework:
Step 1: To install the Django REST framework use the below command in the backend directory:
pip install djangorestframework
The following message will be displayed once the installation is completed:
Step 2: Now install the Django-cors-headers using the below command:
pip install django-cors-headers
The following message will be displayed once the installation is completed:
Step 3: Now open up the setting.py file and add both the dependencies that we just installed to INSTALLED_APPS as shown below:
Python3
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo', 'corsheaders', 'rest_framework',]
Step 4: Also in the settings.py file we need to whitelist the localhost port 3000. If we don’t do that there will be a block between the localhost:8000 and localhost:3000. Add the following code to achieve the same:
Python3
# White listing the localhost:3000 port# for ReactCORS_ORIGIN_WHITELIST = ( 'http://localhost:3000',)
Step 5: In the MIDDLEWARE section we need to add the cors-headers settings as shown below:
Python3
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware']
At this point, our settings.py would look like below:
Python3
from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'.BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'django-insecure-_c3!4)8+yce2l-ju@gz@b6(e0$00y@xhx7+lxk1p==k+pyqko3' # SECURITY WARNING: don't run with debug turned on in production!DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo', 'corsheaders', 'rest_framework',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware'] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] WSGI_APPLICATION = 'backend.wsgi.application' # Database# https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }} # Password validation# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] # White listing the localhost:3000 portCORS_ORIGIN_WHITELIST = ( 'http://localhost:3000') # Internationalization# https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Now we need to create the Serializers for the Todo data Model. The Serializers are responsible for converting model instances to JSON. This will help the frontend to work with the received data easily. JSON is the standard for data interchange on the web.
Step 6: Now create a file inside the todo folder and name it serializers.py. Inside the folder add the following code:
Python3
# import serializers from the REST frameworkfrom rest_framework import serializers # import the todo data modelfrom .models import Todo # create a serializer classclass TodoSerializer(serializers.ModelSerializer): # create a meta class class Meta: model = Todo fields = ('id', 'title','description','completed')
Step 7: Now it’s time to create the Views. So open up the views.py file. Now add the following code to the file:
Python3
from django.shortcuts import render # import view sets from the REST frameworkfrom rest_framework import viewsets # import the TodoSerializer from the serializer filefrom .serializers import TodoSerializer # import the Todo model from the models filefrom .models import Todo # create a class for the Todo model viewsetsclass TodoView(viewsets.ModelViewSet): # create a serializer class and # assign it to the TodoSerializer class serializer_class = TodoSerializer # define a variable and populate it # with the Todo list objects queryset = Todo.objects.all()
Step 8: Now open up the urls.py file and add the following code to it.
Python3
from django.contrib import admin # add include to the pathfrom django.urls import path, include # import views from todofrom todo import views # import routers from the REST framework# it is necessary for routingfrom rest_framework import routers # create a router objectrouter = routers.DefaultRouter() # register the routerrouter.register(r'tasks',views.TodoView, 'task') urlpatterns = [ path('admin/', admin.site.urls), # add another path to the url patterns # when you visit the localhost:8000/api # you should be routed to the django Rest framework path('api/', include(router.urls)) ]
This is the final step for creating the REST API and we can now perform all CRUD operations. Routers allow us to make queries. For example, if we go the “tasks”, this will return the list of all the tasks. Also, you can have a single ‘task’ with an id to return a single task, where id is the primary key.
Now let’s check if we are moving forward in the right direction. So run the server and navigate to the following URL:
localhost:8000/api
If everything is good, we will get the following outcome:
As you can see our API is up and running.
Now if we navigate to the following links we can view and interact with our tasks:
locaLHOST:8000/api/tasks
Now let’s build the frontend for our Todo app. For this follow the below steps:
Step 1: Navigate to the main project directory(ie, Django-react-app) and activate the virtual environment using the below command:
dar\Scripts\activate.bat
Step 2: Now use the below command to create a boilerplate of React js app:
npx create-react-app frontend
Here, npx stands for Node Package Executable. After the boilerplate is setup you will get the following message:
We will be also needing some UI flair for the UI design, specifically reactstrap and bootstrap.
Step 3: So, use the below command to install reactstrap and bootstrap in the project:
npm install reactstrap bootstrap
Step 4: First move into the Frontend folder and use the below command to run the React server to make sure everything if working till this point:
npm start
If everything is fine, you’ll get the following page on the localhost:3000
Step 5: Now open up the App.js file in the frontend folder. And clear the boilerplate code and change it to the below code:
Javascript
import "./App.css"; function App() { return <div className="App"><h2>Welcome to Geeksforgeeks!</h2></div>;} export default App;
At this point the frontend will look like below:
As you can see in the above image. Any changes made to the App.js file are reflected directly to the UI.
Step 6: Now the code to the App.js file. Comments are added to the code for better understanding.
Javascript
// import Component from the react moduleimport React, { Component } from "react";import Modal from "./components/Modal";import axios from 'axios'; // create a class that extends the componentclass App extends Component { // add a constructor to take props constructor(props) { super(props); // add the props here this.state = { // the viewCompleted prop represents the status // of the task. Set it to false by default viewCompleted: false, activeItem: { title: "", description: "", completed: false }, // this list stores all the completed tasks taskList: [] }; } // Add componentDidMount() componentDidMount() { this.refreshList(); } refreshList = () => { axios //Axios to send and receive HTTP requests .get("http://localhost:8000/api/tasks/") .then(res => this.setState({ taskList: res.data })) .catch(err => console.log(err)); }; // this arrow function takes status as a parameter // and changes the status of viewCompleted to true // if the status is true, else changes it to false displayCompleted = status => { if (status) { return this.setState({ viewCompleted: true }); } return this.setState({ viewCompleted: false }); }; // this array function renders two spans that help control // the set of items to be displayed(ie, completed or incomplete) renderTabList = () => { return ( <div className="my-5 tab-list"> <span onClick={() => this.displayCompleted(true)} className={this.state.viewCompleted ? "active" : ""} > completed </span> <span onClick={() => this.displayCompleted(false)} className={this.state.viewCompleted ? "" : "active"} > Incompleted </span> </div> ); }; // Main variable to render items on the screen renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.taskList.filter( (item) => item.completed === viewCompleted ); return newItems.map((item) => ( <li key={item.id} className="list-group-item d-flex justify-content-between align-items-center" > <span className={`todo-title mr-2 ${ this.state.viewCompleted ? "completed-todo" : "" }`} title={item.description} > {item.title} </span> <span> <button onClick={() => this.editItem(item)} className="btn btn-secondary mr-2" > Edit </button> <button onClick={() => this.handleDelete(item)} className="btn btn-danger" > Delete </button> </span> </li> )); }; toggle = () => { //add this after modal creation this.setState({ modal: !this.state.modal }); }; handleSubmit = (item) => { this.toggle(); alert("save" + JSON.stringify(item)); }; // Submit an item handleSubmit = (item) => { this.toggle(); if (item.id) { // if old post to edit and submit axios .put(`http://localhost:8000/api/tasks/${item.id}/`, item) .then((res) => this.refreshList()); return; } // if new post to submit axios .post("http://localhost:8000/api/tasks/", item) .then((res) => this.refreshList()); }; // Delete item handleDelete = (item) => { axios .delete(`http://localhost:8000/api/tasks/${item.id}/`) .then((res) => this.refreshList()); }; handleDelete = (item) => { alert("delete" + JSON.stringify(item)); }; // Create item createItem = () => { const item = { title: "", description: "", completed: false }; this.setState({ activeItem: item, modal: !this.state.modal }); }; //Edit item editItem = (item) => { this.setState({ activeItem: item, modal: !this.state.modal }); }; // Start by visual effects to viewer render() { return ( <main className="content"> <h1 className="text-success text-uppercase text-center my-4"> GFG Task Manager </h1> <div className="row "> <div className="col-md-6 col-sm-10 mx-auto p-0"> <div className="card p-3"> <div className=""> <button onClick={this.createItem} className="btn btn-info"> Add task </button> </div> {this.renderTabList()} <ul className="list-group list-group-flush"> {this.renderItems()} </ul> </div> </div> </div> {this.state.modal ? ( <Modal activeItem={this.state.activeItem} toggle={this.toggle} onSave={this.handleSubmit} /> ) : null} </main> ); }}export default App;
Step 7: Now open up the Index.css file, clear the CSS inside it and add the following CSS in the file:
CSS
.todo-title { cursor: pointer;}.completed-todo { text-decoration: line-through;}.tab-list > span { padding: 5px 8px; border: 1px solid rgb(7, 167, 68); border-radius: 10px; margin-right: 5px; cursor: pointer;}.tab-list > span.active { background-color: rgb(6, 139, 12); color: #fff;}
Step 8: Now create a new folder named “Components” in the src directory and add a file Modal.js to it. Then add the following code to it.
Javascript
import React, { Component } from "react"; // importing all of these classes from reactstrap moduleimport { Button, Modal, ModalHeader, ModalBody, ModalFooter, Form, FormGroup, Input, Label} from "reactstrap"; // build a class base componentclass CustomModal extends Component { constructor(props) { super(props); this.state = { activeItem: this.props.activeItem }; } // changes handler to check if a checkbox is checed or not handleChange = e => { let { name, value } = e.target; if (e.target.type === "checkbox") { value = e.target.checked; } const activeItem = { ...this.state.activeItem, [name]: value }; this.setState({ activeItem }); }; // rendering modal in the custommodal class received toggle and on save as props, render() { const { toggle, onSave } = this.props; return ( <Modal isOpen={true} toggle={toggle}> <ModalHeader toggle={toggle}> Task Item </ModalHeader> <ModalBody> <Form> {/* 3 formgroups 1 title label */} <FormGroup> <Label for="title">Title</Label> <Input type="text" name="title" value={this.state.activeItem.title} onChange={this.handleChange} placeholder="Enter Task Title" /> </FormGroup> {/* 2 description label */} <FormGroup> <Label for="description">Description</Label> <Input type="text" name="description" value={this.state.activeItem.description} onChange={this.handleChange} placeholder="Enter Task Description" /> </FormGroup> {/* 3 completed label */} <FormGroup check> <Label for="completed"> <Input type="checkbox" name="completed" checked={this.state.activeItem.completed} onChange={this.handleChange} /> Completed </Label> </FormGroup> </Form> </ModalBody> {/* create a modal footer */} <ModalFooter> <Button color="success" onClick={() => onSave(this.state.activeItem)}> Save </Button> </ModalFooter> </Modal> ); }}export default CustomModal
Step 10: Make the changes to the index.js file as follows:
Javascript
import React from "react";import ReactDOM from "react-dom";import "./index.css";import App from "./App"; // importing css stylesheet to use the bootstrap class// add this line only in this fileimport "bootstrap/dist/css/bootstrap.min.css"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById("root"));
For us to make requests to the API endpoints on the backend server of Django, we will need to install Axios. Use the following command inside the frontend folder to install Axios:
npm install axios
Output:
Congratulation!!. At this point, you have successfully build a Fullstack Django-React app and Used the Django REST framework to establish communication between the frontend and backend.
khushboogoyal499
punamsingh628700
nikhatkhan11
mmslavin
simmytarika5
Blogathon-2021
Python Django
react-js
Blogathon
Python
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 361,
"s": 28,
"text": "In this article, we will learn the process of communicating between the Django Backend and React js frontend using the Django REST Framework. For the sake of a better understanding of the concept, we will be building a Simple Task Manager and go through the primary concepts for this type of integration between React js and Django."
},
{
"code": null,
"e": 631,
"s": 361,
"text": "Reactjs in a nutshell is a Javascript library for developing Single Page Applications(SPA) with very detailed and well-structured documentation. For this project, React will serve as the Frontend, handling the User Interface(UI) through the Request to Django’s backend."
},
{
"code": null,
"e": 735,
"s": 631,
"text": "Let’s take a look first at what we will be building. The below images shows the UI of the Task Manager."
},
{
"code": null,
"e": 926,
"s": 735,
"text": "This task manager application is a sort of to-do list. Here we will have three buttons as “Completed”, “Incomplete” and a button to add the task named “Add task” as shown in the above image."
},
{
"code": null,
"e": 1289,
"s": 926,
"text": "In order to add a task, you click on the Add task button which will open up a window within the app to add the task as shown below. Here we can add the “Title” for the task and give it a description inside the “Description” section. Finally, you can check or uncheck depending upon the status of the task(ie, Completed or Incomplete) as shown in the below image:"
},
{
"code": null,
"e": 1418,
"s": 1289,
"text": "After you “Save” the task, you can navigate between the Completed and Incomplete tabs to keep track of the tasks as shown below:"
},
{
"code": null,
"e": 1509,
"s": 1418,
"text": "Here you will also have the option to “Delete” or “Edit” and existing task as shown below:"
},
{
"code": null,
"e": 1589,
"s": 1509,
"text": "All of the operations performed above are managed by the Django REST Framework."
},
{
"code": null,
"e": 1645,
"s": 1589,
"text": "So the following are the prerequisites for the project:"
},
{
"code": null,
"e": 1688,
"s": 1645,
"text": "Python 3 (preferably Python 3.5 and above)"
},
{
"code": null,
"e": 1696,
"s": 1688,
"text": "Node js"
},
{
"code": null,
"e": 1729,
"s": 1696,
"text": "VS Code( or, IDE of your choice)"
},
{
"code": null,
"e": 1979,
"s": 1729,
"text": "To verify if you have python 3 installed, use the following command in your command prompt( Since this project is developed on a Windows machine, we will be using the command prompt but depending upon your operating system you can use the terminal):"
},
{
"code": null,
"e": 1989,
"s": 1979,
"text": "python -V"
},
{
"code": null,
"e": 2065,
"s": 1989,
"text": "This will show up the current python version on your system as shown below:"
},
{
"code": null,
"e": 2130,
"s": 2065,
"text": "To check if the Node module is installed, use the below command:"
},
{
"code": null,
"e": 2145,
"s": 2130,
"text": "node --version"
},
{
"code": null,
"e": 2212,
"s": 2145,
"text": "This will show you the node version on your system as shown below:"
},
{
"code": null,
"e": 2300,
"s": 2212,
"text": "At this point, we are good to go as we have Python and Node js installed in our system."
},
{
"code": null,
"e": 2330,
"s": 2300,
"text": "Let’s start with the Backend."
},
{
"code": null,
"e": 2448,
"s": 2330,
"text": "Now let’s open up our command prompt. Now follow the below steps in the same order to follow along with this article."
},
{
"code": null,
"e": 2581,
"s": 2448,
"text": "Step 1: Create a directory named “Django-react-app” using the below command(the command may change slightly depending upon your OS):"
},
{
"code": null,
"e": 2604,
"s": 2581,
"text": "mkdir django-react-app"
},
{
"code": null,
"e": 2683,
"s": 2604,
"text": "Step 2: Moved into the directory that we just created using the below command:"
},
{
"code": null,
"e": 2707,
"s": 2683,
"text": "cd django-react-project"
},
{
"code": null,
"e": 2773,
"s": 2707,
"text": "Step 3: Now create a virtual environment using the below command:"
},
{
"code": null,
"e": 2792,
"s": 2773,
"text": "python -m venv dar"
},
{
"code": null,
"e": 2987,
"s": 2792,
"text": "We have named our virtual environment “dar”, short for Django and react. This is necessary as we don’t have to install packages and dependencies globally. It is also a good programming practice."
},
{
"code": null,
"e": 3074,
"s": 2987,
"text": "Step 4: Activate the virtual environment that we just created using the below command:"
},
{
"code": null,
"e": 3099,
"s": 3074,
"text": "dar\\Scripts\\activate.bat"
},
{
"code": null,
"e": 3154,
"s": 3099,
"text": "This will activate our virtual machine as shown below:"
},
{
"code": null,
"e": 3233,
"s": 3154,
"text": "Step 5: Now install Django inside the virtual machine using the below command:"
},
{
"code": null,
"e": 3252,
"s": 3233,
"text": "pip install django"
},
{
"code": null,
"e": 3320,
"s": 3252,
"text": "You will get a similar message as your installation gets completed:"
},
{
"code": null,
"e": 3429,
"s": 3320,
"text": "Step 6: Now let’s create our project named “backend” for our Django backend. To do so use the below command:"
},
{
"code": null,
"e": 3463,
"s": 3429,
"text": "django-admin startproject backend"
},
{
"code": null,
"e": 3621,
"s": 3463,
"text": "The Django-react app will be our main folder and inside it, we will have two folders, one for the backend and one for the frontend that we will create later."
},
{
"code": null,
"e": 3689,
"s": 3621,
"text": "Step 7: Now navigate to the backend folder using the below command:"
},
{
"code": null,
"e": 3700,
"s": 3689,
"text": "cd backend"
},
{
"code": null,
"e": 3778,
"s": 3700,
"text": "Step 8: Now we will start our app and call it “todo” using the below command:"
},
{
"code": null,
"e": 3809,
"s": 3778,
"text": "python manage.py startapp todo"
},
{
"code": null,
"e": 3870,
"s": 3809,
"text": "The app gets created using the above command as shown below:"
},
{
"code": null,
"e": 4011,
"s": 3870,
"text": "Now let’s go ahead and start up the VS code and open the project folder inside it. At this stage our project structure will look like below:"
},
{
"code": null,
"e": 4070,
"s": 4011,
"text": " Step 9: Now use the below command to migrate the project:"
},
{
"code": null,
"e": 4095,
"s": 4070,
"text": "python manage.py migrate"
},
{
"code": null,
"e": 4142,
"s": 4095,
"text": "The migrations will be applied as shown below:"
},
{
"code": null,
"e": 4201,
"s": 4142,
"text": "Step 10: Now let’s run the server using the below command:"
},
{
"code": null,
"e": 4228,
"s": 4201,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 4372,
"s": 4228,
"text": "Now you can visit the local host to check if the project has started properly. As you can see in the below image the project is up and running:"
},
{
"code": null,
"e": 4552,
"s": 4372,
"text": "Step 11: Now we need to take some configuration steps inside the settings.py file. In the INSTALLED_APPS section add the name of the app that we created (ie, todo) as shown below:"
},
{
"code": null,
"e": 4560,
"s": 4552,
"text": "Python3"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo',]",
"e": 4796,
"s": 4560,
"text": null
},
{
"code": null,
"e": 4858,
"s": 4799,
"text": "At this point, the settings.py file would look like below:"
},
{
"code": null,
"e": 4868,
"s": 4860,
"text": "Python3"
},
{
"code": "from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'.BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'django-insecure-_c3!4)8+yce2l-ju@gz@b6(e0$00y@xhx7+lxk1p==k+pyqko3' # SECURITY WARNING: don't run with debug turned on in production!DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] WSGI_APPLICATION = 'backend.wsgi.application' # Database# https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }} # Password validation# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] # Internationalization# https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'",
"e": 7732,
"s": 4868,
"text": null
},
{
"code": null,
"e": 7896,
"s": 7732,
"text": "Step 12: Next, we will need to create a Model. The Model will determine how the to-do items are stored in the database. We will have three properties in the model:"
},
{
"code": null,
"e": 7979,
"s": 7896,
"text": "Title: This will be the title of the task with a maximum length of 150 characters."
},
{
"code": null,
"e": 8074,
"s": 7979,
"text": "Description: This will be the description of the task with a maximum length of 500 characters."
},
{
"code": null,
"e": 8215,
"s": 8074,
"text": "Completed: This will be a boolean value, that will be used to determine the current status of the task. By default, it will be set to false."
},
{
"code": null,
"e": 8279,
"s": 8215,
"text": "So go ahead and open the models.py file and the following code:"
},
{
"code": null,
"e": 8287,
"s": 8279,
"text": "Python3"
},
{
"code": "class Todo(models.Model): title=models.CharField(max_length=150) description=models.CharField(max_length=500) completed=models.BooleanField(default=False)",
"e": 8451,
"s": 8287,
"text": null
},
{
"code": null,
"e": 8545,
"s": 8454,
"text": "We will also create a string representation of the title inside the Todo class as follows:"
},
{
"code": null,
"e": 8555,
"s": 8547,
"text": "Python3"
},
{
"code": "def __str__(self): #it will return the title return self.title G\")",
"e": 8625,
"s": 8555,
"text": null
},
{
"code": null,
"e": 8680,
"s": 8625,
"text": "At this point, our models.py file will look like this:"
},
{
"code": null,
"e": 8688,
"s": 8680,
"text": "Python3"
},
{
"code": "from django.db import models class Todo(models.Model): title=models.CharField(max_length=150) description=models.CharField(max_length=500) completed=models.BooleanField(default=False) # string representation of the class def __str__(self): #it will return the title return self.title",
"e": 9003,
"s": 8688,
"text": null
},
{
"code": null,
"e": 9178,
"s": 9003,
"text": "Step 13: Now let’s go ahead and make migrations. Note that every time you make changes to the models.py file, we will need to make migrations. Use the below command to do so:"
},
{
"code": null,
"e": 9210,
"s": 9178,
"text": "python manage.py makemigrations"
},
{
"code": null,
"e": 9280,
"s": 9210,
"text": "The following message will be generated when your migration is ready:"
},
{
"code": null,
"e": 9345,
"s": 9280,
"text": "Step 14: Now let’s apply all migrations using the below command:"
},
{
"code": null,
"e": 9370,
"s": 9345,
"text": "python manage.py migrate"
},
{
"code": null,
"e": 9417,
"s": 9370,
"text": "This will apply our migrations as shown below:"
},
{
"code": null,
"e": 9603,
"s": 9417,
"text": "Now we can test to see that the CRUD operations work on the todo model file using the Admin site (or, the interface). For this, we will need to register the models in the admin.py file."
},
{
"code": null,
"e": 9675,
"s": 9603,
"text": "Step 15: Open up the admin.py file and add up the following code in it:"
},
{
"code": null,
"e": 9683,
"s": 9675,
"text": "Python3"
},
{
"code": "from django.contrib import admin # import the model Todofrom .models import Todo # create a class for the admin-model integrationclass TodoAdmin(admin.ModelAdmin): # add the fields of the model here list_display = (\"title\",\"description\",\"completed\") # we will need to register the# model class and the Admin model class# using the register() method# of admin.site classadmin.site.register(Todo,TodoAdmin)",
"e": 10095,
"s": 9683,
"text": null
},
{
"code": null,
"e": 10158,
"s": 10095,
"text": "Step 16: Now let’s create a superuser using the below command:"
},
{
"code": null,
"e": 10191,
"s": 10158,
"text": "python manage.py createsuperuser"
},
{
"code": null,
"e": 10240,
"s": 10191,
"text": "Here we will be using the following credentials:"
},
{
"code": null,
"e": 10256,
"s": 10240,
"text": "Username: Geeks"
},
{
"code": null,
"e": 10295,
"s": 10256,
"text": "Email address: geeks@geeksforgeeks.org"
},
{
"code": null,
"e": 10310,
"s": 10295,
"text": "Password:12345"
},
{
"code": null,
"e": 10411,
"s": 10310,
"text": "Note: You can set up your credentials as per your need. The above credentials need not be the same. "
},
{
"code": null,
"e": 10479,
"s": 10411,
"text": "We would get the following message when the superuser gets created:"
},
{
"code": null,
"e": 10587,
"s": 10479,
"text": "Step 17: Now let’s run the server and check everything is going as intended so far using the below command:"
},
{
"code": null,
"e": 10614,
"s": 10587,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 10646,
"s": 10614,
"text": "Navigate to the following link:"
},
{
"code": null,
"e": 10694,
"s": 10646,
"text": "http://127.0.0.1:8000/admin/login/?next=/admin/"
},
{
"code": null,
"e": 10743,
"s": 10694,
"text": "This will show us the admin page as shown below:"
},
{
"code": null,
"e": 10856,
"s": 10743,
"text": "Here fill up your credentials and log in. We will use the credentials that we used while creating the superuser:"
},
{
"code": null,
"e": 10964,
"s": 10856,
"text": "This will lead us to the following page. Here we can see our users, the app, and the groups as shown below:"
},
{
"code": null,
"e": 10971,
"s": 10964,
"text": "Users:"
},
{
"code": null,
"e": 10977,
"s": 10971,
"text": "Todo:"
},
{
"code": null,
"e": 11031,
"s": 10977,
"text": "Let’s add some task to it and save it as shown below:"
},
{
"code": null,
"e": 11095,
"s": 11031,
"text": "We can see this task listed on the todo section as shown below:"
},
{
"code": null,
"e": 11278,
"s": 11095,
"text": "To create the API we will need to install the Django REST Framework for Serializers. We also need Django-cors-headers for whitelisting port 3000, which is the default port for React."
},
{
"code": null,
"e": 11342,
"s": 11278,
"text": "Now follow the below steps to create the Django REST framework:"
},
{
"code": null,
"e": 11436,
"s": 11342,
"text": "Step 1: To install the Django REST framework use the below command in the backend directory:"
},
{
"code": null,
"e": 11468,
"s": 11436,
"text": "pip install djangorestframework"
},
{
"code": null,
"e": 11544,
"s": 11468,
"text": "The following message will be displayed once the installation is completed:"
},
{
"code": null,
"e": 11613,
"s": 11544,
"text": "Step 2: Now install the Django-cors-headers using the below command:"
},
{
"code": null,
"e": 11645,
"s": 11613,
"text": "pip install django-cors-headers"
},
{
"code": null,
"e": 11721,
"s": 11645,
"text": "The following message will be displayed once the installation is completed:"
},
{
"code": null,
"e": 11848,
"s": 11721,
"text": "Step 3: Now open up the setting.py file and add both the dependencies that we just installed to INSTALLED_APPS as shown below:"
},
{
"code": null,
"e": 11856,
"s": 11848,
"text": "Python3"
},
{
"code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo', 'corsheaders', 'rest_framework',]",
"e": 12106,
"s": 11856,
"text": null
},
{
"code": null,
"e": 12325,
"s": 12109,
"text": "Step 4: Also in the settings.py file we need to whitelist the localhost port 3000. If we don’t do that there will be a block between the localhost:8000 and localhost:3000. Add the following code to achieve the same:"
},
{
"code": null,
"e": 12335,
"s": 12327,
"text": "Python3"
},
{
"code": "# White listing the localhost:3000 port# for ReactCORS_ORIGIN_WHITELIST = ( 'http://localhost:3000',)",
"e": 12440,
"s": 12335,
"text": null
},
{
"code": null,
"e": 12534,
"s": 12443,
"text": "Step 5: In the MIDDLEWARE section we need to add the cors-headers settings as shown below:"
},
{
"code": null,
"e": 12544,
"s": 12536,
"text": "Python3"
},
{
"code": "MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware']",
"e": 12992,
"s": 12544,
"text": null
},
{
"code": null,
"e": 13046,
"s": 12992,
"text": "At this point, our settings.py would look like below:"
},
{
"code": null,
"e": 13054,
"s": 13046,
"text": "Python3"
},
{
"code": "from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'.BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = 'django-insecure-_c3!4)8+yce2l-ju@gz@b6(e0$00y@xhx7+lxk1p==k+pyqko3' # SECURITY WARNING: don't run with debug turned on in production!DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'todo', 'corsheaders', 'rest_framework',] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware'] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] WSGI_APPLICATION = 'backend.wsgi.application' # Database# https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }} # Password validation# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },] # White listing the localhost:3000 portCORS_ORIGIN_WHITELIST = ( 'http://localhost:3000') # Internationalization# https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'",
"e": 16092,
"s": 13054,
"text": null
},
{
"code": null,
"e": 16348,
"s": 16092,
"text": "Now we need to create the Serializers for the Todo data Model. The Serializers are responsible for converting model instances to JSON. This will help the frontend to work with the received data easily. JSON is the standard for data interchange on the web."
},
{
"code": null,
"e": 16467,
"s": 16348,
"text": "Step 6: Now create a file inside the todo folder and name it serializers.py. Inside the folder add the following code:"
},
{
"code": null,
"e": 16475,
"s": 16467,
"text": "Python3"
},
{
"code": "# import serializers from the REST frameworkfrom rest_framework import serializers # import the todo data modelfrom .models import Todo # create a serializer classclass TodoSerializer(serializers.ModelSerializer): # create a meta class class Meta: model = Todo fields = ('id', 'title','description','completed')",
"e": 16808,
"s": 16475,
"text": null
},
{
"code": null,
"e": 16924,
"s": 16811,
"text": "Step 7: Now it’s time to create the Views. So open up the views.py file. Now add the following code to the file:"
},
{
"code": null,
"e": 16934,
"s": 16926,
"text": "Python3"
},
{
"code": "from django.shortcuts import render # import view sets from the REST frameworkfrom rest_framework import viewsets # import the TodoSerializer from the serializer filefrom .serializers import TodoSerializer # import the Todo model from the models filefrom .models import Todo # create a class for the Todo model viewsetsclass TodoView(viewsets.ModelViewSet): # create a serializer class and # assign it to the TodoSerializer class serializer_class = TodoSerializer # define a variable and populate it # with the Todo list objects queryset = Todo.objects.all()",
"e": 17513,
"s": 16934,
"text": null
},
{
"code": null,
"e": 17587,
"s": 17516,
"text": "Step 8: Now open up the urls.py file and add the following code to it."
},
{
"code": null,
"e": 17597,
"s": 17589,
"text": "Python3"
},
{
"code": "from django.contrib import admin # add include to the pathfrom django.urls import path, include # import views from todofrom todo import views # import routers from the REST framework# it is necessary for routingfrom rest_framework import routers # create a router objectrouter = routers.DefaultRouter() # register the routerrouter.register(r'tasks',views.TodoView, 'task') urlpatterns = [ path('admin/', admin.site.urls), # add another path to the url patterns # when you visit the localhost:8000/api # you should be routed to the django Rest framework path('api/', include(router.urls)) ]",
"e": 18205,
"s": 17597,
"text": null
},
{
"code": null,
"e": 18511,
"s": 18205,
"text": "This is the final step for creating the REST API and we can now perform all CRUD operations. Routers allow us to make queries. For example, if we go the “tasks”, this will return the list of all the tasks. Also, you can have a single ‘task’ with an id to return a single task, where id is the primary key."
},
{
"code": null,
"e": 18629,
"s": 18511,
"text": "Now let’s check if we are moving forward in the right direction. So run the server and navigate to the following URL:"
},
{
"code": null,
"e": 18648,
"s": 18629,
"text": "localhost:8000/api"
},
{
"code": null,
"e": 18706,
"s": 18648,
"text": "If everything is good, we will get the following outcome:"
},
{
"code": null,
"e": 18748,
"s": 18706,
"text": "As you can see our API is up and running."
},
{
"code": null,
"e": 18831,
"s": 18748,
"text": "Now if we navigate to the following links we can view and interact with our tasks:"
},
{
"code": null,
"e": 18856,
"s": 18831,
"text": "locaLHOST:8000/api/tasks"
},
{
"code": null,
"e": 18936,
"s": 18856,
"text": "Now let’s build the frontend for our Todo app. For this follow the below steps:"
},
{
"code": null,
"e": 19067,
"s": 18936,
"text": "Step 1: Navigate to the main project directory(ie, Django-react-app) and activate the virtual environment using the below command:"
},
{
"code": null,
"e": 19092,
"s": 19067,
"text": "dar\\Scripts\\activate.bat"
},
{
"code": null,
"e": 19167,
"s": 19092,
"text": "Step 2: Now use the below command to create a boilerplate of React js app:"
},
{
"code": null,
"e": 19197,
"s": 19167,
"text": "npx create-react-app frontend"
},
{
"code": null,
"e": 19310,
"s": 19197,
"text": "Here, npx stands for Node Package Executable. After the boilerplate is setup you will get the following message:"
},
{
"code": null,
"e": 19406,
"s": 19310,
"text": "We will be also needing some UI flair for the UI design, specifically reactstrap and bootstrap."
},
{
"code": null,
"e": 19492,
"s": 19406,
"text": "Step 3: So, use the below command to install reactstrap and bootstrap in the project:"
},
{
"code": null,
"e": 19525,
"s": 19492,
"text": "npm install reactstrap bootstrap"
},
{
"code": null,
"e": 19671,
"s": 19525,
"text": "Step 4: First move into the Frontend folder and use the below command to run the React server to make sure everything if working till this point:"
},
{
"code": null,
"e": 19681,
"s": 19671,
"text": "npm start"
},
{
"code": null,
"e": 19756,
"s": 19681,
"text": "If everything is fine, you’ll get the following page on the localhost:3000"
},
{
"code": null,
"e": 19880,
"s": 19756,
"text": "Step 5: Now open up the App.js file in the frontend folder. And clear the boilerplate code and change it to the below code:"
},
{
"code": null,
"e": 19891,
"s": 19880,
"text": "Javascript"
},
{
"code": "import \"./App.css\"; function App() { return <div className=\"App\"><h2>Welcome to Geeksforgeeks!</h2></div>;} export default App;",
"e": 20020,
"s": 19891,
"text": null
},
{
"code": null,
"e": 20072,
"s": 20023,
"text": "At this point the frontend will look like below:"
},
{
"code": null,
"e": 20181,
"s": 20076,
"text": "As you can see in the above image. Any changes made to the App.js file are reflected directly to the UI."
},
{
"code": null,
"e": 20281,
"s": 20183,
"text": "Step 6: Now the code to the App.js file. Comments are added to the code for better understanding."
},
{
"code": null,
"e": 20294,
"s": 20283,
"text": "Javascript"
},
{
"code": "// import Component from the react moduleimport React, { Component } from \"react\";import Modal from \"./components/Modal\";import axios from 'axios'; // create a class that extends the componentclass App extends Component { // add a constructor to take props constructor(props) { super(props); // add the props here this.state = { // the viewCompleted prop represents the status // of the task. Set it to false by default viewCompleted: false, activeItem: { title: \"\", description: \"\", completed: false }, // this list stores all the completed tasks taskList: [] }; } // Add componentDidMount() componentDidMount() { this.refreshList(); } refreshList = () => { axios //Axios to send and receive HTTP requests .get(\"http://localhost:8000/api/tasks/\") .then(res => this.setState({ taskList: res.data })) .catch(err => console.log(err)); }; // this arrow function takes status as a parameter // and changes the status of viewCompleted to true // if the status is true, else changes it to false displayCompleted = status => { if (status) { return this.setState({ viewCompleted: true }); } return this.setState({ viewCompleted: false }); }; // this array function renders two spans that help control // the set of items to be displayed(ie, completed or incomplete) renderTabList = () => { return ( <div className=\"my-5 tab-list\"> <span onClick={() => this.displayCompleted(true)} className={this.state.viewCompleted ? \"active\" : \"\"} > completed </span> <span onClick={() => this.displayCompleted(false)} className={this.state.viewCompleted ? \"\" : \"active\"} > Incompleted </span> </div> ); }; // Main variable to render items on the screen renderItems = () => { const { viewCompleted } = this.state; const newItems = this.state.taskList.filter( (item) => item.completed === viewCompleted ); return newItems.map((item) => ( <li key={item.id} className=\"list-group-item d-flex justify-content-between align-items-center\" > <span className={`todo-title mr-2 ${ this.state.viewCompleted ? \"completed-todo\" : \"\" }`} title={item.description} > {item.title} </span> <span> <button onClick={() => this.editItem(item)} className=\"btn btn-secondary mr-2\" > Edit </button> <button onClick={() => this.handleDelete(item)} className=\"btn btn-danger\" > Delete </button> </span> </li> )); }; toggle = () => { //add this after modal creation this.setState({ modal: !this.state.modal }); }; handleSubmit = (item) => { this.toggle(); alert(\"save\" + JSON.stringify(item)); }; // Submit an item handleSubmit = (item) => { this.toggle(); if (item.id) { // if old post to edit and submit axios .put(`http://localhost:8000/api/tasks/${item.id}/`, item) .then((res) => this.refreshList()); return; } // if new post to submit axios .post(\"http://localhost:8000/api/tasks/\", item) .then((res) => this.refreshList()); }; // Delete item handleDelete = (item) => { axios .delete(`http://localhost:8000/api/tasks/${item.id}/`) .then((res) => this.refreshList()); }; handleDelete = (item) => { alert(\"delete\" + JSON.stringify(item)); }; // Create item createItem = () => { const item = { title: \"\", description: \"\", completed: false }; this.setState({ activeItem: item, modal: !this.state.modal }); }; //Edit item editItem = (item) => { this.setState({ activeItem: item, modal: !this.state.modal }); }; // Start by visual effects to viewer render() { return ( <main className=\"content\"> <h1 className=\"text-success text-uppercase text-center my-4\"> GFG Task Manager </h1> <div className=\"row \"> <div className=\"col-md-6 col-sm-10 mx-auto p-0\"> <div className=\"card p-3\"> <div className=\"\"> <button onClick={this.createItem} className=\"btn btn-info\"> Add task </button> </div> {this.renderTabList()} <ul className=\"list-group list-group-flush\"> {this.renderItems()} </ul> </div> </div> </div> {this.state.modal ? ( <Modal activeItem={this.state.activeItem} toggle={this.toggle} onSave={this.handleSubmit} /> ) : null} </main> ); }}export default App;",
"e": 25129,
"s": 20294,
"text": null
},
{
"code": null,
"e": 25235,
"s": 25132,
"text": "Step 7: Now open up the Index.css file, clear the CSS inside it and add the following CSS in the file:"
},
{
"code": null,
"e": 25241,
"s": 25237,
"text": "CSS"
},
{
"code": ".todo-title { cursor: pointer;}.completed-todo { text-decoration: line-through;}.tab-list > span { padding: 5px 8px; border: 1px solid rgb(7, 167, 68); border-radius: 10px; margin-right: 5px; cursor: pointer;}.tab-list > span.active { background-color: rgb(6, 139, 12); color: #fff;}",
"e": 25534,
"s": 25241,
"text": null
},
{
"code": null,
"e": 25672,
"s": 25534,
"text": "Step 8: Now create a new folder named “Components” in the src directory and add a file Modal.js to it. Then add the following code to it."
},
{
"code": null,
"e": 25683,
"s": 25672,
"text": "Javascript"
},
{
"code": "import React, { Component } from \"react\"; // importing all of these classes from reactstrap moduleimport { Button, Modal, ModalHeader, ModalBody, ModalFooter, Form, FormGroup, Input, Label} from \"reactstrap\"; // build a class base componentclass CustomModal extends Component { constructor(props) { super(props); this.state = { activeItem: this.props.activeItem }; } // changes handler to check if a checkbox is checed or not handleChange = e => { let { name, value } = e.target; if (e.target.type === \"checkbox\") { value = e.target.checked; } const activeItem = { ...this.state.activeItem, [name]: value }; this.setState({ activeItem }); }; // rendering modal in the custommodal class received toggle and on save as props, render() { const { toggle, onSave } = this.props; return ( <Modal isOpen={true} toggle={toggle}> <ModalHeader toggle={toggle}> Task Item </ModalHeader> <ModalBody> <Form> {/* 3 formgroups 1 title label */} <FormGroup> <Label for=\"title\">Title</Label> <Input type=\"text\" name=\"title\" value={this.state.activeItem.title} onChange={this.handleChange} placeholder=\"Enter Task Title\" /> </FormGroup> {/* 2 description label */} <FormGroup> <Label for=\"description\">Description</Label> <Input type=\"text\" name=\"description\" value={this.state.activeItem.description} onChange={this.handleChange} placeholder=\"Enter Task Description\" /> </FormGroup> {/* 3 completed label */} <FormGroup check> <Label for=\"completed\"> <Input type=\"checkbox\" name=\"completed\" checked={this.state.activeItem.completed} onChange={this.handleChange} /> Completed </Label> </FormGroup> </Form> </ModalBody> {/* create a modal footer */} <ModalFooter> <Button color=\"success\" onClick={() => onSave(this.state.activeItem)}> Save </Button> </ModalFooter> </Modal> ); }}export default CustomModal",
"e": 28119,
"s": 25683,
"text": null
},
{
"code": null,
"e": 28181,
"s": 28122,
"text": "Step 10: Make the changes to the index.js file as follows:"
},
{
"code": null,
"e": 28194,
"s": 28183,
"text": "Javascript"
},
{
"code": "import React from \"react\";import ReactDOM from \"react-dom\";import \"./index.css\";import App from \"./App\"; // importing css stylesheet to use the bootstrap class// add this line only in this fileimport \"bootstrap/dist/css/bootstrap.min.css\"; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById(\"root\"));",
"e": 28539,
"s": 28194,
"text": null
},
{
"code": null,
"e": 28719,
"s": 28539,
"text": "For us to make requests to the API endpoints on the backend server of Django, we will need to install Axios. Use the following command inside the frontend folder to install Axios:"
},
{
"code": null,
"e": 28737,
"s": 28719,
"text": "npm install axios"
},
{
"code": null,
"e": 28745,
"s": 28737,
"text": "Output:"
},
{
"code": null,
"e": 28931,
"s": 28745,
"text": "Congratulation!!. At this point, you have successfully build a Fullstack Django-React app and Used the Django REST framework to establish communication between the frontend and backend."
},
{
"code": null,
"e": 28948,
"s": 28931,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 28965,
"s": 28948,
"text": "punamsingh628700"
},
{
"code": null,
"e": 28978,
"s": 28965,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 28987,
"s": 28978,
"text": "mmslavin"
},
{
"code": null,
"e": 29000,
"s": 28987,
"text": "simmytarika5"
},
{
"code": null,
"e": 29015,
"s": 29000,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 29029,
"s": 29015,
"text": "Python Django"
},
{
"code": null,
"e": 29038,
"s": 29029,
"text": "react-js"
},
{
"code": null,
"e": 29048,
"s": 29038,
"text": "Blogathon"
},
{
"code": null,
"e": 29055,
"s": 29048,
"text": "Python"
},
{
"code": null,
"e": 29063,
"s": 29055,
"text": "ReactJS"
}
] |
GATE CS 2008 - GeeksforGeeks
|
02 Dec, 2021
If P, Q, R are subsets of the universal set U, then
U
Pc U Qc U Rc
P U Qc U Rc
Qc U Rc
The following system of equations
has a unique solution. The only possible value(s) for α is/are
any real number
one of 0, 1 or -1
either 0 or 1
0
any real number other than 5
The choice E was not there in GATE paper. We have added it as the given 4 choices don't seem correct.
Augment the given matrix as
1 1 2 | 1
1 2 3 | 2
1 4 a | 4
Apply R2 <- R2 - R1 and R3 <- R3 - R1
1 1 2 | 1
0 1 1 | 1
0 3 a-2 | 3
Apply R3 <- R3 - 3R2
1 1 2 | 1
0 1 1 | 1
0 0 a-5 | 0
So for the system of equations to have a unique solution,
a - 5 != 0
or
a != 5
or
a = R - {5}
A)
B)
C)
D)
A) m(4, 6)
B) m(4, 8)
C) m(6, 8)
D) m(4, 6, 8)
m(6,8)+m(1,6,15)
m(1,6,8,15)an
I. Whether the intersection of two regular languages is infinite
II. Whether a given context-free language is regular
III. Whether two push-down automata accept the same language
IV. Whether a given grammar is context-free
For Ex :
Grammar is :
S-> aAcBe
A->Ab|b
B->d
Input string : abbcde
Derivation : ( Top-Down, Right Most Derivation)
S->aAcBe
->aAcde
->aAbcde
->abbcde
: abbcde
->aAbcde ( using A-> b )
->aAcde ( using A-> Ab )
->aAcBe ( using B -> d )
->S ( using S-> aAcBe )
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
Spring Boot - Annotations
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
DSA Sheet by Love Babbar
Download Image From URL in Android
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
|
[
{
"code": null,
"e": 29577,
"s": 29549,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 29630,
"s": 29577,
"text": "If P, Q, R are subsets of the universal set U, then "
},
{
"code": null,
"e": 29637,
"s": 29634,
"text": "U "
},
{
"code": null,
"e": 29651,
"s": 29637,
"text": "Pc U Qc U Rc "
},
{
"code": null,
"e": 29664,
"s": 29651,
"text": "P U Qc U Rc "
},
{
"code": null,
"e": 29673,
"s": 29664,
"text": "Qc U Rc "
},
{
"code": null,
"e": 29709,
"s": 29673,
"text": "The following system of equations "
},
{
"code": null,
"e": 29773,
"s": 29709,
"text": "has a unique solution. The only possible value(s) for α is/are "
},
{
"code": null,
"e": 29791,
"s": 29773,
"text": "any real number "
},
{
"code": null,
"e": 29811,
"s": 29791,
"text": "one of 0, 1 or -1 "
},
{
"code": null,
"e": 29826,
"s": 29811,
"text": "either 0 or 1 "
},
{
"code": null,
"e": 29829,
"s": 29826,
"text": "0 "
},
{
"code": null,
"e": 29859,
"s": 29829,
"text": "any real number other than 5 "
},
{
"code": null,
"e": 29963,
"s": 29859,
"text": "The choice E was not there in GATE paper. We have added it as the given 4 choices don't seem correct. "
},
{
"code": null,
"e": 30248,
"s": 29963,
"text": "Augment the given matrix as\n\n1 1 2 | 1\n1 2 3 | 2\n1 4 a | 4\n\nApply R2 <- R2 - R1 and R3 <- R3 - R1\n\n1 1 2 | 1\n0 1 1 | 1\n0 3 a-2 | 3\n\nApply R3 <- R3 - 3R2\n\n1 1 2 | 1\n0 1 1 | 1\n0 0 a-5 | 0\n\nSo for the system of equations to have a unique solution,\n\na - 5 != 0\nor\n\na != 5\nor\na = R - {5} \n"
},
{
"code": null,
"e": 30273,
"s": 30248,
"text": "\n\nA) \n\n\nB) \n\nC) \n\nD) "
},
{
"code": null,
"e": 30323,
"s": 30273,
"text": "A) m(4, 6)\n\nB) m(4, 8)\n\nC) m(6, 8)\n\nD) m(4, 6, 8)"
},
{
"code": null,
"e": 30340,
"s": 30323,
"text": "m(6,8)+m(1,6,15)"
},
{
"code": null,
"e": 30354,
"s": 30340,
"text": "m(1,6,8,15)an"
},
{
"code": null,
"e": 30577,
"s": 30354,
"text": "I. Whether the intersection of two regular languages is infinite\nII. Whether a given context-free language is regular\nIII. Whether two push-down automata accept the same language\nIV. Whether a given grammar is context-free"
},
{
"code": null,
"e": 30736,
"s": 30577,
"text": "\nFor Ex :\n\nGrammar is :\n\nS-> aAcBe\n\nA->Ab|b\n\nB->d\n\nInput string : abbcde\n\nDerivation : ( Top-Down, Right Most Derivation)\n\nS->aAcBe\n->aAcde\n->aAbcde\n->abbcde "
},
{
"code": null,
"e": 30850,
"s": 30736,
"text": "\n: abbcde\n\n->aAbcde ( using A-> b )\n\n->aAcde ( using A-> Ab )\n\n->aAcBe ( using B -> d )\n\n->S ( using S-> aAcBe ) "
},
{
"code": null,
"e": 30948,
"s": 30850,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 31022,
"s": 30948,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 31075,
"s": 31022,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 31101,
"s": 31075,
"text": "Spring Boot - Annotations"
},
{
"code": null,
"e": 31149,
"s": 31101,
"text": "Git - Difference Between Git Fetch and Git Pull"
},
{
"code": null,
"e": 31198,
"s": 31149,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31237,
"s": 31198,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 31262,
"s": 31237,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 31297,
"s": 31262,
"text": "Download Image From URL in Android"
},
{
"code": null,
"e": 31310,
"s": 31297,
"text": "Java Threads"
}
] |
How to make 3D Rotating Image in CSS ?
|
22 Jun, 2021
In this tutorial, we will be showing you how to create a 3D rotating image gallery using simple HTML and CSS-animation property.
Explanation:
In this article, we have used mainly CSS variable, CSS flex, object-fit, transform-style, animation, transform and keyframes properties to perform this task. To read more about CSS keyframes properties please refer to https://www.geeksforgeeks.org/css-animations/ article.
HTML: Creating structure
html
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="app.css"> </head> <body> <div class="box"> <!-- adding CSS variable --i --> <span style="--i:1;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131445/img1-300x214.jpg"> </span> <!-- adding CSS variable --i --> <span style="--i:2;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131451/img2-300x150.jpeg"> </span> <!-- adding CSS variable --i --> <span style="--i:4;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131448/img3-200x200.jpg"> </span> <!-- adding CSS variable --i --> <span style="--i:5;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img4-300x167.png"> </span> <!-- adding CSS variable --i --> <span style="--i:6;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131449/img5-200x113.jpeg"> </span> <!-- adding CSS variable --i --> <span style="--i:7;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131450/img6-300x82.png" > </span> <!-- adding CSS variable --i --> <span style="--i:8;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131446/img7-200x200.jpeg"> </span> <!-- adding CSS variable --i --> <span style="--i:9;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img8-200x133.jpeg"> </span> <!-- adding CSS variable --i --> <span style="--i:3;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131447/img9-200x200.jpeg"> </span> </div> </body> </html>
CSS:
css
/* Applying Global CSS */* { margin: 0; padding: 0; box-sizing: border-box;} /* Centering the content of whole body */body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #000;} /* Adding transform-style CSS property to the boxes */.box { position: relative; width: 200px; height: 200px; transform-style: preserve-3d; animation: animate 20s linear infinite;} /* Adding keyframes for animation */@keyframes animate { 0% { transform: perspective(1000px) rotateY(0deg); } 100% { transform: perspective(1000px) rotateY(360deg); }} /* Adding CSS to all the span tags for animation */.box span { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform-origin: center; transform-style: preserve-3d; transform: rotateY(calc(var(--i) * 45deg)) translateZ(400px); -webkit-box-reflect:below 0px linear-gradient(transparent, transparent, #0004);} /* Adding object-fit CSS property to all the images */.box span img { position: absolute; top: 0; left: 0; height: 250px; width: 300px; object-fit: cover;}
Final Solution:
css
<!DOCTYPE html><html> <head> <style> /* Applying Global CSS */ * { margin: 0; padding: 0; box-sizing: border-box; } /* Centering the content of whole body */ body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #000; } /* Adding transform-style CSS property to the boxes */ .box { position: relative; width: 200px; height: 200px; transform-style: preserve-3d; animation: animate 20s linear infinite; } /* Adding keyframes for animation */ @keyframes animate { 0% { transform: perspective(1000px) rotateY(0deg); } 100% { transform: perspective(1000px) rotateY(360deg); } } /* Adding CSS to all the span tags for animation */ .box span { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform-origin: center; transform-style: preserve-3d; transform: rotateY(calc(var(--i) * 45deg)) translateZ(400px); -webkit-box-reflect: below 0px linear-gradient(transparent, transparent, #0004); } /* Adding object-fit CSS property to all the images */ .box span img { position: absolute; top: 0; left: 0; height: 250px; width: 300px; object-fit: cover; } </style> </head> <body> <div class="box"> <!-- Adding CSS variable --i --> <span style="--i: 1;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131445/img1-300x214.jpg" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 2;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131451/img2-300x150.jpeg" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 4;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131448/img3-200x200.jpg" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 5;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img4-300x167.png" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 6;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131449/img5-200x113.jpeg" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 7;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131450/img6-300x82.png" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 8;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131446/img7-200x200.jpeg" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 9;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img8-200x133.jpeg" /> </span> <!-- Adding CSS variable --i --> <span style="--i: 3;"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131447/img9-200x200.jpeg" /> </span> </div> </body></html>
Output:
rajeev0719singh
CSS-Advanced
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
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 ?
Design a Tribute Page using HTML & CSS
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 157,
"s": 28,
"text": "In this tutorial, we will be showing you how to create a 3D rotating image gallery using simple HTML and CSS-animation property."
},
{
"code": null,
"e": 170,
"s": 157,
"text": "Explanation:"
},
{
"code": null,
"e": 443,
"s": 170,
"text": "In this article, we have used mainly CSS variable, CSS flex, object-fit, transform-style, animation, transform and keyframes properties to perform this task. To read more about CSS keyframes properties please refer to https://www.geeksforgeeks.org/css-animations/ article."
},
{
"code": null,
"e": 470,
"s": 445,
"text": "HTML: Creating structure"
},
{
"code": null,
"e": 477,
"s": 472,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"app.css\"> </head> <body> <div class=\"box\"> <!-- adding CSS variable --i --> <span style=\"--i:1;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131445/img1-300x214.jpg\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:2;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131451/img2-300x150.jpeg\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:4;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131448/img3-200x200.jpg\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:5;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img4-300x167.png\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:6;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131449/img5-200x113.jpeg\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:7;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131450/img6-300x82.png\" > </span> <!-- adding CSS variable --i --> <span style=\"--i:8;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131446/img7-200x200.jpeg\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:9;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img8-200x133.jpeg\"> </span> <!-- adding CSS variable --i --> <span style=\"--i:3;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131447/img9-200x200.jpeg\"> </span> </div> </body> </html>",
"e": 2529,
"s": 477,
"text": null
},
{
"code": null,
"e": 2536,
"s": 2529,
"text": "CSS: "
},
{
"code": null,
"e": 2540,
"s": 2536,
"text": "css"
},
{
"code": "/* Applying Global CSS */* { margin: 0; padding: 0; box-sizing: border-box;} /* Centering the content of whole body */body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #000;} /* Adding transform-style CSS property to the boxes */.box { position: relative; width: 200px; height: 200px; transform-style: preserve-3d; animation: animate 20s linear infinite;} /* Adding keyframes for animation */@keyframes animate { 0% { transform: perspective(1000px) rotateY(0deg); } 100% { transform: perspective(1000px) rotateY(360deg); }} /* Adding CSS to all the span tags for animation */.box span { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform-origin: center; transform-style: preserve-3d; transform: rotateY(calc(var(--i) * 45deg)) translateZ(400px); -webkit-box-reflect:below 0px linear-gradient(transparent, transparent, #0004);} /* Adding object-fit CSS property to all the images */.box span img { position: absolute; top: 0; left: 0; height: 250px; width: 300px; object-fit: cover;}",
"e": 3716,
"s": 2540,
"text": null
},
{
"code": null,
"e": 3734,
"s": 3716,
"text": "Final Solution: "
},
{
"code": null,
"e": 3738,
"s": 3734,
"text": "css"
},
{
"code": "<!DOCTYPE html><html> <head> <style> /* Applying Global CSS */ * { margin: 0; padding: 0; box-sizing: border-box; } /* Centering the content of whole body */ body { display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #000; } /* Adding transform-style CSS property to the boxes */ .box { position: relative; width: 200px; height: 200px; transform-style: preserve-3d; animation: animate 20s linear infinite; } /* Adding keyframes for animation */ @keyframes animate { 0% { transform: perspective(1000px) rotateY(0deg); } 100% { transform: perspective(1000px) rotateY(360deg); } } /* Adding CSS to all the span tags for animation */ .box span { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transform-origin: center; transform-style: preserve-3d; transform: rotateY(calc(var(--i) * 45deg)) translateZ(400px); -webkit-box-reflect: below 0px linear-gradient(transparent, transparent, #0004); } /* Adding object-fit CSS property to all the images */ .box span img { position: absolute; top: 0; left: 0; height: 250px; width: 300px; object-fit: cover; } </style> </head> <body> <div class=\"box\"> <!-- Adding CSS variable --i --> <span style=\"--i: 1;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131445/img1-300x214.jpg\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 2;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131451/img2-300x150.jpeg\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 4;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131448/img3-200x200.jpg\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 5;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img4-300x167.png\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 6;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131449/img5-200x113.jpeg\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 7;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131450/img6-300x82.png\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 8;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131446/img7-200x200.jpeg\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 9;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img8-200x133.jpeg\" /> </span> <!-- Adding CSS variable --i --> <span style=\"--i: 3;\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200723131447/img9-200x200.jpeg\" /> </span> </div> </body></html>",
"e": 7610,
"s": 3738,
"text": null
},
{
"code": null,
"e": 7620,
"s": 7610,
"text": "Output: "
},
{
"code": null,
"e": 7638,
"s": 7622,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 7651,
"s": 7638,
"text": "CSS-Advanced"
},
{
"code": null,
"e": 7660,
"s": 7651,
"text": "CSS-Misc"
},
{
"code": null,
"e": 7670,
"s": 7660,
"text": "HTML-Misc"
},
{
"code": null,
"e": 7674,
"s": 7670,
"text": "CSS"
},
{
"code": null,
"e": 7679,
"s": 7674,
"text": "HTML"
},
{
"code": null,
"e": 7696,
"s": 7679,
"text": "Web Technologies"
},
{
"code": null,
"e": 7701,
"s": 7696,
"text": "HTML"
},
{
"code": null,
"e": 7799,
"s": 7701,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7838,
"s": 7799,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 7877,
"s": 7838,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 7916,
"s": 7877,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 7945,
"s": 7916,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 7982,
"s": 7945,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 8006,
"s": 7982,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 8059,
"s": 8006,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 8119,
"s": 8059,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 8180,
"s": 8119,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Mutation Testing in Java (Using Jumble)
|
08 May, 2017
Mutation testing is a white-box testing technique, which changes certain portions of the code to reveal possible faults. On a very high level, it is the process of rewriting the source code with some known or possible bugs or differences to the actual code in small ways in order to remove the redundancies in the source code. The goal of mutation testing is to evaluate the coverage of your tests. There are many mutation testing tool for Java.
JumblePITμJavaJester
Jumble
PIT
μJava
Jester
This post deals with Jumble Mutation testing Tool in Java. Jumble is a mutation testing tool which changes the Java code at byte code level. It runs a unit test case and applies certain set of mutations.
Passed Mutations: Changes in code which do not affect the final output
Failed Mutations: Changes in code which change the final output
Score : It is the percentage of passed mutations out of the total mutations. It is used to assess the validity of our test suite.InstallationDownload Eclipse IDE and install Jumble to Eclipse.
Simple Code Snippet in Java
int index = 0;
while(true)
{
index++;
if (index == 10)
break;
}
Mutated Code in JAVA
int index = 0;
while (true)
{
index++;
if (index >= 10)
break;
}
Explanation: The mutant code above will pass the Jumble test because change in == to >= does not affect the output of the code. Execution will stop when index == 10 and since we are increasing value by 1 and index starts from 0 so the output will remain same.
Example with JumbleThe code written below has been tested with Jumble plugin in Eclipse. The code detects the first occurrence of a duplicate and returns the value to the calling function. The program is flawed in many ways which you can try figuring out.
// Java program to illustrate mutation Testing// The code detects the first occurrence of a // duplicate and returns the value to the calling// functionpackage testPackage; import java.util.Arrays;import java.util.List;public class SampProg{ protected int repeatedNumber(final List a) { int len = a.size(),i,dup = -1; int[] arr = new int[len]; for (i=0; i<len; i++) { arr[i] = a.get(i); } Arrays.sort(arr); try { for (i=1; i<len; i++) { if(arr[i] == arr[i-1]) { dup = arr[i]; break; } } } catch(Exception e) { System.out.println(e.getMessage()); } return dup; }}
After writing the program we create test cases using JUnit in Java. The output obtained on performing Jumble Analysis is given below:
Mutating testPackage.SampProg
Tests: testPackage.SampProgTest
Mutation points = 11, unit test time limit 2.94s
M FAIL: (testPackage.SampProg.java:8): -1 -> 1
M FAIL: (testPackage.SampProg.java:10): 0 -> 1
.M FAIL: (testPackage.SampProg.java:10): negated conditional
M FAIL: (testPackage.SampProg.java:16): 1 -> 0
M FAIL: (testPackage.SampProg.java:18): 1 -> 0
M FAIL: (testPackage.SampProg.java:18): - -> +
M FAIL: (testPackage.SampProg.java:18): negated conditional
M FAIL: (testPackage.SampProg.java:16): += -> -=
M FAIL: (testPackage.SampProg.java:16): negated conditional
.
Jumbling took 7.595s
Score: 18%
Interpreting the Result
In the first line of M FAIL in the output -1 was changed to 1. In the main program, if there are no duplicates we expect the value to be returned as -1. but instead we get the value 1. We can fix the mutation by enabling checks for value mutation.Next, we can see “negated conditional” on the 3rd, 7th and 9th line where condition has been negated. Here however we can’t fix the error for this program.Other cases where the mutation failed to give proper output is when operators are changed to other operators. In this and many algorithmic codes, mutations related to operator changes cannot be fixed. However mutation testing gives brief idea in some mutations as to where the test case is weak or there is an error in the source code. This link gives mutations performed by jumble
In the first line of M FAIL in the output -1 was changed to 1. In the main program, if there are no duplicates we expect the value to be returned as -1. but instead we get the value 1. We can fix the mutation by enabling checks for value mutation.
Next, we can see “negated conditional” on the 3rd, 7th and 9th line where condition has been negated. Here however we can’t fix the error for this program.
Other cases where the mutation failed to give proper output is when operators are changed to other operators. In this and many algorithmic codes, mutations related to operator changes cannot be fixed. However mutation testing gives brief idea in some mutations as to where the test case is weak or there is an error in the source code. This link gives mutations performed by jumble
This article is contributed by Ipsit. 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
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": "\n08 May, 2017"
},
{
"code": null,
"e": 474,
"s": 28,
"text": "Mutation testing is a white-box testing technique, which changes certain portions of the code to reveal possible faults. On a very high level, it is the process of rewriting the source code with some known or possible bugs or differences to the actual code in small ways in order to remove the redundancies in the source code. The goal of mutation testing is to evaluate the coverage of your tests. There are many mutation testing tool for Java."
},
{
"code": null,
"e": 495,
"s": 474,
"text": "JumblePITμJavaJester"
},
{
"code": null,
"e": 502,
"s": 495,
"text": "Jumble"
},
{
"code": null,
"e": 506,
"s": 502,
"text": "PIT"
},
{
"code": null,
"e": 512,
"s": 506,
"text": "μJava"
},
{
"code": null,
"e": 519,
"s": 512,
"text": "Jester"
},
{
"code": null,
"e": 723,
"s": 519,
"text": "This post deals with Jumble Mutation testing Tool in Java. Jumble is a mutation testing tool which changes the Java code at byte code level. It runs a unit test case and applies certain set of mutations."
},
{
"code": null,
"e": 794,
"s": 723,
"text": "Passed Mutations: Changes in code which do not affect the final output"
},
{
"code": null,
"e": 858,
"s": 794,
"text": "Failed Mutations: Changes in code which change the final output"
},
{
"code": null,
"e": 1051,
"s": 858,
"text": "Score : It is the percentage of passed mutations out of the total mutations. It is used to assess the validity of our test suite.InstallationDownload Eclipse IDE and install Jumble to Eclipse."
},
{
"code": null,
"e": 1079,
"s": 1051,
"text": "Simple Code Snippet in Java"
},
{
"code": null,
"e": 1159,
"s": 1079,
"text": "int index = 0;\nwhile(true)\n{\n index++;\n if (index == 10) \n break;\n}\n"
},
{
"code": null,
"e": 1180,
"s": 1159,
"text": "Mutated Code in JAVA"
},
{
"code": null,
"e": 1261,
"s": 1180,
"text": "int index = 0;\nwhile (true)\n{\n index++;\n if (index >= 10) \n break;\n}\n"
},
{
"code": null,
"e": 1521,
"s": 1261,
"text": "Explanation: The mutant code above will pass the Jumble test because change in == to >= does not affect the output of the code. Execution will stop when index == 10 and since we are increasing value by 1 and index starts from 0 so the output will remain same."
},
{
"code": null,
"e": 1777,
"s": 1521,
"text": "Example with JumbleThe code written below has been tested with Jumble plugin in Eclipse. The code detects the first occurrence of a duplicate and returns the value to the calling function. The program is flawed in many ways which you can try figuring out."
},
{
"code": "// Java program to illustrate mutation Testing// The code detects the first occurrence of a // duplicate and returns the value to the calling// functionpackage testPackage; import java.util.Arrays;import java.util.List;public class SampProg{ protected int repeatedNumber(final List a) { int len = a.size(),i,dup = -1; int[] arr = new int[len]; for (i=0; i<len; i++) { arr[i] = a.get(i); } Arrays.sort(arr); try { for (i=1; i<len; i++) { if(arr[i] == arr[i-1]) { dup = arr[i]; break; } } } catch(Exception e) { System.out.println(e.getMessage()); } return dup; }}",
"e": 2581,
"s": 1777,
"text": null
},
{
"code": null,
"e": 2715,
"s": 2581,
"text": "After writing the program we create test cases using JUnit in Java. The output obtained on performing Jumble Analysis is given below:"
},
{
"code": null,
"e": 3325,
"s": 2715,
"text": "Mutating testPackage.SampProg\nTests: testPackage.SampProgTest\nMutation points = 11, unit test time limit 2.94s\nM FAIL: (testPackage.SampProg.java:8): -1 -> 1\nM FAIL: (testPackage.SampProg.java:10): 0 -> 1\n.M FAIL: (testPackage.SampProg.java:10): negated conditional\nM FAIL: (testPackage.SampProg.java:16): 1 -> 0\nM FAIL: (testPackage.SampProg.java:18): 1 -> 0\nM FAIL: (testPackage.SampProg.java:18): - -> +\nM FAIL: (testPackage.SampProg.java:18): negated conditional\nM FAIL: (testPackage.SampProg.java:16): += -> -=\nM FAIL: (testPackage.SampProg.java:16): negated conditional\n.\nJumbling took 7.595s\nScore: 18%"
},
{
"code": null,
"e": 3349,
"s": 3325,
"text": "Interpreting the Result"
},
{
"code": null,
"e": 4133,
"s": 3349,
"text": "In the first line of M FAIL in the output -1 was changed to 1. In the main program, if there are no duplicates we expect the value to be returned as -1. but instead we get the value 1. We can fix the mutation by enabling checks for value mutation.Next, we can see “negated conditional” on the 3rd, 7th and 9th line where condition has been negated. Here however we can’t fix the error for this program.Other cases where the mutation failed to give proper output is when operators are changed to other operators. In this and many algorithmic codes, mutations related to operator changes cannot be fixed. However mutation testing gives brief idea in some mutations as to where the test case is weak or there is an error in the source code. This link gives mutations performed by jumble"
},
{
"code": null,
"e": 4381,
"s": 4133,
"text": "In the first line of M FAIL in the output -1 was changed to 1. In the main program, if there are no duplicates we expect the value to be returned as -1. but instead we get the value 1. We can fix the mutation by enabling checks for value mutation."
},
{
"code": null,
"e": 4537,
"s": 4381,
"text": "Next, we can see “negated conditional” on the 3rd, 7th and 9th line where condition has been negated. Here however we can’t fix the error for this program."
},
{
"code": null,
"e": 4919,
"s": 4537,
"text": "Other cases where the mutation failed to give proper output is when operators are changed to other operators. In this and many algorithmic codes, mutations related to operator changes cannot be fixed. However mutation testing gives brief idea in some mutations as to where the test case is weak or there is an error in the source code. This link gives mutations performed by jumble"
},
{
"code": null,
"e": 5212,
"s": 4919,
"text": "This article is contributed by Ipsit. 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": 5337,
"s": 5212,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5342,
"s": 5337,
"text": "Java"
},
{
"code": null,
"e": 5347,
"s": 5342,
"text": "Java"
},
{
"code": null,
"e": 5445,
"s": 5347,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5460,
"s": 5445,
"text": "Stream In Java"
},
{
"code": null,
"e": 5481,
"s": 5460,
"text": "Introduction to Java"
},
{
"code": null,
"e": 5502,
"s": 5481,
"text": "Constructors in Java"
},
{
"code": null,
"e": 5521,
"s": 5502,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 5538,
"s": 5521,
"text": "Generics in Java"
},
{
"code": null,
"e": 5568,
"s": 5538,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 5594,
"s": 5568,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5610,
"s": 5594,
"text": "Strings in Java"
},
{
"code": null,
"e": 5647,
"s": 5610,
"text": "Differences between JDK, JRE and JVM"
}
] |
Packet Switching and Delays in Computer Network
|
18 Oct, 2021
Packet switching is a method of transferring the data to a network in form of packets. In order to transfer the file fast and efficiently manner over the network and minimize the transmission latency, the data is broken into small pieces of variable length, called Packet. At the destination, all these small parts (packets) have to be reassembled, belonging to the same file. A packet composes of payload and various control information. No pre-setup or reservation of resources is needed.
Packet Switching uses Store and Forward technique while switching the packets; while forwarding the packet each hop first stores that packet then forward. This technique is very beneficial because packets may get discarded at any hop due to some reason. More than one path is possible between a pair of sources and destinations. Each packet contains Source and destination address using which they independently travel through the network. In other words, packets belonging to the same file may or may not travel through the same path. If there is congestion at some path, packets are allowed to choose different paths possible over an existing network.
Packet-Switched networks were designed to overcome the weaknesses of Circuit-Switched networks since circuit-switched networks were not very effective for small messages.
Advantage of Packet Switching over Circuit Switching :
More efficient in terms of bandwidth, since the concept of reserving circuit is not there.
Minimal transmission latency.
More reliable as a destination can detect the missing packet.
More fault tolerant because packets may follow a different path in case any link is down, Unlike Circuit Switching.
Cost-effective and comparatively cheaper to implement.
The disadvantage of Packet Switching over Circuit Switching :
Packet Switching doesn’t give packets in order, whereas Circuit Switching provides ordered delivery of packets because all the packets follow the same path.
Since the packets are unordered, we need to provide sequence numbers for each packet.
Complexity is more at each node because of the facility to follow multiple paths.
Transmission delay is more because of rerouting.
Packet Switching is beneficial only for small messages, but for bursty data (large messages) Circuit Switching is better.
Modes of Packet Switching :
1. Connection-oriented Packet Switching (Virtual Circuit) : Before starting the transmission, it establishes a logical path or virtual connection using signaling protocol, between sender and receiver and all packets belongs to this flow will follow this predefined route. Virtual Circuit ID is provided by switches/routers to uniquely identify this virtual connection. Data is divided into small units and all these small units are appended with help of sequence numbers. Overall, three phases take place here- The setup, data transfer and tear down phase.
All address information is only transferred during the setup phase. Once the route to a destination is discovered, entry is added to the switching table of each intermediate node. During data transfer, packet header (local header) may contain information such as length, timestamp, sequence number, etc. Connection-oriented switching is very useful in switched WAN. Some popular protocols which use the Virtual Circuit Switching approach are X.25, Frame-Relay, ATM, and MPLS(Multi-Protocol Label Switching).
2. Connectionless Packet Switching (Datagram) :Unlike Connection-oriented packet switching, In Connectionless Packet Switching each packet contains all necessary addressing information such as source address, destination address and port numbers, etc. In Datagram Packet Switching, each packet is treated independently. Packets belonging to one flow may take different routes because routing decisions are made dynamically, so the packets arrived at the destination might be out of order. It has no connection setup and teardown phase, like Virtual Circuits. Packet delivery is not guaranteed in connectionless packet switching, so reliable delivery must be provided by end systems using additional protocols.
A---R1---R2---B
A is the sender (start)
R1, R2 are two routers that store and forward data
B is receiver(destination)
To send a packet from A to B there are delays since this is a Store and Forward network.
Transmission DelayPropagation DelayQueuing DelayProcessing Delay
Transmission Delay
Propagation Delay
Queuing Delay
Processing Delay
al_architjain
preetgandhi
23603vaibhav2021
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 546,
"s": 54,
"text": "Packet switching is a method of transferring the data to a network in form of packets. In order to transfer the file fast and efficiently manner over the network and minimize the transmission latency, the data is broken into small pieces of variable length, called Packet. At the destination, all these small parts (packets) have to be reassembled, belonging to the same file. A packet composes of payload and various control information. No pre-setup or reservation of resources is needed. "
},
{
"code": null,
"e": 1201,
"s": 546,
"text": "Packet Switching uses Store and Forward technique while switching the packets; while forwarding the packet each hop first stores that packet then forward. This technique is very beneficial because packets may get discarded at any hop due to some reason. More than one path is possible between a pair of sources and destinations. Each packet contains Source and destination address using which they independently travel through the network. In other words, packets belonging to the same file may or may not travel through the same path. If there is congestion at some path, packets are allowed to choose different paths possible over an existing network. "
},
{
"code": null,
"e": 1373,
"s": 1201,
"text": "Packet-Switched networks were designed to overcome the weaknesses of Circuit-Switched networks since circuit-switched networks were not very effective for small messages. "
},
{
"code": null,
"e": 1430,
"s": 1373,
"text": "Advantage of Packet Switching over Circuit Switching : "
},
{
"code": null,
"e": 1521,
"s": 1430,
"text": "More efficient in terms of bandwidth, since the concept of reserving circuit is not there."
},
{
"code": null,
"e": 1551,
"s": 1521,
"text": "Minimal transmission latency."
},
{
"code": null,
"e": 1613,
"s": 1551,
"text": "More reliable as a destination can detect the missing packet."
},
{
"code": null,
"e": 1729,
"s": 1613,
"text": "More fault tolerant because packets may follow a different path in case any link is down, Unlike Circuit Switching."
},
{
"code": null,
"e": 1784,
"s": 1729,
"text": "Cost-effective and comparatively cheaper to implement."
},
{
"code": null,
"e": 1848,
"s": 1784,
"text": "The disadvantage of Packet Switching over Circuit Switching : "
},
{
"code": null,
"e": 2005,
"s": 1848,
"text": "Packet Switching doesn’t give packets in order, whereas Circuit Switching provides ordered delivery of packets because all the packets follow the same path."
},
{
"code": null,
"e": 2091,
"s": 2005,
"text": "Since the packets are unordered, we need to provide sequence numbers for each packet."
},
{
"code": null,
"e": 2173,
"s": 2091,
"text": "Complexity is more at each node because of the facility to follow multiple paths."
},
{
"code": null,
"e": 2222,
"s": 2173,
"text": "Transmission delay is more because of rerouting."
},
{
"code": null,
"e": 2344,
"s": 2222,
"text": "Packet Switching is beneficial only for small messages, but for bursty data (large messages) Circuit Switching is better."
},
{
"code": null,
"e": 2374,
"s": 2344,
"text": "Modes of Packet Switching : "
},
{
"code": null,
"e": 2933,
"s": 2374,
"text": "1. Connection-oriented Packet Switching (Virtual Circuit) : Before starting the transmission, it establishes a logical path or virtual connection using signaling protocol, between sender and receiver and all packets belongs to this flow will follow this predefined route. Virtual Circuit ID is provided by switches/routers to uniquely identify this virtual connection. Data is divided into small units and all these small units are appended with help of sequence numbers. Overall, three phases take place here- The setup, data transfer and tear down phase. "
},
{
"code": null,
"e": 3441,
"s": 2933,
"text": "All address information is only transferred during the setup phase. Once the route to a destination is discovered, entry is added to the switching table of each intermediate node. During data transfer, packet header (local header) may contain information such as length, timestamp, sequence number, etc. Connection-oriented switching is very useful in switched WAN. Some popular protocols which use the Virtual Circuit Switching approach are X.25, Frame-Relay, ATM, and MPLS(Multi-Protocol Label Switching)."
},
{
"code": null,
"e": 4153,
"s": 3441,
"text": "2. Connectionless Packet Switching (Datagram) :Unlike Connection-oriented packet switching, In Connectionless Packet Switching each packet contains all necessary addressing information such as source address, destination address and port numbers, etc. In Datagram Packet Switching, each packet is treated independently. Packets belonging to one flow may take different routes because routing decisions are made dynamically, so the packets arrived at the destination might be out of order. It has no connection setup and teardown phase, like Virtual Circuits. Packet delivery is not guaranteed in connectionless packet switching, so reliable delivery must be provided by end systems using additional protocols. "
},
{
"code": null,
"e": 4274,
"s": 4155,
"text": "A---R1---R2---B\n\nA is the sender (start)\nR1, R2 are two routers that store and forward data\nB is receiver(destination)"
},
{
"code": null,
"e": 4364,
"s": 4274,
"text": "To send a packet from A to B there are delays since this is a Store and Forward network. "
},
{
"code": null,
"e": 4429,
"s": 4364,
"text": "Transmission DelayPropagation DelayQueuing DelayProcessing Delay"
},
{
"code": null,
"e": 4448,
"s": 4429,
"text": "Transmission Delay"
},
{
"code": null,
"e": 4466,
"s": 4448,
"text": "Propagation Delay"
},
{
"code": null,
"e": 4480,
"s": 4466,
"text": "Queuing Delay"
},
{
"code": null,
"e": 4497,
"s": 4480,
"text": "Processing Delay"
},
{
"code": null,
"e": 4511,
"s": 4497,
"text": "al_architjain"
},
{
"code": null,
"e": 4523,
"s": 4511,
"text": "preetgandhi"
},
{
"code": null,
"e": 4540,
"s": 4523,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 4558,
"s": 4540,
"text": "Computer Networks"
},
{
"code": null,
"e": 4566,
"s": 4558,
"text": "GATE CS"
},
{
"code": null,
"e": 4584,
"s": 4566,
"text": "Computer Networks"
}
] |
Python append to a file
|
05 Jul, 2022
Prerequisites:
Basics of file handling
Access modes
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. The file handle is like a cursor, which defines from where the data has to be read or written in the file. In order to append a new line to the existing file, open the file in append mode, by using either ‘a’ or ‘a+’ as the access mode. The definition of these access modes is as follows:
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write mode and append mode.
Python3
file1 = open("myfile.txt", "w")L = ["This is Delhi \n", "This is Paris \n", "This is London"]file1.writelines(L)file1.close() # Append-adds at lastfile1 = open("myfile.txt", "a") # append modefile1.write("Today \n")file1.close() file1 = open("myfile.txt", "r")print("Output of Readlines after appending")print(file1.read())print()file1.close() # Write-Overwritesfile1 = open("myfile.txt", "w") # write modefile1.write("Tomorrow \n")file1.close() file1 = open("myfile.txt", "r")print("Output of Readlines after writing")print(file1.read())print()file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is LondonToday
Output of Readlines after writing
Tomorrow
In the above example, it can be seen that the data is not appended from the new line. This can be done by writing the newline ‘\n’ character to the file.
Note: ‘\n’ is treated as a special character of two bytes.
Python3
# Python program to illustrate# append from new line file1 = open("myfile.txt", "w")L = ["This is Delhi \n", "This is Paris \n", "This is London"]file1.writelines(L)file1.close() # Append-adds at last# append modefile1 = open("myfile.txt", "a") # writing newline characterfile1.write("\n")file1.write("Today") # without newline characterfile1.write("Tomorrow") file1 = open("myfile.txt", "r")print("Output of Readlines after appending")print(file1.read())print()file1.close()
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow
with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.
Python3
# Program to show various ways to# append data to a file using# with statement L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] # Writing to filewith open("myfile.txt", "w") as file1: # Writing data to a file file1.write("Hello \n") file1.writelines(L) # Appending to filewith open("myfile.txt", 'a') as file1: file1.write("Today") # Reading from filewith open("myfile.txt", "r+") as file1: # Reading form a file print(file1.read())
Output:
Hello
This is Delhi
This is Paris
This is London
Today
Note: To know more about with statement click here.
surajkumarguptaintern
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n05 Jul, 2022"
},
{
"code": null,
"e": 68,
"s": 52,
"text": "Prerequisites: "
},
{
"code": null,
"e": 92,
"s": 68,
"text": "Basics of file handling"
},
{
"code": null,
"e": 105,
"s": 92,
"text": "Access modes"
},
{
"code": null,
"e": 628,
"s": 105,
"text": "While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. The file handle is like a cursor, which defines from where the data has to be read or written in the file. In order to append a new line to the existing file, open the file in append mode, by using either ‘a’ or ‘a+’ as the access mode. The definition of these access modes is as follows:"
},
{
"code": null,
"e": 842,
"s": 628,
"text": "Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data."
},
{
"code": null,
"e": 1073,
"s": 842,
"text": "Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data."
},
{
"code": null,
"e": 1329,
"s": 1073,
"text": "When the file is opened in append mode, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. Let’s see the below example to clarify the difference between write mode and append mode."
},
{
"code": null,
"e": 1337,
"s": 1329,
"text": "Python3"
},
{
"code": "file1 = open(\"myfile.txt\", \"w\")L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London\"]file1.writelines(L)file1.close() # Append-adds at lastfile1 = open(\"myfile.txt\", \"a\") # append modefile1.write(\"Today \\n\")file1.close() file1 = open(\"myfile.txt\", \"r\")print(\"Output of Readlines after appending\")print(file1.read())print()file1.close() # Write-Overwritesfile1 = open(\"myfile.txt\", \"w\") # write modefile1.write(\"Tomorrow \\n\")file1.close() file1 = open(\"myfile.txt\", \"r\")print(\"Output of Readlines after writing\")print(file1.read())print()file1.close()",
"e": 1898,
"s": 1337,
"text": null
},
{
"code": null,
"e": 1906,
"s": 1898,
"text": "Output:"
},
{
"code": null,
"e": 2035,
"s": 1906,
"text": "Output of Readlines after appending\nThis is Delhi\nThis is Paris\nThis is LondonToday\n\n\nOutput of Readlines after writing\nTomorrow"
},
{
"code": null,
"e": 2190,
"s": 2035,
"text": "In the above example, it can be seen that the data is not appended from the new line. This can be done by writing the newline ‘\\n’ character to the file. "
},
{
"code": null,
"e": 2250,
"s": 2190,
"text": "Note: ‘\\n’ is treated as a special character of two bytes. "
},
{
"code": null,
"e": 2258,
"s": 2250,
"text": "Python3"
},
{
"code": "# Python program to illustrate# append from new line file1 = open(\"myfile.txt\", \"w\")L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London\"]file1.writelines(L)file1.close() # Append-adds at last# append modefile1 = open(\"myfile.txt\", \"a\") # writing newline characterfile1.write(\"\\n\")file1.write(\"Today\") # without newline characterfile1.write(\"Tomorrow\") file1 = open(\"myfile.txt\", \"r\")print(\"Output of Readlines after appending\")print(file1.read())print()file1.close()",
"e": 2735,
"s": 2258,
"text": null
},
{
"code": null,
"e": 2743,
"s": 2735,
"text": "Output:"
},
{
"code": null,
"e": 2836,
"s": 2743,
"text": "Output of Readlines after appending\nThis is Delhi\nThis is Paris\nThis is London\nTodayTomorrow"
},
{
"code": null,
"e": 3177,
"s": 2836,
"text": "with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources. "
},
{
"code": null,
"e": 3185,
"s": 3177,
"text": "Python3"
},
{
"code": "# Program to show various ways to# append data to a file using# with statement L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"] # Writing to filewith open(\"myfile.txt\", \"w\") as file1: # Writing data to a file file1.write(\"Hello \\n\") file1.writelines(L) # Appending to filewith open(\"myfile.txt\", 'a') as file1: file1.write(\"Today\") # Reading from filewith open(\"myfile.txt\", \"r+\") as file1: # Reading form a file print(file1.read())",
"e": 3654,
"s": 3185,
"text": null
},
{
"code": null,
"e": 3662,
"s": 3654,
"text": "Output:"
},
{
"code": null,
"e": 3717,
"s": 3662,
"text": "Hello\nThis is Delhi\nThis is Paris\nThis is London\nToday"
},
{
"code": null,
"e": 3769,
"s": 3717,
"text": "Note: To know more about with statement click here."
},
{
"code": null,
"e": 3791,
"s": 3769,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 3812,
"s": 3791,
"text": "python-file-handling"
},
{
"code": null,
"e": 3819,
"s": 3812,
"text": "Python"
},
{
"code": null,
"e": 3917,
"s": 3819,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3945,
"s": 3917,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3995,
"s": 3945,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4017,
"s": 3995,
"text": "Python map() function"
},
{
"code": null,
"e": 4061,
"s": 4017,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 4103,
"s": 4061,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4125,
"s": 4103,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4160,
"s": 4125,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4186,
"s": 4160,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4218,
"s": 4186,
"text": "How to Install PIP on Windows ?"
}
] |
How to write comments in ReactJS ?
|
19 Sep, 2021
ReactJS is a JavaScript library used for building user interfaces. It is Declarative, Component-based and Technology stack agnostic. It has been designed for speed, simplicity, and scalability. These features make it one of the most popular libraries among web developers.
In this article, we will explore creating a React application and adding comments to it.
Step 1: Create a React application with the following command:
npx create-react-app my-app
Step 2: Move to the project folder my-app with the following command:
cd my-app
Step 3: Start the development server with the following command:
yarn start
(This will run your application at localhost:3000, where you can see all the changes you make to the application.)
Project Structure: It will look like the following.
Example 1: Comments for React Components. We can write comments in React using the double forward-slash // or the asterisk format /* */, similar to regular JavaScript.
App.js
import React, { Component } from 'react'; // This is a comment class App extends Component { /* This is also a comment*/ render() { return ( <div> <h1>Welcome to GeeksforGeeks</h1> </div> ); }} export default App;
Output:
Example 2: The above example does not work when we want to comment things inside the render block. This is because we use JSX inside the render block and must use multi-line comment in curly braces {/* */}.
App.js
import React, { Component } from 'react'; class App extends Component { render() { return ( <div> // This is not a valid comment /* Neither is this */ {/* THIS ONE IS A VALID COMMENT */} <h1>Welcome to GeeksforGeeks</h1> </div> ); }} export default App;
Output:
Note: We must remember, that even though JSX gets rendered just like normal HTML, it is actually a syntax extension to JavaScript. So, using <!– –> as we did with HTML and XML will not work.
App.js
import React, { Component } from 'react'; class App extends Component { render() { return ( <div> <!-- This is not a valid comment --> {/* THIS ONE IS A VALID COMMENT */} <h1>Welcome to GeeksforGeeks</h1> </div> ); }} export default App;
Output:
Blogathon-2021
Picked
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
Difference Between Local Storage, Session Storage And Cookies
Explain the purpose of render() in ReactJS
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Sep, 2021"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "ReactJS is a JavaScript library used for building user interfaces. It is Declarative, Component-based and Technology stack agnostic. It has been designed for speed, simplicity, and scalability. These features make it one of the most popular libraries among web developers."
},
{
"code": null,
"e": 390,
"s": 301,
"text": "In this article, we will explore creating a React application and adding comments to it."
},
{
"code": null,
"e": 453,
"s": 390,
"text": "Step 1: Create a React application with the following command:"
},
{
"code": null,
"e": 481,
"s": 453,
"text": "npx create-react-app my-app"
},
{
"code": null,
"e": 551,
"s": 481,
"text": "Step 2: Move to the project folder my-app with the following command:"
},
{
"code": null,
"e": 561,
"s": 551,
"text": "cd my-app"
},
{
"code": null,
"e": 628,
"s": 563,
"text": "Step 3: Start the development server with the following command:"
},
{
"code": null,
"e": 639,
"s": 628,
"text": "yarn start"
},
{
"code": null,
"e": 754,
"s": 639,
"text": "(This will run your application at localhost:3000, where you can see all the changes you make to the application.)"
},
{
"code": null,
"e": 806,
"s": 754,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 974,
"s": 806,
"text": "Example 1: Comments for React Components. We can write comments in React using the double forward-slash // or the asterisk format /* */, similar to regular JavaScript."
},
{
"code": null,
"e": 981,
"s": 974,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react'; // This is a comment class App extends Component { /* This is also a comment*/ render() { return ( <div> <h1>Welcome to GeeksforGeeks</h1> </div> ); }} export default App;",
"e": 1264,
"s": 981,
"text": null
},
{
"code": null,
"e": 1273,
"s": 1264,
"text": "Output: "
},
{
"code": null,
"e": 1482,
"s": 1275,
"text": "Example 2: The above example does not work when we want to comment things inside the render block. This is because we use JSX inside the render block and must use multi-line comment in curly braces {/* */}."
},
{
"code": null,
"e": 1489,
"s": 1482,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react'; class App extends Component { render() { return ( <div> // This is not a valid comment /* Neither is this */ {/* THIS ONE IS A VALID COMMENT */} <h1>Welcome to GeeksforGeeks</h1> </div> ); }} export default App;",
"e": 1873,
"s": 1489,
"text": null
},
{
"code": null,
"e": 1881,
"s": 1873,
"text": "Output:"
},
{
"code": null,
"e": 2072,
"s": 1881,
"text": "Note: We must remember, that even though JSX gets rendered just like normal HTML, it is actually a syntax extension to JavaScript. So, using <!– –> as we did with HTML and XML will not work."
},
{
"code": null,
"e": 2079,
"s": 2072,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react'; class App extends Component { render() { return ( <div> <!-- This is not a valid comment --> {/* THIS ONE IS A VALID COMMENT */} <h1>Welcome to GeeksforGeeks</h1> </div> ); }} export default App;",
"e": 2447,
"s": 2079,
"text": null
},
{
"code": null,
"e": 2455,
"s": 2447,
"text": "Output:"
},
{
"code": null,
"e": 2470,
"s": 2455,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 2477,
"s": 2470,
"text": "Picked"
},
{
"code": null,
"e": 2493,
"s": 2477,
"text": "React-Questions"
},
{
"code": null,
"e": 2503,
"s": 2493,
"text": "Blogathon"
},
{
"code": null,
"e": 2511,
"s": 2503,
"text": "ReactJS"
},
{
"code": null,
"e": 2528,
"s": 2511,
"text": "Web Technologies"
},
{
"code": null,
"e": 2626,
"s": 2528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2660,
"s": 2626,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 2701,
"s": 2660,
"text": "How to Connect Python with SQL Database?"
},
{
"code": null,
"e": 2742,
"s": 2701,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 2804,
"s": 2742,
"text": "Difference Between Local Storage, Session Storage And Cookies"
},
{
"code": null,
"e": 2847,
"s": 2804,
"text": "Explain the purpose of render() in ReactJS"
},
{
"code": null,
"e": 2890,
"s": 2847,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2928,
"s": 2890,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2973,
"s": 2928,
"text": "How to redirect to another page in ReactJS ?"
}
] |
Threaded Binary Search Tree | Deletion
|
12 Jul, 2022
A threaded binary tree node looks like following.
C++
Java
Python3
C#
Javascript
struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread;};
static class Node { Node left, right; int info; // True if left pointer points to predecessor // in Inorder Traversal boolean lthread; // True if right pointer points to predecessor // in Inorder Traversal boolean rthread;}; // This code contributed by aashish1995
class Node: def __init__(self): self.info = 0; self.left = None; self.right = None; # True if left pointer points to predecessor # in Inorder Traversal self.lthread = False;; # True if right pointer points to predecessor # in Inorder Traversal self.rthread = False; # This code contributed by umadevi9616
public class Node { public Node left, right; public int info; // True if left pointer points to predecessor // in Inorder Traversal public bool lthread; // True if right pointer points to predecessor // in Inorder Traversal public bool rthread; }; // This code is contributed by aashish1995
<script> class Node { constructor(){ this.left = null, this.right = null; this.info = 0; // True if left pointer points to predecessor // in Inorder Traversal this.lthread = false; // True if right pointer points to predecessor // in Inorder Traversal this.rthread = false;}}// This code contributed by aashish1995</script>
We have already discussed Insertion of Threaded Binary Search Tree
In deletion, first the key to be deleted is searched, and then there are different cases for deleting the Node in which key is found.
C++
Java
Python3
C#
Javascript
// Deletes a key from threaded BST with given root and// returns new root of BST.struct Node* delThreadedBST(struct Node* root, int dkey){ // Initialize parent as NULL and ptrent // Node as root. struct Node *par = NULL, *ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != NULL) { if (dkey == ptr->info) { found = 1; break; } par = ptr; if (dkey < ptr->info) { if (ptr->lthread == false) ptr = ptr->left; else break; } else { if (ptr->rthread == false) ptr = ptr->right; else break; } } if (found == 0) printf("dkey not present in tree\n"); // Two Children else if (ptr->lthread == false && ptr->rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr->lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr->rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;}
// Deletes a key from threaded BST with given root and// returns new root of BST.Node delThreadedBST(Node root, int dkey){ // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) System.out.printf("dkey not present in tree\n"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // This code is contributed by gauravrajput1
# Deletes a key from threaded BST with given root and# returns new root of BST.def delThreadedBST(root, dkey): # Initialize parent as None and ptrent # Node as root. par = None; ptr = root; # Set True if key is found found = 0; # Search key in BST : find Node and its # parent. while (ptr != None): if (dkey == ptr.info): found = 1; break; par = ptr; if (dkey < ptr.info): if (ptr.lthread == False) ptr = ptr.left; else break; else: if (ptr.rthread == False) ptr = ptr.right; else break; if (found == 0): print("dkey not present in tree"); # Two Children else if(ptr.lthread == False and ptr.rthread == False): root = caseC(root, par, ptr); # Only Left Child else if(ptr.lthread == False): root = caseB(root, par, ptr); # Only Right Child else if(ptr.rthread == False): root = caseB(root, par, ptr); # No child else: root = caseA(root, par, ptr); return root; # This code is contributed by Rajput-Ji
// Deletes a key from threaded BST with given root and// returns new root of BST.Node delThreadedBST(Node root, int dkey){ // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) Console.Write("dkey not present in tree\n"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // This code is contributed by gauravrajput1
<script>// Deletes a key from threaded BST with given root and// returns new root of BST.function delThreadedBST(root , dkey){ // Initialize parent as null and ptrent // Node as root. var par = null, ptr = root; // Set true if key is found var found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) document.write("dkey not present in tree\n"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // This code is contributed by gauravrajput1</script>
Case A: Leaf Node need to be deleted
In BST, for deleting a leaf Node the left or right pointer of parent was set to NULL. Here instead of setting the pointer to NULL it is made a thread. If the leaf Node is to be deleted is left child of its parent then after deletion, left pointer of parent should become a thread pointing to its predecessor of the parent Node after deletion.
par -> lthread = true;
par -> left = ptr -> left;
If the leaf Node to be deleted is right child of its parent then after deletion, right pointer of parent should become a thread pointing to its successor. The Node which was inorder successor of the leaf Node before deletion will become the inorder successor of the parent Node after deletion.
C++
Java
Python3
C#
Javascript
// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseA(struct Node* root, struct Node* par, struct Node* ptr){ // If Node to be deleted is root if (par == NULL) root = NULL; // If Node to be deleted is left // of its parent else if (ptr == par->left) { par->lthread = true; par->left = ptr->left; } else { par->rthread = true; par->right = ptr->right; } // Free memory and return new root free(ptr); return root;}
// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.Node caseA(Node root, Node par, Node ptr){ // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root;} // This code is contributed by gauravrajput1
# Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseA(root,par,ptr): # If Node to be deleted is root if (par == None): root = None # If Node to be deleted is left # of its parent elif(ptr == par.left): par.lthread = true par.left = ptr.left else: par.rthread = true par.right = ptr.rightreturn root # This code is contributed by Patel2127.
// Here 'par' is pointer to parent Node and// 'ptr' is pointer to current Node.Node caseA(Node root, Node par, Node ptr){ // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root;} // This code is contributed by rutvik_56
<script> // Here 'par' is pointer to parent Node and// 'ptr' is pointer to current Node.function caseA(root, par, ptr){ // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root;} // This code is contributed by rag2127 </script>
Case B: Node to be deleted has only one child After deleting the Node as in a BST, the inorder successor and inorder predecessor of the Node are found out.
s = inSucc(ptr);
p = inPred(ptr);
If Node to be deleted has left subtree, then after deletion right thread of its predecessor should point to its successor.
p->right = s;
Before deletion 15 is predecessor and 2 is successor of 16. After deletion of 16, the Node 20 becomes the successor of 15, so right thread of 15 will point to 20. If Node to be deleted has right subtree, then after deletion left thread of its successor should point to its predecessor.
s->left = p;
Before deletion of 25 is predecessor and 34 is successor of 30. After deletion of 30, the Node 25 becomes the predecessor of 34, so left thread of 34 will point to 25.
C++
Java
Python3
C#
Javascript
// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseB(struct Node* root, struct Node* par, struct Node* ptr){ struct Node* child; // Initialize child Node to be deleted has // left child. if (ptr->lthread == false) child = ptr->left; // Node to be deleted has right child. else child = ptr->right; // Node to be deleted is root Node. if (par == NULL) root = child; // Node is left child of its parent. else if (ptr == par->left) par->left = child; else par->right = child; // Find successor and predecessor Node* s = inSucc(ptr); Node* p = inPred(ptr); // If ptr has left subtree. if (ptr->lthread == false) p->right = s; // If ptr has right subtree. else { if (ptr->rthread == false) s->left = p; } free(ptr); return root;}
// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.static Node caseB(Node root, Node par, Node ptr){ Node child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root;} // This code is contributed by gauravrajput1
# Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseB(root, par, ptr): child = None; # Initialize child Node to be deleted has # left child. if (ptr.lthread == False): child = ptr.left; # Node to be deleted has right child. else: child = ptr.right; # Node to be deleted is root Node. if (par == None): root = child; # Node is left child of its parent. elif(ptr == par.left): par.left = child; else: par.right = child; # Find successor and predecessor s = inSucc(ptr); p = inPred(ptr); # If ptr has left subtree. if (ptr.lthread == False): p.right = s; # If ptr has right subtree. else: if (ptr.rthread == False): s.left = p; return root; # This code is contributed by umadevi9616
// Here 'par' is pointer to parent Node and// 'ptr' is pointer to current Node.static Node caseB(Node root, Node par, Node ptr){ Node child; // Initialize child Node to be deleted // has left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root;} // This code is contributed by gauravrajput1
<script> // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.function caseB(root,par,ptr){ let child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor let s = inSucc(ptr); let p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root;} // This code is contributed by avanitrachhadiya2155 </script>
Case C: Node to be deleted has two children
We find inorder successor of Node ptr (Node to be deleted) and then copy the information of this successor into Node ptr. After this inorder successor Node is deleted using either Case A or Case B.
C++
Java
C#
Javascript
Python3
// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseC(struct Node* root, struct Node* par, struct Node* ptr){ // Find inorder successor and its parent. struct Node* parsucc = ptr; struct Node* succ = ptr->right; // Find leftmost child of successor while (succ->left != NULL) { parsucc = succ; succ = succ->left; } ptr->info = succ->info; if (succ->lthread == true && succ->rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root;}
// Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // This code is contributed by umadevi9616
// Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // This code is contributed by umadevi9616
<script> // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseC(root, par, ptr) { // Find inorder successor and its parent. var parsucc = ptr; var succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // This code is contributed by gauravrajput1</script>
# Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseC(root, par, ptr): # Find inorder successor and its parent. parsucc = ptr; succ = ptr.right; # Find leftmost child of successor while (succ.lthread == False): parsucc = succ; succ = succ.left; ptr.info = succ.info; if (succ.lthread == True and succ.rthread == True): root = caseA(root, parsucc, succ); else: root = caseB(root, parsucc, succ); return root; # This code contributed by umadevi9616
Below is Complete code:
C++
Java
Python3
C#
Javascript
// Complete C++ program to demonstrate deletion// in threaded BST#include <bits/stdc++.h>using namespace std; struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread;}; // Insert a Node in Binary Threaded Treestruct Node* insert(struct Node* root, int ikey){ // Searching for a Node with given value Node* ptr = root; Node* par = NULL; // Parent of key to be inserted while (ptr != NULL) { // If key already exists, return if (ikey == (ptr->info)) { printf("Duplicate Key !\n"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr->info) { if (ptr->lthread == false) ptr = ptr->left; else break; } // Moving on right subtree. else { if (ptr->rthread == false) ptr = ptr->right; else break; } } // Create a new Node Node* tmp = new Node; tmp->info = ikey; tmp->lthread = true; tmp->rthread = true; if (par == NULL) { root = tmp; tmp->left = NULL; tmp->right = NULL; } else if (ikey < (par->info)) { tmp->left = par->left; tmp->right = par; par->lthread = false; par->left = tmp; } else { tmp->left = par; tmp->right = par->right; par->rthread = false; par->right = tmp; } return root;} // Returns inorder successor using left// and right children (Used in deletion)struct Node* inSucc(struct Node* ptr){ if (ptr->rthread == true) return ptr->right; ptr = ptr->right; while (ptr->lthread == false) ptr = ptr->left; return ptr;} // Returns inorder successor using rthread// (Used in inorder)struct Node* inorderSuccessor(struct Node* ptr){ // If rthread is set, we can quickly find if (ptr->rthread == true) return ptr->right; // Else return leftmost child of right subtree ptr = ptr->right; while (ptr->lthread == false) ptr = ptr->left; return ptr;} // Printing the threaded treevoid inorder(struct Node* root){ if (root == NULL) printf("Tree is empty"); // Reach leftmost Node struct Node* ptr = root; while (ptr->lthread == false) ptr = ptr->left; // One by one print successors while (ptr != NULL) { printf("%d ", ptr->info); ptr = inorderSuccessor(ptr); }} struct Node* inPred(struct Node* ptr){ if (ptr->lthread == true) return ptr->left; ptr = ptr->left; while (ptr->rthread == false) ptr = ptr->right; return ptr;} // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseA(struct Node* root, struct Node* par, struct Node* ptr){ // If Node to be deleted is root if (par == NULL) root = NULL; // If Node to be deleted is left // of its parent else if (ptr == par->left) { par->lthread = true; par->left = ptr->left; } else { par->rthread = true; par->right = ptr->right; } // Free memory and return new root free(ptr); return root;} // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseB(struct Node* root, struct Node* par, struct Node* ptr){ struct Node* child; // Initialize child Node to be deleted has // left child. if (ptr->lthread == false) child = ptr->left; // Node to be deleted has right child. else child = ptr->right; // Node to be deleted is root Node. if (par == NULL) root = child; // Node is left child of its parent. else if (ptr == par->left) par->left = child; else par->right = child; // Find successor and predecessor Node* s = inSucc(ptr); Node* p = inPred(ptr); // If ptr has left subtree. if (ptr->lthread == false) p->right = s; // If ptr has right subtree. else { if (ptr->rthread == false) s->left = p; } free(ptr); return root;} // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseC(struct Node* root, struct Node* par, struct Node* ptr){ // Find inorder successor and its parent. struct Node* parsucc = ptr; struct Node* succ = ptr->right; // Find leftmost child of successor while (succ->lthread==false) { parsucc = succ; succ = succ->left; } ptr->info = succ->info; if (succ->lthread == true && succ->rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root;} // Deletes a key from threaded BST with given root and// returns new root of BST.struct Node* delThreadedBST(struct Node* root, int dkey){ // Initialize parent as NULL and ptrent // Node as root. struct Node *par = NULL, *ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != NULL) { if (dkey == ptr->info) { found = 1; break; } par = ptr; if (dkey < ptr->info) { if (ptr->lthread == false) ptr = ptr->left; else break; } else { if (ptr->rthread == false) ptr = ptr->right; else break; } } if (found == 0) printf("dkey not present in tree\n"); // Two Children else if (ptr->lthread == false && ptr->rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr->lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr->rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // Driver Programint main(){ struct Node* root = NULL; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); return 0;}
// Complete Java program to demonstrate deletion// in threaded BSTimport java.util.*;class solution { static class Node { Node left, right; int info; // True if left pointer points to predecessor // in Inorder Traversal boolean lthread; // True if right pointer points to predecessor // in Inorder Traversal boolean rthread; }; // Insert a Node in Binary Threaded Tree static Node insert(Node root, int ikey) { // Searching for a Node with given value Node ptr = root; Node par = null; // Parent of key to be inserted while (ptr != null) { // If key already exists, return if (ikey == (ptr.info)) { System.out.printf("Duplicate Key !\n"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } // Moving on right subtree. else { if (ptr.rthread == false) ptr = ptr.right; else break; } } // Create a new Node Node tmp = new Node(); tmp.info = ikey; tmp.lthread = true; tmp.rthread = true; if (par == null) { root = tmp; tmp.left = null; tmp.right = null; } else if (ikey < (par.info)) { tmp.left = par.left; tmp.right = par; par.lthread = false; par.left = tmp; } else { tmp.left = par; tmp.right = par.right; par.rthread = false; par.right = tmp; } return root; } // Returns inorder successor using left // and right children (Used in deletion) static Node inSucc(Node ptr) { if (ptr.rthread == true) return ptr.right; ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Returns inorder successor using rthread // (Used in inorder) static Node inorderSuccessor(Node ptr) { // If rthread is set, we can quickly find if (ptr.rthread == true) return ptr.right; // Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Printing the threaded tree static void inorder(Node root) { if (root == null) System.out.printf("Tree is empty"); // Reach leftmost Node Node ptr = root; while (ptr.lthread == false) ptr = ptr.left; // One by one print successors while (ptr != null) { System.out.printf("%d ", ptr.info); ptr = inorderSuccessor(ptr); } } static Node inPred(Node ptr) { if (ptr.lthread == true) return ptr.left; ptr = ptr.left; while (ptr.rthread == false) ptr = ptr.right; return ptr; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseA(Node root, Node par, Node ptr) { // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseB(Node root, Node par, Node ptr) { Node child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // Deletes a key from threaded BST with given root and // returns new root of BST. static Node delThreadedBST(Node root, int dkey) { // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) System.out.printf("dkey not present in tree\n"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root; } // Driver Program public static void main(String args[]) { Node root = null; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); }}// This code is contributed by Arnab Kundu
# Complete Python program to demonstrate deletion# in threaded BST class Node: def __init__(self): self.info = 0; self.left = None; self.right = None; # True if left pointer points to predecessor # in Inorder Traversal self.lthread = False; # True if right pointer points to predecessor # in Inorder Traversal self.rthread = False; # Insert a Node in Binary Threaded Treedef insert(root, ikey): # Searching for a Node with given value ptr = root; par = None; # Parent of key to be inserted while (ptr != None): # If key already exists, return if (ikey == (ptr.info)): print("Duplicate Key !"); return root; par = ptr; # Update parent pointer # Moving on left subtree. if (ikey < ptr.info): if (ptr.lthread == False): ptr = ptr.left; else: break; # Moving on right subtree. else: if (ptr.rthread == False): ptr = ptr.right; else: break; # Create a new Node tmp = Node(); tmp.info = ikey; tmp.lthread = True; tmp.rthread = True; if (par == None): root = tmp; tmp.left = None; tmp.right = None; elif(ikey < (par.info)): tmp.left = par.left; tmp.right = par; par.lthread = False; par.left = tmp; else: tmp.left = par; tmp.right = par.right; par.rthread = False; par.right = tmp; return root; # Returns inorder successor using left# and right children (Used in deletion)def inSucc(ptr): if (ptr.rthread == True): return ptr.right; ptr = ptr.right; while (ptr.lthread == False): ptr = ptr.left; return ptr; # Returns inorder successor using rthread# (Used in inorder)def inorderSuccessor(ptr): # If rthread is set, we can quickly find if (ptr.rthread == True): return ptr.right; # Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == False): ptr = ptr.left; return ptr; # Printing the threaded treedef inorder(root): if (root == None): print("Tree is empty"); # Reach leftmost Node ptr = root; while (ptr.lthread == False): ptr = ptr.left; # One by one print successors while (ptr != None): print( ptr.info, end=" "); ptr = inorderSuccessor(ptr); def inPred(ptr): if (ptr.lthread == True): return ptr.left; ptr = ptr.left; while (ptr.rthread == False): ptr = ptr.right; return ptr; # Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseA(root, par, ptr): # If Node to be deleted is root if (par == None): root = None; # If Node to be deleted is left # of its parent elif(ptr == par.left): par.lthread = True; par.left = ptr.left; else: par.rthread = True; par.right = ptr.right; return root; # Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseB(root, par, ptr): child; # Initialize child Node to be deleted has # left child. if (ptr.lthread == False): child = ptr.left; # Node to be deleted has right child. else: child = ptr.right; # Node to be deleted is root Node. if (par == None): root = child; # Node is left child of its parent. elif(ptr == par.left): par.left = child; else: par.right = child; # Find successor and predecessor s = inSucc(ptr); p = inPred(ptr); # If ptr has left subtree. if (ptr.lthread == False): p.right = s; # If ptr has right subtree. else: if (ptr.rthread == False): s.left = p; return root; # Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseC(root, par, ptr): # Find inorder successor and its parent. parsucc = ptr; succ = ptr.right; # Find leftmost child of successor while (succ.lthread == False): parsucc = succ; succ = succ.left; ptr.info = succ.info; if (succ.lthread == True and succ.rthread == True): root = caseA(root, parsucc, succ); else: root = caseB(root, parsucc, succ); return root; # Deletes a key from threaded BST with given root and# returns new root of BST.def delThreadedBST(root, dkey): # Initialize parent as None and ptrent # Node as root. par = None; ptr = root; # Set True if key is found found = 0; # Search key in BST : find Node and its # parent. while (ptr != None): if (dkey == ptr.info): found = 1; break; par = ptr; if (dkey < ptr.info): if (ptr.lthread == False): ptr = ptr.left; else: break; else: if (ptr.rthread == False): ptr = ptr.right; else: break; if (found == 0): print("dkey not present in tree"); # Two Children elif(ptr.lthread == False and ptr.rthread == False): root = caseC(root, par, ptr); # Only Left Child elif(ptr.lthread == False): root = caseB(root, par, ptr); # Only Right Child elif(ptr.rthread == False): root = caseB(root, par, ptr); # No child else: root = caseA(root, par, ptr); return root; # Driver Programif __name__ == '__main__': root = None; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); # This code is contributed by Rajput-Ji
// Complete C# program to demonstrate deletion// in threaded BSTusing System; class GFG { public class Node { public Node left, right; public int info; // True if left pointer points to predecessor // in Inorder Traversal public bool lthread; // True if right pointer points to predecessor // in Inorder Traversal public bool rthread; }; // Insert a Node in Binary Threaded Tree static Node insert(Node root, int ikey) { // Searching for a Node with given value Node ptr = root; Node par = null; // Parent of key to be inserted while (ptr != null) { // If key already exists, return if (ikey == (ptr.info)) { Console.Write("Duplicate Key !\n"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } // Moving on right subtree. else { if (ptr.rthread == false) ptr = ptr.right; else break; } } // Create a new Node Node tmp = new Node(); tmp.info = ikey; tmp.lthread = true; tmp.rthread = true; if (par == null) { root = tmp; tmp.left = null; tmp.right = null; } else if (ikey < (par.info)) { tmp.left = par.left; tmp.right = par; par.lthread = false; par.left = tmp; } else { tmp.left = par; tmp.right = par.right; par.rthread = false; par.right = tmp; } return root; } // Returns inorder successor using left // and right children (Used in deletion) static Node inSucc(Node ptr) { if (ptr.rthread == true) return ptr.right; ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Returns inorder successor using rthread // (Used in inorder) static Node inorderSuccessor(Node ptr) { // If rthread is set, we can quickly find if (ptr.rthread == true) return ptr.right; // Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Printing the threaded tree static void inorder(Node root) { if (root == null) Console.Write("Tree is empty"); // Reach leftmost Node Node ptr = root; while (ptr.lthread == false) ptr = ptr.left; // One by one print successors while (ptr != null) { Console.Write("{0} ", ptr.info); ptr = inorderSuccessor(ptr); } } static Node inPred(Node ptr) { if (ptr.lthread == true) return ptr.left; ptr = ptr.left; while (ptr.rthread == false) ptr = ptr.right; return ptr; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseA(Node root, Node par, Node ptr) { // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseB(Node root, Node par, Node ptr) { Node child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // Deletes a key from threaded BST with given root and // returns new root of BST. static Node delThreadedBST(Node root, int dkey) { // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) Console.Write("dkey not present in tree\n"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root; } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); }} // This code has been contributed by 29AjayKumar
<script> // Complete JavaScript program to demonstrate deletion // in threaded BST class Node { constructor() { this.info = 0; // True if left pointer points to predecessor // in Inorder Traversal this.lthread = false; // True if right pointer points to predecessor // in Inorder Traversal this.rthread = false; this.left = null; this.right = null; } } // Insert a Node in Binary Threaded Tree function insert(root, ikey) { // Searching for a Node with given value var ptr = root; var par = null; // Parent of key to be inserted while (ptr != null) { // If key already exists, return if (ikey == ptr.info) { document.write("Duplicate Key !<br>"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } // Moving on right subtree. else { if (ptr.rthread == false) ptr = ptr.right; else break; } } // Create a new Node var tmp = new Node(); tmp.info = ikey; tmp.lthread = true; tmp.rthread = true; if (par == null) { root = tmp; tmp.left = null; tmp.right = null; } else if (ikey < par.info) { tmp.left = par.left; tmp.right = par; par.lthread = false; par.left = tmp; } else { tmp.left = par; tmp.right = par.right; par.rthread = false; par.right = tmp; } return root; } // Returns inorder successor using left // and right children (Used in deletion) function inSucc(ptr) { if (ptr.rthread == true) return ptr.right; ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Returns inorder successor using rthread // (Used in inorder) function inorderSuccessor(ptr) { // If rthread is set, we can quickly find if (ptr.rthread == true) return ptr.right; // Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Printing the threaded tree function inorder(root) { if (root == null) document.write("Tree is empty"); // Reach leftmost Node var ptr = root; while (ptr.lthread == false) ptr = ptr.left; // One by one print successors while (ptr != null) { document.write(ptr.info + " "); ptr = inorderSuccessor(ptr); } } function inPred(ptr) { if (ptr.lthread == true) return ptr.left; ptr = ptr.left; while (ptr.rthread == false) ptr = ptr.right; return ptr; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseA(root, par, ptr) { // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseB(root, par, ptr) { var child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor var s = inSucc(ptr); var p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseC(root, par, ptr) { // Find inorder successor and its parent. var parsucc = ptr; var succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // Deletes a key from threaded BST with given root and // returns new root of BST. function delThreadedBST(root, dkey) { // Initialize parent as null and ptrent // Node as root. var par = null, ptr = root; // Set true if key is found var found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) document.write("dkey not present in tree<br>"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root; } // Driver code var root = null; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); </script>
5 10 13 14 16 17 30
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
andrew1234
29AjayKumar
vishwashdwivedi26
aashish1995
GauravRajput1
edusanketdk
rag2127
hguru001
rutvik_56
rdtank
avanitrachhadiya2155
patel2127
jainlovely450
umadevi9616
Rajput-Ji
simmytarika5
surinderdawra388
threaded-binary-tree
Binary Search Tree
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jul, 2022"
},
{
"code": null,
"e": 102,
"s": 52,
"text": "A threaded binary tree node looks like following."
},
{
"code": null,
"e": 106,
"s": 102,
"text": "C++"
},
{
"code": null,
"e": 111,
"s": 106,
"text": "Java"
},
{
"code": null,
"e": 119,
"s": 111,
"text": "Python3"
},
{
"code": null,
"e": 122,
"s": 119,
"text": "C#"
},
{
"code": null,
"e": 133,
"s": 122,
"text": "Javascript"
},
{
"code": "struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread;};",
"e": 383,
"s": 133,
"text": null
},
{
"code": "static class Node { Node left, right; int info; // True if left pointer points to predecessor // in Inorder Traversal boolean lthread; // True if right pointer points to predecessor // in Inorder Traversal boolean rthread;}; // This code contributed by aashish1995",
"e": 675,
"s": 383,
"text": null
},
{
"code": "class Node: def __init__(self): self.info = 0; self.left = None; self.right = None; # True if left pointer points to predecessor # in Inorder Traversal self.lthread = False;; # True if right pointer points to predecessor # in Inorder Traversal self.rthread = False; # This code contributed by umadevi9616",
"e": 1060,
"s": 675,
"text": null
},
{
"code": "public class Node { public Node left, right; public int info; // True if left pointer points to predecessor // in Inorder Traversal public bool lthread; // True if right pointer points to predecessor // in Inorder Traversal public bool rthread; }; // This code is contributed by aashish1995",
"e": 1403,
"s": 1060,
"text": null
},
{
"code": "<script> class Node { constructor(){ this.left = null, this.right = null; this.info = 0; // True if left pointer points to predecessor // in Inorder Traversal this.lthread = false; // True if right pointer points to predecessor // in Inorder Traversal this.rthread = false;}}// This code contributed by aashish1995</script>",
"e": 1761,
"s": 1403,
"text": null
},
{
"code": null,
"e": 1829,
"s": 1761,
"text": "We have already discussed Insertion of Threaded Binary Search Tree "
},
{
"code": null,
"e": 1964,
"s": 1829,
"text": "In deletion, first the key to be deleted is searched, and then there are different cases for deleting the Node in which key is found. "
},
{
"code": null,
"e": 1968,
"s": 1964,
"text": "C++"
},
{
"code": null,
"e": 1973,
"s": 1968,
"text": "Java"
},
{
"code": null,
"e": 1981,
"s": 1973,
"text": "Python3"
},
{
"code": null,
"e": 1984,
"s": 1981,
"text": "C#"
},
{
"code": null,
"e": 1995,
"s": 1984,
"text": "Javascript"
},
{
"code": "// Deletes a key from threaded BST with given root and// returns new root of BST.struct Node* delThreadedBST(struct Node* root, int dkey){ // Initialize parent as NULL and ptrent // Node as root. struct Node *par = NULL, *ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != NULL) { if (dkey == ptr->info) { found = 1; break; } par = ptr; if (dkey < ptr->info) { if (ptr->lthread == false) ptr = ptr->left; else break; } else { if (ptr->rthread == false) ptr = ptr->right; else break; } } if (found == 0) printf(\"dkey not present in tree\\n\"); // Two Children else if (ptr->lthread == false && ptr->rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr->lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr->rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;}",
"e": 3208,
"s": 1995,
"text": null
},
{
"code": "// Deletes a key from threaded BST with given root and// returns new root of BST.Node delThreadedBST(Node root, int dkey){ // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) System.out.printf(\"dkey not present in tree\\n\"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // This code is contributed by gauravrajput1",
"e": 4442,
"s": 3208,
"text": null
},
{
"code": "# Deletes a key from threaded BST with given root and# returns new root of BST.def delThreadedBST(root, dkey): # Initialize parent as None and ptrent # Node as root. par = None; ptr = root; # Set True if key is found found = 0; # Search key in BST : find Node and its # parent. while (ptr != None): if (dkey == ptr.info): found = 1; break; par = ptr; if (dkey < ptr.info): if (ptr.lthread == False) ptr = ptr.left; else break; else: if (ptr.rthread == False) ptr = ptr.right; else break; if (found == 0): print(\"dkey not present in tree\"); # Two Children else if(ptr.lthread == False and ptr.rthread == False): root = caseC(root, par, ptr); # Only Left Child else if(ptr.lthread == False): root = caseB(root, par, ptr); # Only Right Child else if(ptr.rthread == False): root = caseB(root, par, ptr); # No child else: root = caseA(root, par, ptr); return root; # This code is contributed by Rajput-Ji",
"e": 5615,
"s": 4442,
"text": null
},
{
"code": "// Deletes a key from threaded BST with given root and// returns new root of BST.Node delThreadedBST(Node root, int dkey){ // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) Console.Write(\"dkey not present in tree\\n\"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // This code is contributed by gauravrajput1",
"e": 6845,
"s": 5615,
"text": null
},
{
"code": "<script>// Deletes a key from threaded BST with given root and// returns new root of BST.function delThreadedBST(root , dkey){ // Initialize parent as null and ptrent // Node as root. var par = null, ptr = root; // Set true if key is found var found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) document.write(\"dkey not present in tree\\n\"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // This code is contributed by gauravrajput1</script>",
"e": 8088,
"s": 6845,
"text": null
},
{
"code": null,
"e": 8126,
"s": 8088,
"text": "Case A: Leaf Node need to be deleted "
},
{
"code": null,
"e": 8470,
"s": 8126,
"text": "In BST, for deleting a leaf Node the left or right pointer of parent was set to NULL. Here instead of setting the pointer to NULL it is made a thread. If the leaf Node is to be deleted is left child of its parent then after deletion, left pointer of parent should become a thread pointing to its predecessor of the parent Node after deletion. "
},
{
"code": null,
"e": 8520,
"s": 8470,
"text": "par -> lthread = true;\npar -> left = ptr -> left;"
},
{
"code": null,
"e": 8816,
"s": 8520,
"text": "If the leaf Node to be deleted is right child of its parent then after deletion, right pointer of parent should become a thread pointing to its successor. The Node which was inorder successor of the leaf Node before deletion will become the inorder successor of the parent Node after deletion. "
},
{
"code": null,
"e": 8820,
"s": 8816,
"text": "C++"
},
{
"code": null,
"e": 8825,
"s": 8820,
"text": "Java"
},
{
"code": null,
"e": 8833,
"s": 8825,
"text": "Python3"
},
{
"code": null,
"e": 8836,
"s": 8833,
"text": "C#"
},
{
"code": null,
"e": 8847,
"s": 8836,
"text": "Javascript"
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseA(struct Node* root, struct Node* par, struct Node* ptr){ // If Node to be deleted is root if (par == NULL) root = NULL; // If Node to be deleted is left // of its parent else if (ptr == par->left) { par->lthread = true; par->left = ptr->left; } else { par->rthread = true; par->right = ptr->right; } // Free memory and return new root free(ptr); return root;}",
"e": 9392,
"s": 8847,
"text": null
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.Node caseA(Node root, Node par, Node ptr){ // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root;} // This code is contributed by gauravrajput1",
"e": 9894,
"s": 9392,
"text": null
},
{
"code": "# Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseA(root,par,ptr): # If Node to be deleted is root if (par == None): root = None # If Node to be deleted is left # of its parent elif(ptr == par.left): par.lthread = true par.left = ptr.left else: par.rthread = true par.right = ptr.rightreturn root # This code is contributed by Patel2127.",
"e": 10331,
"s": 9894,
"text": null
},
{
"code": "// Here 'par' is pointer to parent Node and// 'ptr' is pointer to current Node.Node caseA(Node root, Node par, Node ptr){ // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root;} // This code is contributed by rutvik_56",
"e": 10818,
"s": 10331,
"text": null
},
{
"code": "<script> // Here 'par' is pointer to parent Node and// 'ptr' is pointer to current Node.function caseA(root, par, ptr){ // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root;} // This code is contributed by rag2127 </script>",
"e": 11312,
"s": 10818,
"text": null
},
{
"code": null,
"e": 11469,
"s": 11312,
"text": "Case B: Node to be deleted has only one child After deleting the Node as in a BST, the inorder successor and inorder predecessor of the Node are found out. "
},
{
"code": null,
"e": 11503,
"s": 11469,
"text": "s = inSucc(ptr);\np = inPred(ptr);"
},
{
"code": null,
"e": 11627,
"s": 11503,
"text": "If Node to be deleted has left subtree, then after deletion right thread of its predecessor should point to its successor. "
},
{
"code": null,
"e": 11641,
"s": 11627,
"text": "p->right = s;"
},
{
"code": null,
"e": 11928,
"s": 11641,
"text": "Before deletion 15 is predecessor and 2 is successor of 16. After deletion of 16, the Node 20 becomes the successor of 15, so right thread of 15 will point to 20. If Node to be deleted has right subtree, then after deletion left thread of its successor should point to its predecessor. "
},
{
"code": null,
"e": 11941,
"s": 11928,
"text": "s->left = p;"
},
{
"code": null,
"e": 12110,
"s": 11941,
"text": "Before deletion of 25 is predecessor and 34 is successor of 30. After deletion of 30, the Node 25 becomes the predecessor of 34, so left thread of 34 will point to 25. "
},
{
"code": null,
"e": 12114,
"s": 12110,
"text": "C++"
},
{
"code": null,
"e": 12119,
"s": 12114,
"text": "Java"
},
{
"code": null,
"e": 12127,
"s": 12119,
"text": "Python3"
},
{
"code": null,
"e": 12130,
"s": 12127,
"text": "C#"
},
{
"code": null,
"e": 12141,
"s": 12130,
"text": "Javascript"
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseB(struct Node* root, struct Node* par, struct Node* ptr){ struct Node* child; // Initialize child Node to be deleted has // left child. if (ptr->lthread == false) child = ptr->left; // Node to be deleted has right child. else child = ptr->right; // Node to be deleted is root Node. if (par == NULL) root = child; // Node is left child of its parent. else if (ptr == par->left) par->left = child; else par->right = child; // Find successor and predecessor Node* s = inSucc(ptr); Node* p = inPred(ptr); // If ptr has left subtree. if (ptr->lthread == false) p->right = s; // If ptr has right subtree. else { if (ptr->rthread == false) s->left = p; } free(ptr); return root;}",
"e": 13059,
"s": 12141,
"text": null
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.static Node caseB(Node root, Node par, Node ptr){ Node child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root;} // This code is contributed by gauravrajput1",
"e": 13962,
"s": 13059,
"text": null
},
{
"code": "# Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseB(root, par, ptr): child = None; # Initialize child Node to be deleted has # left child. if (ptr.lthread == False): child = ptr.left; # Node to be deleted has right child. else: child = ptr.right; # Node to be deleted is root Node. if (par == None): root = child; # Node is left child of its parent. elif(ptr == par.left): par.left = child; else: par.right = child; # Find successor and predecessor s = inSucc(ptr); p = inPred(ptr); # If ptr has left subtree. if (ptr.lthread == False): p.right = s; # If ptr has right subtree. else: if (ptr.rthread == False): s.left = p; return root; # This code is contributed by umadevi9616",
"e": 14804,
"s": 13962,
"text": null
},
{
"code": "// Here 'par' is pointer to parent Node and// 'ptr' is pointer to current Node.static Node caseB(Node root, Node par, Node ptr){ Node child; // Initialize child Node to be deleted // has left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root;} // This code is contributed by gauravrajput1",
"e": 15709,
"s": 14804,
"text": null
},
{
"code": "<script> // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.function caseB(root,par,ptr){ let child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor let s = inSucc(ptr); let p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root;} // This code is contributed by avanitrachhadiya2155 </script>",
"e": 16606,
"s": 15709,
"text": null
},
{
"code": null,
"e": 16651,
"s": 16606,
"text": "Case C: Node to be deleted has two children "
},
{
"code": null,
"e": 16850,
"s": 16651,
"text": "We find inorder successor of Node ptr (Node to be deleted) and then copy the information of this successor into Node ptr. After this inorder successor Node is deleted using either Case A or Case B. "
},
{
"code": null,
"e": 16854,
"s": 16850,
"text": "C++"
},
{
"code": null,
"e": 16859,
"s": 16854,
"text": "Java"
},
{
"code": null,
"e": 16862,
"s": 16859,
"text": "C#"
},
{
"code": null,
"e": 16873,
"s": 16862,
"text": "Javascript"
},
{
"code": null,
"e": 16881,
"s": 16873,
"text": "Python3"
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseC(struct Node* root, struct Node* par, struct Node* ptr){ // Find inorder successor and its parent. struct Node* parsucc = ptr; struct Node* succ = ptr->right; // Find leftmost child of successor while (succ->left != NULL) { parsucc = succ; succ = succ->left; } ptr->info = succ->info; if (succ->lthread == true && succ->rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root;}",
"e": 17484,
"s": 16881,
"text": null
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // This code is contributed by umadevi9616",
"e": 18168,
"s": 17484,
"text": null
},
{
"code": "// Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // This code is contributed by umadevi9616",
"e": 18845,
"s": 18168,
"text": null
},
{
"code": "<script> // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseC(root, par, ptr) { // Find inorder successor and its parent. var parsucc = ptr; var succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // This code is contributed by gauravrajput1</script>",
"e": 19511,
"s": 18845,
"text": null
},
{
"code": "# Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseC(root, par, ptr): # Find inorder successor and its parent. parsucc = ptr; succ = ptr.right; # Find leftmost child of successor while (succ.lthread == False): parsucc = succ; succ = succ.left; ptr.info = succ.info; if (succ.lthread == True and succ.rthread == True): root = caseA(root, parsucc, succ); else: root = caseB(root, parsucc, succ); return root; # This code contributed by umadevi9616",
"e": 20059,
"s": 19511,
"text": null
},
{
"code": null,
"e": 20084,
"s": 20059,
"text": "Below is Complete code: "
},
{
"code": null,
"e": 20088,
"s": 20084,
"text": "C++"
},
{
"code": null,
"e": 20093,
"s": 20088,
"text": "Java"
},
{
"code": null,
"e": 20101,
"s": 20093,
"text": "Python3"
},
{
"code": null,
"e": 20104,
"s": 20101,
"text": "C#"
},
{
"code": null,
"e": 20115,
"s": 20104,
"text": "Javascript"
},
{
"code": "// Complete C++ program to demonstrate deletion// in threaded BST#include <bits/stdc++.h>using namespace std; struct Node { struct Node *left, *right; int info; // false if left pointer points to predecessor // in Inorder Traversal bool lthread; // false if right pointer points to predecessor // in Inorder Traversal bool rthread;}; // Insert a Node in Binary Threaded Treestruct Node* insert(struct Node* root, int ikey){ // Searching for a Node with given value Node* ptr = root; Node* par = NULL; // Parent of key to be inserted while (ptr != NULL) { // If key already exists, return if (ikey == (ptr->info)) { printf(\"Duplicate Key !\\n\"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr->info) { if (ptr->lthread == false) ptr = ptr->left; else break; } // Moving on right subtree. else { if (ptr->rthread == false) ptr = ptr->right; else break; } } // Create a new Node Node* tmp = new Node; tmp->info = ikey; tmp->lthread = true; tmp->rthread = true; if (par == NULL) { root = tmp; tmp->left = NULL; tmp->right = NULL; } else if (ikey < (par->info)) { tmp->left = par->left; tmp->right = par; par->lthread = false; par->left = tmp; } else { tmp->left = par; tmp->right = par->right; par->rthread = false; par->right = tmp; } return root;} // Returns inorder successor using left// and right children (Used in deletion)struct Node* inSucc(struct Node* ptr){ if (ptr->rthread == true) return ptr->right; ptr = ptr->right; while (ptr->lthread == false) ptr = ptr->left; return ptr;} // Returns inorder successor using rthread// (Used in inorder)struct Node* inorderSuccessor(struct Node* ptr){ // If rthread is set, we can quickly find if (ptr->rthread == true) return ptr->right; // Else return leftmost child of right subtree ptr = ptr->right; while (ptr->lthread == false) ptr = ptr->left; return ptr;} // Printing the threaded treevoid inorder(struct Node* root){ if (root == NULL) printf(\"Tree is empty\"); // Reach leftmost Node struct Node* ptr = root; while (ptr->lthread == false) ptr = ptr->left; // One by one print successors while (ptr != NULL) { printf(\"%d \", ptr->info); ptr = inorderSuccessor(ptr); }} struct Node* inPred(struct Node* ptr){ if (ptr->lthread == true) return ptr->left; ptr = ptr->left; while (ptr->rthread == false) ptr = ptr->right; return ptr;} // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseA(struct Node* root, struct Node* par, struct Node* ptr){ // If Node to be deleted is root if (par == NULL) root = NULL; // If Node to be deleted is left // of its parent else if (ptr == par->left) { par->lthread = true; par->left = ptr->left; } else { par->rthread = true; par->right = ptr->right; } // Free memory and return new root free(ptr); return root;} // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseB(struct Node* root, struct Node* par, struct Node* ptr){ struct Node* child; // Initialize child Node to be deleted has // left child. if (ptr->lthread == false) child = ptr->left; // Node to be deleted has right child. else child = ptr->right; // Node to be deleted is root Node. if (par == NULL) root = child; // Node is left child of its parent. else if (ptr == par->left) par->left = child; else par->right = child; // Find successor and predecessor Node* s = inSucc(ptr); Node* p = inPred(ptr); // If ptr has left subtree. if (ptr->lthread == false) p->right = s; // If ptr has right subtree. else { if (ptr->rthread == false) s->left = p; } free(ptr); return root;} // Here 'par' is pointer to parent Node and 'ptr' is// pointer to current Node.struct Node* caseC(struct Node* root, struct Node* par, struct Node* ptr){ // Find inorder successor and its parent. struct Node* parsucc = ptr; struct Node* succ = ptr->right; // Find leftmost child of successor while (succ->lthread==false) { parsucc = succ; succ = succ->left; } ptr->info = succ->info; if (succ->lthread == true && succ->rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root;} // Deletes a key from threaded BST with given root and// returns new root of BST.struct Node* delThreadedBST(struct Node* root, int dkey){ // Initialize parent as NULL and ptrent // Node as root. struct Node *par = NULL, *ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != NULL) { if (dkey == ptr->info) { found = 1; break; } par = ptr; if (dkey < ptr->info) { if (ptr->lthread == false) ptr = ptr->left; else break; } else { if (ptr->rthread == false) ptr = ptr->right; else break; } } if (found == 0) printf(\"dkey not present in tree\\n\"); // Two Children else if (ptr->lthread == false && ptr->rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr->lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr->rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root;} // Driver Programint main(){ struct Node* root = NULL; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); return 0;}",
"e": 26570,
"s": 20115,
"text": null
},
{
"code": "// Complete Java program to demonstrate deletion// in threaded BSTimport java.util.*;class solution { static class Node { Node left, right; int info; // True if left pointer points to predecessor // in Inorder Traversal boolean lthread; // True if right pointer points to predecessor // in Inorder Traversal boolean rthread; }; // Insert a Node in Binary Threaded Tree static Node insert(Node root, int ikey) { // Searching for a Node with given value Node ptr = root; Node par = null; // Parent of key to be inserted while (ptr != null) { // If key already exists, return if (ikey == (ptr.info)) { System.out.printf(\"Duplicate Key !\\n\"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } // Moving on right subtree. else { if (ptr.rthread == false) ptr = ptr.right; else break; } } // Create a new Node Node tmp = new Node(); tmp.info = ikey; tmp.lthread = true; tmp.rthread = true; if (par == null) { root = tmp; tmp.left = null; tmp.right = null; } else if (ikey < (par.info)) { tmp.left = par.left; tmp.right = par; par.lthread = false; par.left = tmp; } else { tmp.left = par; tmp.right = par.right; par.rthread = false; par.right = tmp; } return root; } // Returns inorder successor using left // and right children (Used in deletion) static Node inSucc(Node ptr) { if (ptr.rthread == true) return ptr.right; ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Returns inorder successor using rthread // (Used in inorder) static Node inorderSuccessor(Node ptr) { // If rthread is set, we can quickly find if (ptr.rthread == true) return ptr.right; // Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Printing the threaded tree static void inorder(Node root) { if (root == null) System.out.printf(\"Tree is empty\"); // Reach leftmost Node Node ptr = root; while (ptr.lthread == false) ptr = ptr.left; // One by one print successors while (ptr != null) { System.out.printf(\"%d \", ptr.info); ptr = inorderSuccessor(ptr); } } static Node inPred(Node ptr) { if (ptr.lthread == true) return ptr.left; ptr = ptr.left; while (ptr.rthread == false) ptr = ptr.right; return ptr; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseA(Node root, Node par, Node ptr) { // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseB(Node root, Node par, Node ptr) { Node child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // Deletes a key from threaded BST with given root and // returns new root of BST. static Node delThreadedBST(Node root, int dkey) { // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) System.out.printf(\"dkey not present in tree\\n\"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root; } // Driver Program public static void main(String args[]) { Node root = null; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); }}// This code is contributed by Arnab Kundu",
"e": 33791,
"s": 26570,
"text": null
},
{
"code": "# Complete Python program to demonstrate deletion# in threaded BST class Node: def __init__(self): self.info = 0; self.left = None; self.right = None; # True if left pointer points to predecessor # in Inorder Traversal self.lthread = False; # True if right pointer points to predecessor # in Inorder Traversal self.rthread = False; # Insert a Node in Binary Threaded Treedef insert(root, ikey): # Searching for a Node with given value ptr = root; par = None; # Parent of key to be inserted while (ptr != None): # If key already exists, return if (ikey == (ptr.info)): print(\"Duplicate Key !\"); return root; par = ptr; # Update parent pointer # Moving on left subtree. if (ikey < ptr.info): if (ptr.lthread == False): ptr = ptr.left; else: break; # Moving on right subtree. else: if (ptr.rthread == False): ptr = ptr.right; else: break; # Create a new Node tmp = Node(); tmp.info = ikey; tmp.lthread = True; tmp.rthread = True; if (par == None): root = tmp; tmp.left = None; tmp.right = None; elif(ikey < (par.info)): tmp.left = par.left; tmp.right = par; par.lthread = False; par.left = tmp; else: tmp.left = par; tmp.right = par.right; par.rthread = False; par.right = tmp; return root; # Returns inorder successor using left# and right children (Used in deletion)def inSucc(ptr): if (ptr.rthread == True): return ptr.right; ptr = ptr.right; while (ptr.lthread == False): ptr = ptr.left; return ptr; # Returns inorder successor using rthread# (Used in inorder)def inorderSuccessor(ptr): # If rthread is set, we can quickly find if (ptr.rthread == True): return ptr.right; # Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == False): ptr = ptr.left; return ptr; # Printing the threaded treedef inorder(root): if (root == None): print(\"Tree is empty\"); # Reach leftmost Node ptr = root; while (ptr.lthread == False): ptr = ptr.left; # One by one print successors while (ptr != None): print( ptr.info, end=\" \"); ptr = inorderSuccessor(ptr); def inPred(ptr): if (ptr.lthread == True): return ptr.left; ptr = ptr.left; while (ptr.rthread == False): ptr = ptr.right; return ptr; # Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseA(root, par, ptr): # If Node to be deleted is root if (par == None): root = None; # If Node to be deleted is left # of its parent elif(ptr == par.left): par.lthread = True; par.left = ptr.left; else: par.rthread = True; par.right = ptr.right; return root; # Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseB(root, par, ptr): child; # Initialize child Node to be deleted has # left child. if (ptr.lthread == False): child = ptr.left; # Node to be deleted has right child. else: child = ptr.right; # Node to be deleted is root Node. if (par == None): root = child; # Node is left child of its parent. elif(ptr == par.left): par.left = child; else: par.right = child; # Find successor and predecessor s = inSucc(ptr); p = inPred(ptr); # If ptr has left subtree. if (ptr.lthread == False): p.right = s; # If ptr has right subtree. else: if (ptr.rthread == False): s.left = p; return root; # Here 'par' is pointer to parent Node and 'ptr' is# pointer to current Node.def caseC(root, par, ptr): # Find inorder successor and its parent. parsucc = ptr; succ = ptr.right; # Find leftmost child of successor while (succ.lthread == False): parsucc = succ; succ = succ.left; ptr.info = succ.info; if (succ.lthread == True and succ.rthread == True): root = caseA(root, parsucc, succ); else: root = caseB(root, parsucc, succ); return root; # Deletes a key from threaded BST with given root and# returns new root of BST.def delThreadedBST(root, dkey): # Initialize parent as None and ptrent # Node as root. par = None; ptr = root; # Set True if key is found found = 0; # Search key in BST : find Node and its # parent. while (ptr != None): if (dkey == ptr.info): found = 1; break; par = ptr; if (dkey < ptr.info): if (ptr.lthread == False): ptr = ptr.left; else: break; else: if (ptr.rthread == False): ptr = ptr.right; else: break; if (found == 0): print(\"dkey not present in tree\"); # Two Children elif(ptr.lthread == False and ptr.rthread == False): root = caseC(root, par, ptr); # Only Left Child elif(ptr.lthread == False): root = caseB(root, par, ptr); # Only Right Child elif(ptr.rthread == False): root = caseB(root, par, ptr); # No child else: root = caseA(root, par, ptr); return root; # Driver Programif __name__ == '__main__': root = None; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); # This code is contributed by Rajput-Ji",
"e": 39668,
"s": 33791,
"text": null
},
{
"code": "// Complete C# program to demonstrate deletion// in threaded BSTusing System; class GFG { public class Node { public Node left, right; public int info; // True if left pointer points to predecessor // in Inorder Traversal public bool lthread; // True if right pointer points to predecessor // in Inorder Traversal public bool rthread; }; // Insert a Node in Binary Threaded Tree static Node insert(Node root, int ikey) { // Searching for a Node with given value Node ptr = root; Node par = null; // Parent of key to be inserted while (ptr != null) { // If key already exists, return if (ikey == (ptr.info)) { Console.Write(\"Duplicate Key !\\n\"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } // Moving on right subtree. else { if (ptr.rthread == false) ptr = ptr.right; else break; } } // Create a new Node Node tmp = new Node(); tmp.info = ikey; tmp.lthread = true; tmp.rthread = true; if (par == null) { root = tmp; tmp.left = null; tmp.right = null; } else if (ikey < (par.info)) { tmp.left = par.left; tmp.right = par; par.lthread = false; par.left = tmp; } else { tmp.left = par; tmp.right = par.right; par.rthread = false; par.right = tmp; } return root; } // Returns inorder successor using left // and right children (Used in deletion) static Node inSucc(Node ptr) { if (ptr.rthread == true) return ptr.right; ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Returns inorder successor using rthread // (Used in inorder) static Node inorderSuccessor(Node ptr) { // If rthread is set, we can quickly find if (ptr.rthread == true) return ptr.right; // Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Printing the threaded tree static void inorder(Node root) { if (root == null) Console.Write(\"Tree is empty\"); // Reach leftmost Node Node ptr = root; while (ptr.lthread == false) ptr = ptr.left; // One by one print successors while (ptr != null) { Console.Write(\"{0} \", ptr.info); ptr = inorderSuccessor(ptr); } } static Node inPred(Node ptr) { if (ptr.lthread == true) return ptr.left; ptr = ptr.left; while (ptr.rthread == false) ptr = ptr.right; return ptr; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseA(Node root, Node par, Node ptr) { // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseB(Node root, Node par, Node ptr) { Node child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor Node s = inSucc(ptr); Node p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. static Node caseC(Node root, Node par, Node ptr) { // Find inorder successor and its parent. Node parsucc = ptr; Node succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // Deletes a key from threaded BST with given root and // returns new root of BST. static Node delThreadedBST(Node root, int dkey) { // Initialize parent as null and ptrent // Node as root. Node par = null, ptr = root; // Set true if key is found int found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) Console.Write(\"dkey not present in tree\\n\"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root; } // Driver code public static void Main(String[] args) { Node root = null; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); }} // This code has been contributed by 29AjayKumar",
"e": 46882,
"s": 39668,
"text": null
},
{
"code": "<script> // Complete JavaScript program to demonstrate deletion // in threaded BST class Node { constructor() { this.info = 0; // True if left pointer points to predecessor // in Inorder Traversal this.lthread = false; // True if right pointer points to predecessor // in Inorder Traversal this.rthread = false; this.left = null; this.right = null; } } // Insert a Node in Binary Threaded Tree function insert(root, ikey) { // Searching for a Node with given value var ptr = root; var par = null; // Parent of key to be inserted while (ptr != null) { // If key already exists, return if (ikey == ptr.info) { document.write(\"Duplicate Key !<br>\"); return root; } par = ptr; // Update parent pointer // Moving on left subtree. if (ikey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } // Moving on right subtree. else { if (ptr.rthread == false) ptr = ptr.right; else break; } } // Create a new Node var tmp = new Node(); tmp.info = ikey; tmp.lthread = true; tmp.rthread = true; if (par == null) { root = tmp; tmp.left = null; tmp.right = null; } else if (ikey < par.info) { tmp.left = par.left; tmp.right = par; par.lthread = false; par.left = tmp; } else { tmp.left = par; tmp.right = par.right; par.rthread = false; par.right = tmp; } return root; } // Returns inorder successor using left // and right children (Used in deletion) function inSucc(ptr) { if (ptr.rthread == true) return ptr.right; ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Returns inorder successor using rthread // (Used in inorder) function inorderSuccessor(ptr) { // If rthread is set, we can quickly find if (ptr.rthread == true) return ptr.right; // Else return leftmost child of right subtree ptr = ptr.right; while (ptr.lthread == false) ptr = ptr.left; return ptr; } // Printing the threaded tree function inorder(root) { if (root == null) document.write(\"Tree is empty\"); // Reach leftmost Node var ptr = root; while (ptr.lthread == false) ptr = ptr.left; // One by one print successors while (ptr != null) { document.write(ptr.info + \" \"); ptr = inorderSuccessor(ptr); } } function inPred(ptr) { if (ptr.lthread == true) return ptr.left; ptr = ptr.left; while (ptr.rthread == false) ptr = ptr.right; return ptr; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseA(root, par, ptr) { // If Node to be deleted is root if (par == null) root = null; // If Node to be deleted is left // of its parent else if (ptr == par.left) { par.lthread = true; par.left = ptr.left; } else { par.rthread = true; par.right = ptr.right; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseB(root, par, ptr) { var child; // Initialize child Node to be deleted has // left child. if (ptr.lthread == false) child = ptr.left; // Node to be deleted has right child. else child = ptr.right; // Node to be deleted is root Node. if (par == null) root = child; // Node is left child of its parent. else if (ptr == par.left) par.left = child; else par.right = child; // Find successor and predecessor var s = inSucc(ptr); var p = inPred(ptr); // If ptr has left subtree. if (ptr.lthread == false) p.right = s; // If ptr has right subtree. else { if (ptr.rthread == false) s.left = p; } return root; } // Here 'par' is pointer to parent Node and 'ptr' is // pointer to current Node. function caseC(root, par, ptr) { // Find inorder successor and its parent. var parsucc = ptr; var succ = ptr.right; // Find leftmost child of successor while (succ.lthread == false) { parsucc = succ; succ = succ.left; } ptr.info = succ.info; if (succ.lthread == true && succ.rthread == true) root = caseA(root, parsucc, succ); else root = caseB(root, parsucc, succ); return root; } // Deletes a key from threaded BST with given root and // returns new root of BST. function delThreadedBST(root, dkey) { // Initialize parent as null and ptrent // Node as root. var par = null, ptr = root; // Set true if key is found var found = 0; // Search key in BST : find Node and its // parent. while (ptr != null) { if (dkey == ptr.info) { found = 1; break; } par = ptr; if (dkey < ptr.info) { if (ptr.lthread == false) ptr = ptr.left; else break; } else { if (ptr.rthread == false) ptr = ptr.right; else break; } } if (found == 0) document.write(\"dkey not present in tree<br>\"); // Two Children else if (ptr.lthread == false && ptr.rthread == false) root = caseC(root, par, ptr); // Only Left Child else if (ptr.lthread == false) root = caseB(root, par, ptr); // Only Right Child else if (ptr.rthread == false) root = caseB(root, par, ptr); // No child else root = caseA(root, par, ptr); return root; } // Driver code var root = null; root = insert(root, 20); root = insert(root, 10); root = insert(root, 30); root = insert(root, 5); root = insert(root, 16); root = insert(root, 14); root = insert(root, 17); root = insert(root, 13); root = delThreadedBST(root, 20); inorder(root); </script>",
"e": 53412,
"s": 46882,
"text": null
},
{
"code": null,
"e": 53433,
"s": 53412,
"text": "5 10 13 14 16 17 30 "
},
{
"code": null,
"e": 53735,
"s": 53433,
"text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 53746,
"s": 53735,
"text": "andrew1234"
},
{
"code": null,
"e": 53758,
"s": 53746,
"text": "29AjayKumar"
},
{
"code": null,
"e": 53776,
"s": 53758,
"text": "vishwashdwivedi26"
},
{
"code": null,
"e": 53788,
"s": 53776,
"text": "aashish1995"
},
{
"code": null,
"e": 53802,
"s": 53788,
"text": "GauravRajput1"
},
{
"code": null,
"e": 53814,
"s": 53802,
"text": "edusanketdk"
},
{
"code": null,
"e": 53822,
"s": 53814,
"text": "rag2127"
},
{
"code": null,
"e": 53831,
"s": 53822,
"text": "hguru001"
},
{
"code": null,
"e": 53841,
"s": 53831,
"text": "rutvik_56"
},
{
"code": null,
"e": 53848,
"s": 53841,
"text": "rdtank"
},
{
"code": null,
"e": 53869,
"s": 53848,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 53879,
"s": 53869,
"text": "patel2127"
},
{
"code": null,
"e": 53893,
"s": 53879,
"text": "jainlovely450"
},
{
"code": null,
"e": 53905,
"s": 53893,
"text": "umadevi9616"
},
{
"code": null,
"e": 53915,
"s": 53905,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 53928,
"s": 53915,
"text": "simmytarika5"
},
{
"code": null,
"e": 53945,
"s": 53928,
"text": "surinderdawra388"
},
{
"code": null,
"e": 53966,
"s": 53945,
"text": "threaded-binary-tree"
},
{
"code": null,
"e": 53985,
"s": 53966,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 54004,
"s": 53985,
"text": "Binary Search Tree"
}
] |
Python – Adjacent elements in List
|
11 Oct, 2020
Given a List extract both next and previous element for each element.
Input : test_list = [3, 7, 9, 3] Output : [(None, 7), (3, 9), (7, 3), (9, None)] Explanation : for 7 left element is 3 and right, 9.
Input : test_list = [3, 7, 3] Output : [(None, 7), (3, 3), (7, None)] Explanation : for 7 left element is 3 and right, 3.
Method : Using loop
In this, we iterate for each element and get next and previous element using element access.
Python3
# Python3 code to demonstrate working of# Adjacent elements in List# Using loop # Function to find adjacent# elements in Listdef findAdjacentElements(test_list): res = [] for idx, ele in enumerate(test_list): # Checking for all cases to append if idx == 0: res.append((None, test_list[idx + 1])) elif idx == len(test_list) - 1: res.append((test_list[idx - 1], None)) else: res.append((test_list[idx - 1], test_list[idx + 1])) return res # Initializing listinput_list = [3, 7, 8, 2, 1, 5, 8, 9, 3] # Printing original listprint("The original list is:", input_list) # printing resultprint("The Adjacent elements list:", findAdjacentElements(input_list))
Output:
The original list is: [3, 7, 8, 2, 1, 5, 8, 9, 3]The Adjacent elements list: [(None, 7), (3, 8), (7, 2), (8, 1), (2, 5), (1, 8), (5, 9), (8, 3), (9, None)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 98,
"s": 28,
"text": "Given a List extract both next and previous element for each element."
},
{
"code": null,
"e": 231,
"s": 98,
"text": "Input : test_list = [3, 7, 9, 3] Output : [(None, 7), (3, 9), (7, 3), (9, None)] Explanation : for 7 left element is 3 and right, 9."
},
{
"code": null,
"e": 354,
"s": 231,
"text": "Input : test_list = [3, 7, 3] Output : [(None, 7), (3, 3), (7, None)] Explanation : for 7 left element is 3 and right, 3. "
},
{
"code": null,
"e": 374,
"s": 354,
"text": "Method : Using loop"
},
{
"code": null,
"e": 467,
"s": 374,
"text": "In this, we iterate for each element and get next and previous element using element access."
},
{
"code": null,
"e": 475,
"s": 467,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Adjacent elements in List# Using loop # Function to find adjacent# elements in Listdef findAdjacentElements(test_list): res = [] for idx, ele in enumerate(test_list): # Checking for all cases to append if idx == 0: res.append((None, test_list[idx + 1])) elif idx == len(test_list) - 1: res.append((test_list[idx - 1], None)) else: res.append((test_list[idx - 1], test_list[idx + 1])) return res # Initializing listinput_list = [3, 7, 8, 2, 1, 5, 8, 9, 3] # Printing original listprint(\"The original list is:\", input_list) # printing resultprint(\"The Adjacent elements list:\", findAdjacentElements(input_list))",
"e": 1209,
"s": 475,
"text": null
},
{
"code": null,
"e": 1217,
"s": 1209,
"text": "Output:"
},
{
"code": null,
"e": 1373,
"s": 1217,
"text": "The original list is: [3, 7, 8, 2, 1, 5, 8, 9, 3]The Adjacent elements list: [(None, 7), (3, 8), (7, 2), (8, 1), (2, 5), (1, 8), (5, 9), (8, 3), (9, None)]"
},
{
"code": null,
"e": 1394,
"s": 1373,
"text": "Python list-programs"
},
{
"code": null,
"e": 1401,
"s": 1394,
"text": "Python"
},
{
"code": null,
"e": 1417,
"s": 1401,
"text": "Python Programs"
},
{
"code": null,
"e": 1515,
"s": 1417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1547,
"s": 1515,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1574,
"s": 1547,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1595,
"s": 1574,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1618,
"s": 1595,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1674,
"s": 1618,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1696,
"s": 1674,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1735,
"s": 1696,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 1773,
"s": 1735,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 1810,
"s": 1773,
"text": "Python Program for Fibonacci numbers"
}
] |
Python | os.write() method
|
18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.write() method in Python is used to write a bytestring to the given file descriptor.
A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc.
Note: os.write() method is intended for low-level operation and should be applied to a file descriptor as returned by os.open() or os.pipe() method.
Syntax: os.write(fd, str)
Parameter:fd: The file descriptor representing the target file.str: A bytes-like object to be written in the file.
Return Type: This method returns an integer value which represents the number of bytes actually written.
# Python program to explain os.write() method # importing os module import os # File path path = "/home / ihritik / Documents / GeeksForGeeks.txt" # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR) # String to be writtens = "GeeksForGeeks: A Computer science portal for Geeks." # Convert the string to bytesline = str.encode(s) # Write the bytestring to the file# associated with the file# descriptor fd and get the number of# Bytes actually writtennumBytes = os.write(fd, line) print("Number of bytes written:", numBytes) # close the file descriptoros.close(fd)
Number of bytes written: 51
python-os-module
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Jun, 2019"
},
{
"code": null,
"e": 273,
"s": 54,
"text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 361,
"s": 273,
"text": "os.write() method in Python is used to write a bytestring to the given file descriptor."
},
{
"code": null,
"e": 559,
"s": 361,
"text": "A file descriptor is small integer value that corresponds to a file that has been opened by the current process. It is used to perform various lower level I/O operations like read, write, send etc."
},
{
"code": null,
"e": 708,
"s": 559,
"text": "Note: os.write() method is intended for low-level operation and should be applied to a file descriptor as returned by os.open() or os.pipe() method."
},
{
"code": null,
"e": 734,
"s": 708,
"text": "Syntax: os.write(fd, str)"
},
{
"code": null,
"e": 849,
"s": 734,
"text": "Parameter:fd: The file descriptor representing the target file.str: A bytes-like object to be written in the file."
},
{
"code": null,
"e": 954,
"s": 849,
"text": "Return Type: This method returns an integer value which represents the number of bytes actually written."
},
{
"code": "# Python program to explain os.write() method # importing os module import os # File path path = \"/home / ihritik / Documents / GeeksForGeeks.txt\" # Open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_RDWR) # String to be writtens = \"GeeksForGeeks: A Computer science portal for Geeks.\" # Convert the string to bytesline = str.encode(s) # Write the bytestring to the file# associated with the file# descriptor fd and get the number of# Bytes actually writtennumBytes = os.write(fd, line) print(\"Number of bytes written:\", numBytes) # close the file descriptoros.close(fd)",
"e": 1598,
"s": 954,
"text": null
},
{
"code": null,
"e": 1627,
"s": 1598,
"text": "Number of bytes written: 51\n"
},
{
"code": null,
"e": 1644,
"s": 1627,
"text": "python-os-module"
},
{
"code": null,
"e": 1651,
"s": 1644,
"text": "Python"
},
{
"code": null,
"e": 1749,
"s": 1651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1781,
"s": 1749,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1808,
"s": 1781,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1829,
"s": 1808,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1852,
"s": 1829,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1908,
"s": 1852,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1939,
"s": 1908,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1981,
"s": 1939,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2023,
"s": 1981,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2062,
"s": 2023,
"text": "Python | datetime.timedelta() function"
}
] |
Dart Programming - Map.addAll() Function
|
The Map.addAll() function adds all key-value pairs of other to this map.
Map.addAll(Map<K, V> other)
other − represents a key value pair.
other − represents a key value pair.
Return Type − void
void main() {
Map m = {'name':'Tom','Id':'E1001'};
print('Map :${m}');
m.addAll({'dept':'HR','email':'tom@xyz.com'});
print('Map after adding entries :${m}');
}
It will produce the following output −
Map : {name: Tom, Id: E1001}
Map after adding entries : {name: Tom, Id: E1001, dept: HR, email: tom@xyz.com}
44 Lectures
4.5 hours
Sriyank Siddhartha
34 Lectures
4 hours
Sriyank Siddhartha
69 Lectures
4 hours
Frahaan Hussain
117 Lectures
10 hours
Frahaan Hussain
22 Lectures
1.5 hours
Pranjal Srivastava
34 Lectures
3 hours
Pranjal Srivastava
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2598,
"s": 2525,
"text": "The Map.addAll() function adds all key-value pairs of other to this map."
},
{
"code": null,
"e": 2628,
"s": 2598,
"text": "Map.addAll(Map<K, V> other) \n"
},
{
"code": null,
"e": 2665,
"s": 2628,
"text": "other − represents a key value pair."
},
{
"code": null,
"e": 2702,
"s": 2665,
"text": "other − represents a key value pair."
},
{
"code": null,
"e": 2721,
"s": 2702,
"text": "Return Type − void"
},
{
"code": null,
"e": 2905,
"s": 2721,
"text": "void main() { \n Map m = {'name':'Tom','Id':'E1001'}; \n print('Map :${m}'); \n \n m.addAll({'dept':'HR','email':'tom@xyz.com'}); \n print('Map after adding entries :${m}'); \n} "
},
{
"code": null,
"e": 2944,
"s": 2905,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3055,
"s": 2944,
"text": "Map : {name: Tom, Id: E1001} \nMap after adding entries : {name: Tom, Id: E1001, dept: HR, email: tom@xyz.com}\n"
},
{
"code": null,
"e": 3090,
"s": 3055,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3110,
"s": 3090,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3143,
"s": 3110,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3163,
"s": 3143,
"text": " Sriyank Siddhartha"
},
{
"code": null,
"e": 3196,
"s": 3163,
"text": "\n 69 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3213,
"s": 3196,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3248,
"s": 3213,
"text": "\n 117 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3265,
"s": 3248,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3300,
"s": 3265,
"text": "\n 22 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3320,
"s": 3300,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3353,
"s": 3320,
"text": "\n 34 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3373,
"s": 3353,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3380,
"s": 3373,
"text": " Print"
},
{
"code": null,
"e": 3391,
"s": 3380,
"text": " Add Notes"
}
] |
How to change the background color of the font in PowerShell?
|
To change the background color of the font, you can use the GUI and command line both.
With GUI − Colors → Screen Background.
CLI −
$host.UI.RawUI.BackgroundColor = "DarkBlue"
You will notice that the background color of the text has been changed to DarkBlue.
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To change the background color of the font, you can use the GUI and command line both."
},
{
"code": null,
"e": 1188,
"s": 1149,
"text": "With GUI − Colors → Screen Background."
},
{
"code": null,
"e": 1194,
"s": 1188,
"text": "CLI −"
},
{
"code": null,
"e": 1238,
"s": 1194,
"text": "$host.UI.RawUI.BackgroundColor = \"DarkBlue\""
},
{
"code": null,
"e": 1322,
"s": 1238,
"text": "You will notice that the background color of the text has been changed to DarkBlue."
}
] |
AWT ContainerListener Interface
|
The interfaceContainerListener is used for receiving container events. The class that process container events needs to implements this interface.
Following is the declaration for java.awt.event.ContainerListener interface:
public interface ContainerListener
extends EventListener
void componentAdded(ContainerEvent e)
Invoked when a component has been added to the container.
void componentRemoved(ContainerEvent e)
Invoked when a component has been removed from the container.
This class inherits methods from the following interfaces:
java.awt.event.EventListener
java.awt.event.EventListener
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtListenerDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showContainerListenerDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showContainerListenerDemo(){
headerLabel.setText("Listener in action: ContainerListener");
ScrollPane panel = new ScrollPane();
panel.setBackground(Color.magenta);
panel.addContainerListener(new CustomContainerListener());
Label msglabel = new Label();
msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomContainerListener implements ContainerListener {
public void componentAdded(ContainerEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " added. ");
}
public void componentRemoved(ContainerEvent e) {
statusLabel.setText(statusLabel.getText()
+ e.getComponent().getClass().getSimpleName() + " removed. ");
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtListenerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtListenerDemo
Verify the following output
13 Lectures
2 hours
EduOLC
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1895,
"s": 1747,
"text": "The interfaceContainerListener is used for receiving container events. The class that process container events needs to implements this interface."
},
{
"code": null,
"e": 1972,
"s": 1895,
"text": "Following is the declaration for java.awt.event.ContainerListener interface:"
},
{
"code": null,
"e": 2029,
"s": 1972,
"text": "public interface ContainerListener\nextends EventListener"
},
{
"code": null,
"e": 2068,
"s": 2029,
"text": "void componentAdded(ContainerEvent e) "
},
{
"code": null,
"e": 2126,
"s": 2068,
"text": "Invoked when a component has been added to the container."
},
{
"code": null,
"e": 2167,
"s": 2126,
"text": "void componentRemoved(ContainerEvent e) "
},
{
"code": null,
"e": 2229,
"s": 2167,
"text": "Invoked when a component has been removed from the container."
},
{
"code": null,
"e": 2288,
"s": 2229,
"text": "This class inherits methods from the following interfaces:"
},
{
"code": null,
"e": 2317,
"s": 2288,
"text": "java.awt.event.EventListener"
},
{
"code": null,
"e": 2346,
"s": 2317,
"text": "java.awt.event.EventListener"
},
{
"code": null,
"e": 2460,
"s": 2346,
"text": "Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 4669,
"s": 2460,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class AwtListenerDemo {\n private Frame mainFrame;\n private Label headerLabel;\n private Label statusLabel;\n private Panel controlPanel;\n\n public AwtListenerDemo(){\n prepareGUI();\n }\n\n public static void main(String[] args){\n AwtListenerDemo awtListenerDemo = new AwtListenerDemo(); \n awtListenerDemo.showContainerListenerDemo();\n }\n\n private void prepareGUI(){\n mainFrame = new Frame(\"Java AWT Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n \n headerLabel = new Label();\n headerLabel.setAlignment(Label.CENTER);\n statusLabel = new Label(); \n statusLabel.setAlignment(Label.CENTER);\n statusLabel.setSize(350,100);\n\n controlPanel = new Panel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n\n private void showContainerListenerDemo(){\n headerLabel.setText(\"Listener in action: ContainerListener\"); \n\n ScrollPane panel = new ScrollPane(); \n panel.setBackground(Color.magenta); \n panel.addContainerListener(new CustomContainerListener()); \n\n Label msglabel = new Label();\n msglabel.setAlignment(Label.CENTER);\n msglabel.setText(\"Welcome to TutorialsPoint AWT Tutorial.\");\n panel.add(msglabel);\n \n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n\n class CustomContainerListener implements ContainerListener {\n public void componentAdded(ContainerEvent e) {\n statusLabel.setText(statusLabel.getText() \n + e.getComponent().getClass().getSimpleName() + \" added. \");\n }\n\n public void componentRemoved(ContainerEvent e) {\n statusLabel.setText(statusLabel.getText() \n + e.getComponent().getClass().getSimpleName() + \" removed. \");\n }\n }\n}"
},
{
"code": null,
"e": 4760,
"s": 4669,
"text": "Compile the program using command prompt. Go to D:/ > AWT and type the following command."
},
{
"code": null,
"e": 4817,
"s": 4760,
"text": "D:\\AWT>javac com\\tutorialspoint\\gui\\AwtListenerDemo.java"
},
{
"code": null,
"e": 4914,
"s": 4817,
"text": "If no error comes that means compilation is successful. Run the program using following command."
},
{
"code": null,
"e": 4965,
"s": 4914,
"text": "D:\\AWT>java com.tutorialspoint.gui.AwtListenerDemo"
},
{
"code": null,
"e": 4993,
"s": 4965,
"text": "Verify the following output"
},
{
"code": null,
"e": 5026,
"s": 4993,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5034,
"s": 5026,
"text": " EduOLC"
},
{
"code": null,
"e": 5041,
"s": 5034,
"text": " Print"
},
{
"code": null,
"e": 5052,
"s": 5041,
"text": " Add Notes"
}
] |
Count squares of size K inscribed in a square of size N - GeeksforGeeks
|
16 Apr, 2021
Given two integers N and K, the task is to find the number of squares of size K that is inscribed in a square of size N.
Examples:
Input: N = 4, K = 2Output: 9Explanation:There are 9 squares of size 2 inscribed in a square of size 4.
Input: N = 5, K = 3Output: 9Explanation:There are 9 squares of size 3 inscribed in a square of size 5.
Approach: The key observation to solve the problem is that the total number of squares in a square of size N is (N * (N + 1)* (2*N + 1)) / 6. Therefore, the total number of squares of size K possible from a square of size N are:
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the// above approach #include <iostream>using namespace std; // Function to calculate the number// of squares of size K in a square// of size Nint No_of_squares(int N, int K){ // Stores the number of squares int no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver Codeint main(){ // Size of the // bigger square int N = 5; // Size of // smaller square int K = 3; cout << No_of_squares(N, K); return 0;}
// Java implementation of the// above approachimport java.util.*;class GFG{ // Function to calculate the// number of squares of size// K in a square of size Nstatic int No_of_squares(int N, int K){ // Stores the number // of squares int no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver Codepublic static void main(String[] args){ // Size of the // bigger square int N = 5; // Size of // smaller square int K = 3; System.out.print(No_of_squares(N, K));}} // This code is contributed by Princi Singh
# Python3 implementation of the# above approach # Function to calculate the# number of squares of size# K in a square of size Ndef No_of_squares(N, K): # Stores the number # of squares no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares; # Driver Codeif __name__ == '__main__': # Size of the # bigger square N = 5; # Size of # smaller square K = 3; print(No_of_squares(N, K)); # This code is contributed by 29AjayKumar
// C# implementation of the// above approachusing System; class GFG{ // Function to calculate the// number of squares of size// K in a square of size Nstatic int No_of_squares(int N, int K){ // Stores the number // of squares int no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver Codepublic static void Main(String[] args){ // Size of the // bigger square int N = 5; // Size of // smaller square int K = 3; Console.Write(No_of_squares(N, K));}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for// the above approach // Function to calculate the// number of squares of size// K in a square of size Nfunction No_of_squares(N, K){ // Stores the number // of squares let no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver code // Size of the // bigger square let N = 5; // Size of // smaller square let K = 3; document.write(No_of_squares(N, K)); // This code is contributed by splevel62.</script>
9
Time Complexity: O(1) Auxiliary Space: O(1)
princi singh
amit143katiyar
29AjayKumar
splevel62
square-rectangle
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Closest Pair of Points | O(nlogn) Implementation
Program to find line passing through 2 Points
Maximum distance between two points in coordinate plane using Rotating Caliper's Method
Program to find area of a triangle
Quickhull Algorithm for Convex Hull
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Program to find GCD or HCF of two numbers
|
[
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 24972,
"s": 24851,
"text": "Given two integers N and K, the task is to find the number of squares of size K that is inscribed in a square of size N."
},
{
"code": null,
"e": 24982,
"s": 24972,
"text": "Examples:"
},
{
"code": null,
"e": 25085,
"s": 24982,
"text": "Input: N = 4, K = 2Output: 9Explanation:There are 9 squares of size 2 inscribed in a square of size 4."
},
{
"code": null,
"e": 25188,
"s": 25085,
"text": "Input: N = 5, K = 3Output: 9Explanation:There are 9 squares of size 3 inscribed in a square of size 5."
},
{
"code": null,
"e": 25417,
"s": 25188,
"text": "Approach: The key observation to solve the problem is that the total number of squares in a square of size N is (N * (N + 1)* (2*N + 1)) / 6. Therefore, the total number of squares of size K possible from a square of size N are:"
},
{
"code": null,
"e": 25468,
"s": 25417,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 25472,
"s": 25468,
"text": "C++"
},
{
"code": null,
"e": 25477,
"s": 25472,
"text": "Java"
},
{
"code": null,
"e": 25485,
"s": 25477,
"text": "Python3"
},
{
"code": null,
"e": 25488,
"s": 25485,
"text": "C#"
},
{
"code": null,
"e": 25499,
"s": 25488,
"text": "Javascript"
},
{
"code": "// C++ implementation of the// above approach #include <iostream>using namespace std; // Function to calculate the number// of squares of size K in a square// of size Nint No_of_squares(int N, int K){ // Stores the number of squares int no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver Codeint main(){ // Size of the // bigger square int N = 5; // Size of // smaller square int K = 3; cout << No_of_squares(N, K); return 0;}",
"e": 26016,
"s": 25499,
"text": null
},
{
"code": "// Java implementation of the// above approachimport java.util.*;class GFG{ // Function to calculate the// number of squares of size// K in a square of size Nstatic int No_of_squares(int N, int K){ // Stores the number // of squares int no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver Codepublic static void main(String[] args){ // Size of the // bigger square int N = 5; // Size of // smaller square int K = 3; System.out.print(No_of_squares(N, K));}} // This code is contributed by Princi Singh",
"e": 26616,
"s": 26016,
"text": null
},
{
"code": "# Python3 implementation of the# above approach # Function to calculate the# number of squares of size# K in a square of size Ndef No_of_squares(N, K): # Stores the number # of squares no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares; # Driver Codeif __name__ == '__main__': # Size of the # bigger square N = 5; # Size of # smaller square K = 3; print(No_of_squares(N, K)); # This code is contributed by 29AjayKumar",
"e": 27109,
"s": 26616,
"text": null
},
{
"code": "// C# implementation of the// above approachusing System; class GFG{ // Function to calculate the// number of squares of size// K in a square of size Nstatic int No_of_squares(int N, int K){ // Stores the number // of squares int no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver Codepublic static void Main(String[] args){ // Size of the // bigger square int N = 5; // Size of // smaller square int K = 3; Console.Write(No_of_squares(N, K));}} // This code is contributed by Amit Katiyar",
"e": 27728,
"s": 27109,
"text": null
},
{
"code": "<script> // JavaScript program for// the above approach // Function to calculate the// number of squares of size// K in a square of size Nfunction No_of_squares(N, K){ // Stores the number // of squares let no_of_squares = 0; no_of_squares = (N - K + 1) * (N - K + 1); return no_of_squares;} // Driver code // Size of the // bigger square let N = 5; // Size of // smaller square let K = 3; document.write(No_of_squares(N, K)); // This code is contributed by splevel62.</script>",
"e": 28248,
"s": 27728,
"text": null
},
{
"code": null,
"e": 28250,
"s": 28248,
"text": "9"
},
{
"code": null,
"e": 28294,
"s": 28250,
"text": "Time Complexity: O(1) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28307,
"s": 28294,
"text": "princi singh"
},
{
"code": null,
"e": 28322,
"s": 28307,
"text": "amit143katiyar"
},
{
"code": null,
"e": 28334,
"s": 28322,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28344,
"s": 28334,
"text": "splevel62"
},
{
"code": null,
"e": 28361,
"s": 28344,
"text": "square-rectangle"
},
{
"code": null,
"e": 28371,
"s": 28361,
"text": "Geometric"
},
{
"code": null,
"e": 28384,
"s": 28371,
"text": "Mathematical"
},
{
"code": null,
"e": 28397,
"s": 28384,
"text": "Mathematical"
},
{
"code": null,
"e": 28407,
"s": 28397,
"text": "Geometric"
},
{
"code": null,
"e": 28505,
"s": 28407,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28514,
"s": 28505,
"text": "Comments"
},
{
"code": null,
"e": 28527,
"s": 28514,
"text": "Old Comments"
},
{
"code": null,
"e": 28576,
"s": 28527,
"text": "Closest Pair of Points | O(nlogn) Implementation"
},
{
"code": null,
"e": 28622,
"s": 28576,
"text": "Program to find line passing through 2 Points"
},
{
"code": null,
"e": 28710,
"s": 28622,
"text": "Maximum distance between two points in coordinate plane using Rotating Caliper's Method"
},
{
"code": null,
"e": 28745,
"s": 28710,
"text": "Program to find area of a triangle"
},
{
"code": null,
"e": 28781,
"s": 28745,
"text": "Quickhull Algorithm for Convex Hull"
},
{
"code": null,
"e": 28841,
"s": 28781,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 28856,
"s": 28841,
"text": "C++ Data Types"
},
{
"code": null,
"e": 28899,
"s": 28856,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28923,
"s": 28899,
"text": "Merge two sorted arrays"
}
] |
JSF - Convertor Tags
|
JSF provides inbuilt convertors to convert its UI component's data to object used in a managed bean and vice versa. For example, these tags can convert a text into date object and can validate the format of input as well.
For these tags, you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">
Following are important Convertor Tags in JSF 2.0 −
Converts a String into a Number of desired format
Converts a String into a Date of desired format
Creating a custom convertor
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2174,
"s": 1952,
"text": "JSF provides inbuilt convertors to convert its UI component's data to object used in a managed bean and vice versa. For example, these tags can convert a text into date object and can validate the format of input as well."
},
{
"code": null,
"e": 2252,
"s": 2174,
"text": "For these tags, you need to use the following namespaces of URI in html node."
},
{
"code": null,
"e": 2347,
"s": 2252,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:f = \"http://java.sun.com/jsf/core\">"
},
{
"code": null,
"e": 2399,
"s": 2347,
"text": "Following are important Convertor Tags in JSF 2.0 −"
},
{
"code": null,
"e": 2449,
"s": 2399,
"text": "Converts a String into a Number of desired format"
},
{
"code": null,
"e": 2497,
"s": 2449,
"text": "Converts a String into a Date of desired format"
},
{
"code": null,
"e": 2525,
"s": 2497,
"text": "Creating a custom convertor"
},
{
"code": null,
"e": 2560,
"s": 2525,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2575,
"s": 2560,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 2582,
"s": 2575,
"text": " Print"
},
{
"code": null,
"e": 2593,
"s": 2582,
"text": " Add Notes"
}
] |
C++ program to compare two Strings using Operator Overloading - GeeksforGeeks
|
18 May, 2021
Pre-requisite: Operator Overloading in C++Given two strings, how to check if the two strings are equal or not, using Operator Overloading.
Examples:
Input: ABCD, XYZ
Output: ABCD is not equal to XYZ
ABCD is greater than XYZ
Input: Geeks, Geeks
Output: Geeks is equal to Geeks
Approach: Using binary operator overloading.
Declare a class with a string variable and operator function ‘==’, ‘<=’ and ‘>=’ that accepts an instance of the class and compares it’s variable with the string variable of the current instance.
Create two instances of the class and initialize their class variables with the two input strings respectively.
Now, use the overloaded operator(==, <= and >=) function to compare the class variable of the two instances.
Below is the implementation of the above approach:
C++
// C++ program to compare two Strings// using Operator Overloading #include <cstring>#include <iostream>#include <string.h> using namespace std; // Class to implement operator overloading// function for concatenating the stringsclass CompareString { public: // Classes object of string char str[25]; // Parameterized Constructor CompareString(char str1[]) { // Initialize the string to class object strcpy(this->str, str1); } // Overloading '==' under a function // which returns integer 1/true // if left operand string // and right operand string are equal. //(else return 0/false) int operator==(CompareString s2) { if (strcmp(str, s2.str) == 0) return 1; else return 0; } // Overloading '<=' under a function // which returns integer 1/true // if left operand string is smaller than // or equal to the right operand string. // (else return 0/false) int operator<=(CompareString s3) { if (strlen(str) <= strlen(s3.str)) return 1; else return 0; } // Overloading '>=' under a function // which returns integer 1/true // if left operand string is larger than // or equal to the right operand string. //(else return 0/false) int operator>=(CompareString s3) { if (strlen(str) >= strlen(s3.str)) return 1; else return 0; }}; void compare(CompareString s1, CompareString s2){ if (s1 == s2) cout << s1.str << " is equal to " << s2.str << endl; else { cout << s1.str << " is not equal to " << s2.str << endl; if (s1 >= s2) cout << s1.str << " is greater than " << s2.str << endl; else cout << s2.str << " is greater than " << s1.str << endl; }} // Testcase1void testcase1(){ // Declaring two strings char str1[] = "Geeks"; char str2[] = "ForGeeks"; // Declaring and initializing the class // with above two strings CompareString s1(str1); CompareString s2(str2); cout << "Comparing \"" << s1.str << "\" and \"" << s2.str << "\"" << endl; compare(s1, s2);} // Testcase2void testcase2(){ // Declaring two strings char str1[] = "Geeks"; char str2[] = "Geeks"; // Declaring and initializing the class // with above two strings CompareString s1(str1); CompareString s2(str2); cout << "\n\nComparing \"" << s1.str << "\" and \"" << s2.str << "\"" << endl; compare(s1, s2);} // Driver codeint main(){ testcase1(); testcase2(); return 0;}
Comparing "Geeks" and "ForGeeks"
Geeks is not equal to ForGeeks
ForGeeks is greater than Geeks
Comparing "Geeks" and "Geeks"
Geeks is equal to Geeks
saurabh1990aror
cpp-operator-overloading
cpp-overloading
Operator Overloading
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Bitwise Operators in C/C++
Socket Programming in C/C++
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 25106,
"s": 25078,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 25245,
"s": 25106,
"text": "Pre-requisite: Operator Overloading in C++Given two strings, how to check if the two strings are equal or not, using Operator Overloading."
},
{
"code": null,
"e": 25256,
"s": 25245,
"text": "Examples: "
},
{
"code": null,
"e": 25392,
"s": 25256,
"text": "Input: ABCD, XYZ\nOutput: ABCD is not equal to XYZ\n ABCD is greater than XYZ\n\nInput: Geeks, Geeks\nOutput: Geeks is equal to Geeks"
},
{
"code": null,
"e": 25438,
"s": 25392,
"text": "Approach: Using binary operator overloading. "
},
{
"code": null,
"e": 25634,
"s": 25438,
"text": "Declare a class with a string variable and operator function ‘==’, ‘<=’ and ‘>=’ that accepts an instance of the class and compares it’s variable with the string variable of the current instance."
},
{
"code": null,
"e": 25746,
"s": 25634,
"text": "Create two instances of the class and initialize their class variables with the two input strings respectively."
},
{
"code": null,
"e": 25855,
"s": 25746,
"text": "Now, use the overloaded operator(==, <= and >=) function to compare the class variable of the two instances."
},
{
"code": null,
"e": 25907,
"s": 25855,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25911,
"s": 25907,
"text": "C++"
},
{
"code": "// C++ program to compare two Strings// using Operator Overloading #include <cstring>#include <iostream>#include <string.h> using namespace std; // Class to implement operator overloading// function for concatenating the stringsclass CompareString { public: // Classes object of string char str[25]; // Parameterized Constructor CompareString(char str1[]) { // Initialize the string to class object strcpy(this->str, str1); } // Overloading '==' under a function // which returns integer 1/true // if left operand string // and right operand string are equal. //(else return 0/false) int operator==(CompareString s2) { if (strcmp(str, s2.str) == 0) return 1; else return 0; } // Overloading '<=' under a function // which returns integer 1/true // if left operand string is smaller than // or equal to the right operand string. // (else return 0/false) int operator<=(CompareString s3) { if (strlen(str) <= strlen(s3.str)) return 1; else return 0; } // Overloading '>=' under a function // which returns integer 1/true // if left operand string is larger than // or equal to the right operand string. //(else return 0/false) int operator>=(CompareString s3) { if (strlen(str) >= strlen(s3.str)) return 1; else return 0; }}; void compare(CompareString s1, CompareString s2){ if (s1 == s2) cout << s1.str << \" is equal to \" << s2.str << endl; else { cout << s1.str << \" is not equal to \" << s2.str << endl; if (s1 >= s2) cout << s1.str << \" is greater than \" << s2.str << endl; else cout << s2.str << \" is greater than \" << s1.str << endl; }} // Testcase1void testcase1(){ // Declaring two strings char str1[] = \"Geeks\"; char str2[] = \"ForGeeks\"; // Declaring and initializing the class // with above two strings CompareString s1(str1); CompareString s2(str2); cout << \"Comparing \\\"\" << s1.str << \"\\\" and \\\"\" << s2.str << \"\\\"\" << endl; compare(s1, s2);} // Testcase2void testcase2(){ // Declaring two strings char str1[] = \"Geeks\"; char str2[] = \"Geeks\"; // Declaring and initializing the class // with above two strings CompareString s1(str1); CompareString s2(str2); cout << \"\\n\\nComparing \\\"\" << s1.str << \"\\\" and \\\"\" << s2.str << \"\\\"\" << endl; compare(s1, s2);} // Driver codeint main(){ testcase1(); testcase2(); return 0;}",
"e": 28556,
"s": 25911,
"text": null
},
{
"code": null,
"e": 28707,
"s": 28556,
"text": "Comparing \"Geeks\" and \"ForGeeks\"\nGeeks is not equal to ForGeeks\nForGeeks is greater than Geeks\n\n\nComparing \"Geeks\" and \"Geeks\"\nGeeks is equal to Geeks"
},
{
"code": null,
"e": 28725,
"s": 28709,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 28750,
"s": 28725,
"text": "cpp-operator-overloading"
},
{
"code": null,
"e": 28766,
"s": 28750,
"text": "cpp-overloading"
},
{
"code": null,
"e": 28787,
"s": 28766,
"text": "Operator Overloading"
},
{
"code": null,
"e": 28791,
"s": 28787,
"text": "C++"
},
{
"code": null,
"e": 28799,
"s": 28791,
"text": "Strings"
},
{
"code": null,
"e": 28807,
"s": 28799,
"text": "Strings"
},
{
"code": null,
"e": 28811,
"s": 28807,
"text": "CPP"
},
{
"code": null,
"e": 28909,
"s": 28811,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28928,
"s": 28909,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28971,
"s": 28928,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 28995,
"s": 28971,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29022,
"s": 28995,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 29050,
"s": 29022,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 29075,
"s": 29050,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 29121,
"s": 29075,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 29155,
"s": 29121,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 29215,
"s": 29155,
"text": "Write a program to print all permutations of a given string"
}
] |
How to change the color of a Tkinter rectangle on clicking?
|
The Canvas widget is one of the most versatile widgets in the Tkinter Library. It is used for creating shapes of different types and sizes, animating objects, visualizing graphics, and many more. To change the property of a particular item in Tkinter, we can use itemconfig(**options) method. It takes options such as background color, outline color, and other useful properties of the items defined in a canvas.
In this example, we will create a rectangle such that the color inside the rectangle would change after clicking a Button.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry
win.geometry("700x300")
# Define a function to change the state of the Widget
def change_color():
canvas.itemconfig(rectangle, fill='green')
# Define a Canvas Widget
canvas = Canvas(win, width=500, height=240)
canvas.pack()
# Create a rectangle in Canvas
rectangle = canvas.create_rectangle(100, 100, 400, 400, fill='blue')
# Create a Button to Disable the Combobox Widget
ttk.Button(win, text="Change Color", command=change_color).pack()
win.mainloop()
When you run the above code, it will display a window with a blue-colored rectangle at the center.
Now, click the "Change Color" button. It will change the color of the rectangle to green.
|
[
{
"code": null,
"e": 1475,
"s": 1062,
"text": "The Canvas widget is one of the most versatile widgets in the Tkinter Library. It is used for creating shapes of different types and sizes, animating objects, visualizing graphics, and many more. To change the property of a particular item in Tkinter, we can use itemconfig(**options) method. It takes options such as background color, outline color, and other useful properties of the items defined in a canvas."
},
{
"code": null,
"e": 1598,
"s": 1475,
"text": "In this example, we will create a rectangle such that the color inside the rectangle would change after clicking a Button."
},
{
"code": null,
"e": 2207,
"s": 1598,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of Tkinter Frame\nwin = Tk()\n\n# Set the geometry\nwin.geometry(\"700x300\")\n\n# Define a function to change the state of the Widget\ndef change_color():\n canvas.itemconfig(rectangle, fill='green')\n\n# Define a Canvas Widget\ncanvas = Canvas(win, width=500, height=240)\ncanvas.pack()\n\n# Create a rectangle in Canvas\nrectangle = canvas.create_rectangle(100, 100, 400, 400, fill='blue')\n\n# Create a Button to Disable the Combobox Widget\nttk.Button(win, text=\"Change Color\", command=change_color).pack()\nwin.mainloop()"
},
{
"code": null,
"e": 2306,
"s": 2207,
"text": "When you run the above code, it will display a window with a blue-colored rectangle at the center."
},
{
"code": null,
"e": 2396,
"s": 2306,
"text": "Now, click the \"Change Color\" button. It will change the color of the rectangle to green."
}
] |
Check if a number can be expressed as a product of exactly K prime divisors - GeeksforGeeks
|
17 Nov, 2021
Given an integer N, the task is to check if it can be expressed as a product of exactly K prime divisors. Examples:
Input: N = 12, K = 3
Output: Yes
Explanation:
12 can be expressed as product of 2×2×3.
Input: N = 14, K = 3
Output: No
Explanation:
14 can be only expressed as product of 2×7.
Approach:To solve the problem mentioned above we are given the value N and we will find the maximum number of values we can split N into. We can represent prime factorization of N as where pi are the prime factors of N and ai are the exponents. We know that total number of divisors of N is . Therefore, we can observe that we have to check whether it is possible to represent N as product of K numbers or not. If the maximum split is less than K then it is not possible to express it in exactly K prime divisors, else it is always possible.
C++
Java
Python3
C#
Javascript
// CPP implementation to Check if a// number can be expressed as a// product of exactly K prime divisors #include <bits/stdc++.h>using namespace std; // function to find K prime divisorsvoid KPrimeDivisors(int N, int K){ int maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { printf("No\n"); return; } printf("Yes\n");} /* Driver code */int main(){ // initialise N and K int N = 12; int K = 3; KPrimeDivisors(N, K); return 0;}
// Java implementation to Check if a// number can be expressed as a// product of exactly K prime divisorsclass GFG { // function to find K prime divisors static void KPrimeDivisors(int N, int K) { int maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { System.out.println("No"); return; } System.out.println("Yes"); } /* Driver code */ public static void main (String[] args) { // initialise N and K int N = 12; int K = 3; KPrimeDivisors(N, K); }} // This code is contributed by Yash_R
# Python implementation to Check if a# number can be expressed as a# product of exactly K prime divisors import math as mt # function to find K prime divisorsdef KPrimeDivisors(n, k): # To count maximum split of N maximum_split = 0 # count number of 2s that divide N while n % 2 == 0: maximum_split+= 1 n = n // 2 # n must be odd at this point # so we skip one element for i in range(3, mt.ceil(mt.sqrt(n)), 2): while n % i == 0: n = n / i; maximum_split+= 1 # Condition to handle the case when n # is a prime number greater than 2 if n > 2: maximum_split+= 1 # check if maximum_split is less than K # then it not possible if maximum_split < k: print("No") return print("Yes") # Driver codeN = 12K = 3KPrimeDivisors(N, K)
// C# implementation to Check if a// number can be expressed as a// product of exactly K prime divisorsusing System; class GFG { // function to find K prime divisors static void KPrimeDivisors(int N, int K) { int maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { Console.WriteLine("No"); return; } Console.WriteLine("Yes"); } /* Driver code */ public static void Main(String[] args) { // initialise N and K int N = 12; int K = 3; KPrimeDivisors(N, K); }} // This code is contributed by 29AjayKumar
<script>// javascript implementation to Check if a// number can be expressed as a// product of exactly K prime divisors // function to find K prime divisors function KPrimeDivisors(N , K) { var maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { document.write("No"); return; } document.write("Yes"); } /* Driver code */ // initialise N and K var N = 12; var K = 3; KPrimeDivisors(N, K); // This code is contributed by gauravrajput1.</script>
Yes
Time Complexity: O(sqrt(N))
Auxiliary Space: O(1)
Yash_R
29AjayKumar
GauravRajput1
rishavmahato348
prime-factor
Algorithms
Greedy
Mathematical
Greedy
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
How to write a Pseudo Code?
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Program for array rotation
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 25244,
"s": 25216,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25361,
"s": 25244,
"text": "Given an integer N, the task is to check if it can be expressed as a product of exactly K prime divisors. Examples: "
},
{
"code": null,
"e": 25539,
"s": 25361,
"text": "Input: N = 12, K = 3\nOutput: Yes\nExplanation:\n12 can be expressed as product of 2×2×3.\n\nInput: N = 14, K = 3\nOutput: No\nExplanation:\n14 can be only expressed as product of 2×7."
},
{
"code": null,
"e": 26084,
"s": 25541,
"text": "Approach:To solve the problem mentioned above we are given the value N and we will find the maximum number of values we can split N into. We can represent prime factorization of N as where pi are the prime factors of N and ai are the exponents. We know that total number of divisors of N is . Therefore, we can observe that we have to check whether it is possible to represent N as product of K numbers or not. If the maximum split is less than K then it is not possible to express it in exactly K prime divisors, else it is always possible. "
},
{
"code": null,
"e": 26088,
"s": 26084,
"text": "C++"
},
{
"code": null,
"e": 26093,
"s": 26088,
"text": "Java"
},
{
"code": null,
"e": 26101,
"s": 26093,
"text": "Python3"
},
{
"code": null,
"e": 26104,
"s": 26101,
"text": "C#"
},
{
"code": null,
"e": 26115,
"s": 26104,
"text": "Javascript"
},
{
"code": "// CPP implementation to Check if a// number can be expressed as a// product of exactly K prime divisors #include <bits/stdc++.h>using namespace std; // function to find K prime divisorsvoid KPrimeDivisors(int N, int K){ int maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { printf(\"No\\n\"); return; } printf(\"Yes\\n\");} /* Driver code */int main(){ // initialise N and K int N = 12; int K = 3; KPrimeDivisors(N, K); return 0;}",
"e": 27152,
"s": 26115,
"text": null
},
{
"code": "// Java implementation to Check if a// number can be expressed as a// product of exactly K prime divisorsclass GFG { // function to find K prime divisors static void KPrimeDivisors(int N, int K) { int maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { System.out.println(\"No\"); return; } System.out.println(\"Yes\"); } /* Driver code */ public static void main (String[] args) { // initialise N and K int N = 12; int K = 3; KPrimeDivisors(N, K); }} // This code is contributed by Yash_R",
"e": 28433,
"s": 27152,
"text": null
},
{
"code": "# Python implementation to Check if a# number can be expressed as a# product of exactly K prime divisors import math as mt # function to find K prime divisorsdef KPrimeDivisors(n, k): # To count maximum split of N maximum_split = 0 # count number of 2s that divide N while n % 2 == 0: maximum_split+= 1 n = n // 2 # n must be odd at this point # so we skip one element for i in range(3, mt.ceil(mt.sqrt(n)), 2): while n % i == 0: n = n / i; maximum_split+= 1 # Condition to handle the case when n # is a prime number greater than 2 if n > 2: maximum_split+= 1 # check if maximum_split is less than K # then it not possible if maximum_split < k: print(\"No\") return print(\"Yes\") # Driver codeN = 12K = 3KPrimeDivisors(N, K)",
"e": 29317,
"s": 28433,
"text": null
},
{
"code": "// C# implementation to Check if a// number can be expressed as a// product of exactly K prime divisorsusing System; class GFG { // function to find K prime divisors static void KPrimeDivisors(int N, int K) { int maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { Console.WriteLine(\"No\"); return; } Console.WriteLine(\"Yes\"); } /* Driver code */ public static void Main(String[] args) { // initialise N and K int N = 12; int K = 3; KPrimeDivisors(N, K); }} // This code is contributed by 29AjayKumar",
"e": 30623,
"s": 29317,
"text": null
},
{
"code": "<script>// javascript implementation to Check if a// number can be expressed as a// product of exactly K prime divisors // function to find K prime divisors function KPrimeDivisors(N , K) { var maximum_split = 0; // count number of 2s that divide N while (N % 2 == 0) { maximum_split++; N /= 2; } // N must be odd at this point. // So we can skip one element for (i = 3; i * i <= N; i = i + 2) { while (N % i == 0) { // divide the value of N N = N / i; // increment count maximum_split++; } } // Condition to handle the case when n // is a prime number greater than 2 if (N > 2) maximum_split++; // check if maximum_split is less than K // then it not possible if (maximum_split < K) { document.write(\"No\"); return; } document.write(\"Yes\"); } /* Driver code */ // initialise N and K var N = 12; var K = 3; KPrimeDivisors(N, K); // This code is contributed by gauravrajput1.</script>",
"e": 31857,
"s": 30623,
"text": null
},
{
"code": null,
"e": 31861,
"s": 31857,
"text": "Yes"
},
{
"code": null,
"e": 31891,
"s": 31863,
"text": "Time Complexity: O(sqrt(N))"
},
{
"code": null,
"e": 31914,
"s": 31891,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 31921,
"s": 31914,
"text": "Yash_R"
},
{
"code": null,
"e": 31933,
"s": 31921,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31947,
"s": 31933,
"text": "GauravRajput1"
},
{
"code": null,
"e": 31963,
"s": 31947,
"text": "rishavmahato348"
},
{
"code": null,
"e": 31976,
"s": 31963,
"text": "prime-factor"
},
{
"code": null,
"e": 31987,
"s": 31976,
"text": "Algorithms"
},
{
"code": null,
"e": 31994,
"s": 31987,
"text": "Greedy"
},
{
"code": null,
"e": 32007,
"s": 31994,
"text": "Mathematical"
},
{
"code": null,
"e": 32014,
"s": 32007,
"text": "Greedy"
},
{
"code": null,
"e": 32027,
"s": 32014,
"text": "Mathematical"
},
{
"code": null,
"e": 32038,
"s": 32027,
"text": "Algorithms"
},
{
"code": null,
"e": 32136,
"s": 32038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32185,
"s": 32136,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 32210,
"s": 32185,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32261,
"s": 32210,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 32288,
"s": 32261,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 32316,
"s": 32288,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 32367,
"s": 32316,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 32425,
"s": 32367,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 32476,
"s": 32425,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 32503,
"s": 32476,
"text": "Program for array rotation"
}
] |
C# - Nullables
|
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows −
< data_type> ? <variable_name> = null;
The following example demonstrates use of nullable data types −
using System;
namespace CalculatorApplication {
class NullablesAtShow {
static void Main(string[] args) {
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolval = new bool?();
// display the values
Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4);
Console.WriteLine("A Nullable boolean value: {0}", boolval);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Nullables at Show: , 45, , 3.14157
A Nullable boolean value:
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this −
using System;
namespace CalculatorApplication {
class NullablesAtShow {
static void Main(string[] args) {
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result −
Value of num3: 5.34
Value of num3: 3.14157
119 Lectures
23.5 hours
Raja Biswas
37 Lectures
13 hours
Trevoir Williams
16 Lectures
1 hours
Peter Jepson
159 Lectures
21.5 hours
Ebenezer Ogbu
193 Lectures
17 hours
Arnold Higuit
24 Lectures
2.5 hours
Eric Frick
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2395,
"s": 2270,
"text": "C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values."
},
{
"code": null,
"e": 2638,
"s": 2395,
"text": "For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows −"
},
{
"code": null,
"e": 2678,
"s": 2638,
"text": "< data_type> ? <variable_name> = null;\n"
},
{
"code": null,
"e": 2742,
"s": 2678,
"text": "The following example demonstrates use of nullable data types −"
},
{
"code": null,
"e": 3279,
"s": 2742,
"text": "using System;\n\nnamespace CalculatorApplication {\n class NullablesAtShow {\n static void Main(string[] args) {\n int? num1 = null;\n int? num2 = 45;\n \n double? num3 = new double?();\n double? num4 = 3.14157;\n \n bool? boolval = new bool?();\n\n // display the values\n Console.WriteLine(\"Nullables at Show: {0}, {1}, {2}, {3}\", num1, num2, num3, num4);\n Console.WriteLine(\"A Nullable boolean value: {0}\", boolval);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 3360,
"s": 3279,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3423,
"s": 3360,
"text": "Nullables at Show: , 45, , 3.14157\nA Nullable boolean value:\n"
},
{
"code": null,
"e": 3651,
"s": 3423,
"text": "The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible."
},
{
"code": null,
"e": 3844,
"s": 3651,
"text": "If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this −"
},
{
"code": null,
"e": 4289,
"s": 3844,
"text": "using System;\n\nnamespace CalculatorApplication {\n class NullablesAtShow {\n static void Main(string[] args) {\n double? num1 = null;\n double? num2 = 3.14157;\n double num3;\n \n num3 = num1 ?? 5.34; \n Console.WriteLine(\" Value of num3: {0}\", num3);\n \n num3 = num2 ?? 5.34;\n Console.WriteLine(\" Value of num3: {0}\", num3);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 4370,
"s": 4289,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4414,
"s": 4370,
"text": "Value of num3: 5.34\nValue of num3: 3.14157\n"
},
{
"code": null,
"e": 4451,
"s": 4414,
"text": "\n 119 Lectures \n 23.5 hours \n"
},
{
"code": null,
"e": 4464,
"s": 4451,
"text": " Raja Biswas"
},
{
"code": null,
"e": 4498,
"s": 4464,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4516,
"s": 4498,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4549,
"s": 4516,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4563,
"s": 4549,
"text": " Peter Jepson"
},
{
"code": null,
"e": 4600,
"s": 4563,
"text": "\n 159 Lectures \n 21.5 hours \n"
},
{
"code": null,
"e": 4615,
"s": 4600,
"text": " Ebenezer Ogbu"
},
{
"code": null,
"e": 4650,
"s": 4615,
"text": "\n 193 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 4665,
"s": 4650,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 4700,
"s": 4665,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4712,
"s": 4700,
"text": " Eric Frick"
},
{
"code": null,
"e": 4719,
"s": 4712,
"text": " Print"
},
{
"code": null,
"e": 4730,
"s": 4719,
"text": " Add Notes"
}
] |
Program to find average salary excluding the minimum and maximum salary in Python
|
Suppoe we have an array with distinct elements called salary where salary[i] is the salary of ith employee. We have to find the average salary of employees excluding the minimum and maximum salary.
So, if the input is like salary = [8000,6000,2000,8500,2500,4000], then the output will be 5125.0, as the minimum and maximum salary values are 2000 and 8500, so excluding them the average salary values are [8000,6000,2500,4000] so the average is (8000 + 6000 + 2500 + 4000)/4 = 5125.
To solve this, we will follow these steps −
delete minimum of salary from salary
delete minimum of salary from salary
delete maximum of salary from salary
delete maximum of salary from salary
return sum of the salary values / number of elements in salary after removal
return sum of the salary values / number of elements in salary after removal
Let us see the following implementation to get better understanding −
Live Demo
def solve(salary):
salary.remove(min(salary))
salary.remove(max(salary))
return sum(salary)/len(salary)
salary = [8000,6000,2000,8500,2500,4000]
print(solve(salary))
[8000,6000,2000,8500,2500,4000]
5125.0
|
[
{
"code": null,
"e": 1260,
"s": 1062,
"text": "Suppoe we have an array with distinct elements called salary where salary[i] is the salary of ith employee. We have to find the average salary of employees excluding the minimum and maximum salary."
},
{
"code": null,
"e": 1545,
"s": 1260,
"text": "So, if the input is like salary = [8000,6000,2000,8500,2500,4000], then the output will be 5125.0, as the minimum and maximum salary values are 2000 and 8500, so excluding them the average salary values are [8000,6000,2500,4000] so the average is (8000 + 6000 + 2500 + 4000)/4 = 5125."
},
{
"code": null,
"e": 1589,
"s": 1545,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1626,
"s": 1589,
"text": "delete minimum of salary from salary"
},
{
"code": null,
"e": 1663,
"s": 1626,
"text": "delete minimum of salary from salary"
},
{
"code": null,
"e": 1700,
"s": 1663,
"text": "delete maximum of salary from salary"
},
{
"code": null,
"e": 1737,
"s": 1700,
"text": "delete maximum of salary from salary"
},
{
"code": null,
"e": 1814,
"s": 1737,
"text": "return sum of the salary values / number of elements in salary after removal"
},
{
"code": null,
"e": 1891,
"s": 1814,
"text": "return sum of the salary values / number of elements in salary after removal"
},
{
"code": null,
"e": 1961,
"s": 1891,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1972,
"s": 1961,
"text": " Live Demo"
},
{
"code": null,
"e": 2148,
"s": 1972,
"text": "def solve(salary):\n salary.remove(min(salary))\n salary.remove(max(salary))\n return sum(salary)/len(salary)\n\nsalary = [8000,6000,2000,8500,2500,4000]\nprint(solve(salary))"
},
{
"code": null,
"e": 2180,
"s": 2148,
"text": "[8000,6000,2000,8500,2500,4000]"
},
{
"code": null,
"e": 2187,
"s": 2180,
"text": "5125.0"
}
] |
Selenium - Log4j Logging
|
Log4j is an audit logging framework that gives information about what has happened during execution. It offers the following advantages −
Enables us to understand the application run.
Enables us to understand the application run.
Log output can be saved that can be analyzed later.
Log output can be saved that can be analyzed later.
Helps in debugging, in case of test automation failures.
Helps in debugging, in case of test automation failures.
Can also be used for auditing purposes to look at the application's health.
Can also be used for auditing purposes to look at the application's health.
1. Instance of Logger class.
2. Log level methods used for logging the messages as one of the following −
error
warn
info
debug
log
Let us use the same percent calculator for this demo.
Step 1 − Download log4j JAR file from https://logging.apache.org/log4j/1.2/download.html and download the Zipped format of the JAR file.
Step 2 − Create 'New Java Project' by navigating to the File menu.
Step 3 − Enter the name of the project as 'log4j_demo' and click 'Next'.
Step 4 − Click Add External Jar and add 'Log4j-1.2.17.jar'.
Step 5 − Click Add External Jar and add Selenium WebDriver Libraries.
Step 6 − Click Add External Jar and add Selenium WebDriver JAR's located in the Libs folder.
Step 7 − Add a New XML file using which we can specify the Log4j properties.
Step 8 − Enter the Logfile name as 'Log4j.xml'.
Step 9 − The final folder structure is shown below.
Step 10 − Now add the properties of Log4j which would be picked up during execution.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j = "http://jakarta.apache.org/log4j/" debug = "false">
<appender name = "fileAppender" class = "org.apache.log4j.FileAppender">
<param name = "Threshold" value = "INFO" />
<param name = "File" value = "percent_calculator.log"/>
<layout class = "org.apache.log4j.PatternLayout">
<param name = "ConversionPattern"
value = "%d{yyyy-MM-dd HH:mm:ss} [%c] (%t:%x) %m%n" />
</layout>
</appender>
<root>
<level value = "INFO"/>
<appender-ref ref = "fileAppender"/>
</root>
</log4j:configuration>
Step 11 − Now for demonstration purpose, we will incorporate log4j in the same test that we have been performing (percent calculator). Add a class file in the 'Main' function.
package log4j_demo;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class log4j_demo {
static final Logger logger = LogManager.getLogger(log4j_demo.class.getName());
public static void main(String[] args) {
DOMConfigurator.configure("log4j.xml");
logger.info("# # # # # # # # # # # # # # # # # # # # # # # # # # # ");
logger.info("TEST Has Started");
WebDriver driver = new FirefoxDriver();
//Puts a Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net/");
logger.info("Open Calc Application");
//Maximize the browser
driver.manage().window().maximize();
//Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
logger.info("Clicked Math Calculator Link");
//Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
logger.info("Clicked Percent Calculator Link");
//Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
logger.info("Entered Value into First Text Box");
//Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
logger.info("Entered Value into Second Text Box");
//Click Calculate Button
driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click();
logger.info("Click Calculate Button");
//Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText();
logger.info("Get Text Value");
//Print a Log In message to the screen
logger.info(" The Result is " + result);
if(result.equals("5")) {
logger.info("The Result is Pass");
} else {
logger.error("TEST FAILED. NEEDS INVESTIGATION");
}
logger.info("# # # # # # # # # # # # # # # # # # # # # # # # # # # ");
//Close the Browser.
driver.close();
}
}
Upon execution, the log file is created on the root folder as shown below. You CANNOT locate the file in Eclipse. You should open 'Windows Explorer' to show the same.
The contents of the file is shown below.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2013,
"s": 1875,
"text": "Log4j is an audit logging framework that gives information about what has happened during execution. It offers the following advantages −"
},
{
"code": null,
"e": 2059,
"s": 2013,
"text": "Enables us to understand the application run."
},
{
"code": null,
"e": 2105,
"s": 2059,
"text": "Enables us to understand the application run."
},
{
"code": null,
"e": 2157,
"s": 2105,
"text": "Log output can be saved that can be analyzed later."
},
{
"code": null,
"e": 2209,
"s": 2157,
"text": "Log output can be saved that can be analyzed later."
},
{
"code": null,
"e": 2266,
"s": 2209,
"text": "Helps in debugging, in case of test automation failures."
},
{
"code": null,
"e": 2323,
"s": 2266,
"text": "Helps in debugging, in case of test automation failures."
},
{
"code": null,
"e": 2399,
"s": 2323,
"text": "Can also be used for auditing purposes to look at the application's health."
},
{
"code": null,
"e": 2475,
"s": 2399,
"text": "Can also be used for auditing purposes to look at the application's health."
},
{
"code": null,
"e": 2504,
"s": 2475,
"text": "1. Instance of Logger class."
},
{
"code": null,
"e": 2581,
"s": 2504,
"text": "2. Log level methods used for logging the messages as one of the following −"
},
{
"code": null,
"e": 2587,
"s": 2581,
"text": "error"
},
{
"code": null,
"e": 2592,
"s": 2587,
"text": "warn"
},
{
"code": null,
"e": 2597,
"s": 2592,
"text": "info"
},
{
"code": null,
"e": 2603,
"s": 2597,
"text": "debug"
},
{
"code": null,
"e": 2607,
"s": 2603,
"text": "log"
},
{
"code": null,
"e": 2661,
"s": 2607,
"text": "Let us use the same percent calculator for this demo."
},
{
"code": null,
"e": 2798,
"s": 2661,
"text": "Step 1 − Download log4j JAR file from https://logging.apache.org/log4j/1.2/download.html and download the Zipped format of the JAR file."
},
{
"code": null,
"e": 2865,
"s": 2798,
"text": "Step 2 − Create 'New Java Project' by navigating to the File menu."
},
{
"code": null,
"e": 2938,
"s": 2865,
"text": "Step 3 − Enter the name of the project as 'log4j_demo' and click 'Next'."
},
{
"code": null,
"e": 2998,
"s": 2938,
"text": "Step 4 − Click Add External Jar and add 'Log4j-1.2.17.jar'."
},
{
"code": null,
"e": 3068,
"s": 2998,
"text": "Step 5 − Click Add External Jar and add Selenium WebDriver Libraries."
},
{
"code": null,
"e": 3161,
"s": 3068,
"text": "Step 6 − Click Add External Jar and add Selenium WebDriver JAR's located in the Libs folder."
},
{
"code": null,
"e": 3238,
"s": 3161,
"text": "Step 7 − Add a New XML file using which we can specify the Log4j properties."
},
{
"code": null,
"e": 3286,
"s": 3238,
"text": "Step 8 − Enter the Logfile name as 'Log4j.xml'."
},
{
"code": null,
"e": 3338,
"s": 3286,
"text": "Step 9 − The final folder structure is shown below."
},
{
"code": null,
"e": 3423,
"s": 3338,
"text": "Step 10 − Now add the properties of Log4j which would be picked up during execution."
},
{
"code": null,
"e": 4119,
"s": 3423,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE log4j:configuration SYSTEM \"log4j.dtd\">\n<log4j:configuration xmlns:log4j = \"http://jakarta.apache.org/log4j/\" debug = \"false\">\n\n <appender name = \"fileAppender\" class = \"org.apache.log4j.FileAppender\">\n <param name = \"Threshold\" value = \"INFO\" />\n <param name = \"File\" value = \"percent_calculator.log\"/>\n \n <layout class = \"org.apache.log4j.PatternLayout\">\n <param name = \"ConversionPattern\"\n value = \"%d{yyyy-MM-dd HH:mm:ss} [%c] (%t:%x) %m%n\" />\n </layout>\n </appender>\n\n <root>\n <level value = \"INFO\"/>\n <appender-ref ref = \"fileAppender\"/>\n </root>\n \n</log4j:configuration>"
},
{
"code": null,
"e": 4295,
"s": 4119,
"text": "Step 11 − Now for demonstration purpose, we will incorporate log4j in the same test that we have been performing (percent calculator). Add a class file in the 'Main' function."
},
{
"code": null,
"e": 6802,
"s": 4295,
"text": "package log4j_demo;\nimport org.apache.log4j.LogManager;\nimport org.apache.log4j.Logger;\nimport org.apache.log4j.xml.DOMConfigurator;\n\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.*;\nimport org.openqa.selenium.firefox.FirefoxDriver;\n\npublic class log4j_demo {\n static final Logger logger = LogManager.getLogger(log4j_demo.class.getName());\n \n public static void main(String[] args) {\n \n DOMConfigurator.configure(\"log4j.xml\");\n logger.info(\"# # # # # # # # # # # # # # # # # # # # # # # # # # # \");\n logger.info(\"TEST Has Started\");\n WebDriver driver = new FirefoxDriver();\n \n //Puts a Implicit wait, Will wait for 10 seconds before throwing exception\n driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);\n \n //Launch website\n driver.navigate().to(\"http://www.calculator.net/\");\n logger.info(\"Open Calc Application\");\n \n //Maximize the browser\n driver.manage().window().maximize();\n \n //Click on Math Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[3]/a\")).click();\n logger.info(\"Clicked Math Calculator Link\");\n \n //Click on Percent Calculators\n driver.findElement(By.xpath(\".//*[@id = 'menu']/div[4]/div[3]/a\")).click();\n logger.info(\"Clicked Percent Calculator Link\");\n \n //Enter value 10 in the first number of the percent Calculator\n driver.findElement(By.id(\"cpar1\")).sendKeys(\"10\");\n logger.info(\"Entered Value into First Text Box\");\n \n //Enter value 50 in the second number of the percent Calculator\n driver.findElement(By.id(\"cpar2\")).sendKeys(\"50\");\n logger.info(\"Entered Value into Second Text Box\");\n \n //Click Calculate Button\n driver.findElement(By.xpath(\".//*[@id = 'content']/table/tbody/tr/td[2]/input\")).click();\n logger.info(\"Click Calculate Button\");\n \n //Get the Result Text based on its xpath \n String result =\n driver.findElement(By.xpath(\".//*[@id = 'content']/p[2]/span/font/b\")).getText(); \n logger.info(\"Get Text Value\");\n \n //Print a Log In message to the screen\n logger.info(\" The Result is \" + result);\n \n if(result.equals(\"5\")) {\n logger.info(\"The Result is Pass\");\n } else {\n logger.error(\"TEST FAILED. NEEDS INVESTIGATION\");\n }\n \n logger.info(\"# # # # # # # # # # # # # # # # # # # # # # # # # # # \");\n //Close the Browser.\n driver.close(); \n }\n}"
},
{
"code": null,
"e": 6969,
"s": 6802,
"text": "Upon execution, the log file is created on the root folder as shown below. You CANNOT locate the file in Eclipse. You should open 'Windows Explorer' to show the same."
},
{
"code": null,
"e": 7010,
"s": 6969,
"text": "The contents of the file is shown below."
},
{
"code": null,
"e": 7045,
"s": 7010,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7057,
"s": 7045,
"text": " Aditya Dua"
},
{
"code": null,
"e": 7093,
"s": 7057,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 7107,
"s": 7093,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7144,
"s": 7107,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 7166,
"s": 7144,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7199,
"s": 7166,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7213,
"s": 7199,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7248,
"s": 7213,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 7262,
"s": 7248,
"text": " Arun Motoori"
},
{
"code": null,
"e": 7299,
"s": 7262,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 7313,
"s": 7299,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7320,
"s": 7313,
"text": " Print"
},
{
"code": null,
"e": 7331,
"s": 7320,
"text": " Add Notes"
}
] |
How to Find Interior and Exterior Skeleton of Binary Images Using MATLAB? - GeeksforGeeks
|
18 Jan, 2022
Skeletonization is a process for reducing foreground regions in a binary image to a skeletal remnant that largely preserves the extent and connectivity of the original region while throwing away most of the original foreground pixels. In this article, we will see how to find interior and exterior skeleton of binary images using MATLAB in-built function.
Thinning: Thinning is a morphological operation performed on binary images. It removes some selected foreground pixels from binary images and hence thins the image. Mathematically, it is the difference of binary image and the result of hit-or-miss transformation applied on the same binary image.
Inner Skeleton of image: Every binary image can be thinned infinite times. The inner structure is obtained when thinning operation is applied infinite times until the resultant image is 1 pixel thick. The underlying inner skeleton of the binary image is obtained finally.
Exterior Skeleton of image: The exterior skeleton of the image consists of the boundary only and interior pixels of the image are removed. It is different from edge detection because in edge detection we detect all interior edges along with boundary edges. In the exterior skeleton finding the result only consist of the outer boundary and all interior pixels are removed.
Function Used:
imread( ) inbuilt function is used to read the image.
rgb2gray( ) inbuilt function is used to convert RGB colour image into grayscale.
bwmorph( ) inbuilt function is used to find skeleton of the image.
imtool( ) inbuilt function is used to display the image.
Example:
Matlab
% Find Skeleton of a binary image.% read the image.k=imread('skeleton.png'); % Convert into grayscale.k=rgb2gray(k); % apply morphological operation.k1=bwmorph(k,'skel',Inf); % display original image.imtool(k); % display skeleton of image.imtool(k1);
Output:
Figure 1: Input image
Figure 2:Output image
Figure 3: Results on GFGlogo
Example:
Matlab
% MATLAB code for remove% inner pixels of image.% read the image.k=imread('skeleton.png'); % Convert into grayscale.k=rgb2gray(k); % Apply morphological operation.k2=bwmorph(k,'remove',Inf); % display original image.imtool(k); % display boundary image.imtool(k2);
Output:
Figure 4: Input image
Figure 5: Output image
Figure 6: Result on GFGlogo
surinderdawra388
sumitgumber28
MATLAB image-processing
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
MRI Image Segmentation in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
Laplacian of Gaussian Filter in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Boundary Extraction of image using MATLAB
|
[
{
"code": null,
"e": 24281,
"s": 24253,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 24637,
"s": 24281,
"text": "Skeletonization is a process for reducing foreground regions in a binary image to a skeletal remnant that largely preserves the extent and connectivity of the original region while throwing away most of the original foreground pixels. In this article, we will see how to find interior and exterior skeleton of binary images using MATLAB in-built function."
},
{
"code": null,
"e": 24934,
"s": 24637,
"text": "Thinning: Thinning is a morphological operation performed on binary images. It removes some selected foreground pixels from binary images and hence thins the image. Mathematically, it is the difference of binary image and the result of hit-or-miss transformation applied on the same binary image."
},
{
"code": null,
"e": 25206,
"s": 24934,
"text": "Inner Skeleton of image: Every binary image can be thinned infinite times. The inner structure is obtained when thinning operation is applied infinite times until the resultant image is 1 pixel thick. The underlying inner skeleton of the binary image is obtained finally."
},
{
"code": null,
"e": 25579,
"s": 25206,
"text": "Exterior Skeleton of image: The exterior skeleton of the image consists of the boundary only and interior pixels of the image are removed. It is different from edge detection because in edge detection we detect all interior edges along with boundary edges. In the exterior skeleton finding the result only consist of the outer boundary and all interior pixels are removed."
},
{
"code": null,
"e": 25595,
"s": 25579,
"text": "Function Used: "
},
{
"code": null,
"e": 25649,
"s": 25595,
"text": "imread( ) inbuilt function is used to read the image."
},
{
"code": null,
"e": 25730,
"s": 25649,
"text": "rgb2gray( ) inbuilt function is used to convert RGB colour image into grayscale."
},
{
"code": null,
"e": 25797,
"s": 25730,
"text": "bwmorph( ) inbuilt function is used to find skeleton of the image."
},
{
"code": null,
"e": 25854,
"s": 25797,
"text": "imtool( ) inbuilt function is used to display the image."
},
{
"code": null,
"e": 25863,
"s": 25854,
"text": "Example:"
},
{
"code": null,
"e": 25870,
"s": 25863,
"text": "Matlab"
},
{
"code": "% Find Skeleton of a binary image.% read the image.k=imread('skeleton.png'); % Convert into grayscale.k=rgb2gray(k); % apply morphological operation.k1=bwmorph(k,'skel',Inf); % display original image.imtool(k); % display skeleton of image.imtool(k1);",
"e": 26121,
"s": 25870,
"text": null
},
{
"code": null,
"e": 26129,
"s": 26121,
"text": "Output:"
},
{
"code": null,
"e": 26151,
"s": 26129,
"text": "Figure 1: Input image"
},
{
"code": null,
"e": 26175,
"s": 26153,
"text": "Figure 2:Output image"
},
{
"code": null,
"e": 26204,
"s": 26175,
"text": "Figure 3: Results on GFGlogo"
},
{
"code": null,
"e": 26213,
"s": 26204,
"text": "Example:"
},
{
"code": null,
"e": 26220,
"s": 26213,
"text": "Matlab"
},
{
"code": "% MATLAB code for remove% inner pixels of image.% read the image.k=imread('skeleton.png'); % Convert into grayscale.k=rgb2gray(k); % Apply morphological operation.k2=bwmorph(k,'remove',Inf); % display original image.imtool(k); % display boundary image.imtool(k2);",
"e": 26484,
"s": 26220,
"text": null
},
{
"code": null,
"e": 26495,
"s": 26487,
"text": "Output:"
},
{
"code": null,
"e": 26520,
"s": 26497,
"text": "Figure 4: Input image "
},
{
"code": null,
"e": 26547,
"s": 26524,
"text": "Figure 5: Output image"
},
{
"code": null,
"e": 26577,
"s": 26549,
"text": "Figure 6: Result on GFGlogo"
},
{
"code": null,
"e": 26596,
"s": 26579,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26610,
"s": 26596,
"text": "sumitgumber28"
},
{
"code": null,
"e": 26634,
"s": 26610,
"text": "MATLAB image-processing"
},
{
"code": null,
"e": 26641,
"s": 26634,
"text": "MATLAB"
},
{
"code": null,
"e": 26739,
"s": 26641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26748,
"s": 26739,
"text": "Comments"
},
{
"code": null,
"e": 26761,
"s": 26748,
"text": "Old Comments"
},
{
"code": null,
"e": 26834,
"s": 26761,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 26867,
"s": 26834,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 26932,
"s": 26867,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 26972,
"s": 26932,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 27000,
"s": 26972,
"text": "Laplace Transform in MATLAB"
},
{
"code": null,
"e": 27039,
"s": 27000,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 27104,
"s": 27039,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 27164,
"s": 27104,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 27225,
"s": 27164,
"text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?"
}
] |
Sorting odd and even elements separately JavaScript
|
We are required to write a JavaScript function that takes in an array of Integers.
The function should sort the array such all the odd numbers come first, then followed by the even number.
The order of odd or even numbers within themselves is not of much importance, but all odd numbers should come before any even number.
For example −
If the input array is −
const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];
Then the sorted array should be (it’s one of the many solutions where all odds are before evens) −
const output = [
1, 3, 5, 7, 9,
1, 0, 2, 4, 6,
8, 0
];
const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];
const sortOddEven = (arr = []) => {
let i = 0, j, temp;
while (i < arr.length - 1) {
j = i;
while (!(arr[j] % 2) && arr[j + 1] % 2) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
if (!j) {
break;
};
j--;
};
i++;
};
};
sortOddEven(arr);
console.log(arr);
And the output in the console will be −
[
1, 3, 5, 7, 9,
1, 0, 2, 4, 6,
8, 0
]
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of Integers."
},
{
"code": null,
"e": 1251,
"s": 1145,
"text": "The function should sort the array such all the odd numbers come first, then followed by the even number."
},
{
"code": null,
"e": 1385,
"s": 1251,
"text": "The order of odd or even numbers within themselves is not of much importance, but all odd numbers should come before any even number."
},
{
"code": null,
"e": 1399,
"s": 1385,
"text": "For example −"
},
{
"code": null,
"e": 1423,
"s": 1399,
"text": "If the input array is −"
},
{
"code": null,
"e": 1473,
"s": 1423,
"text": "const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];"
},
{
"code": null,
"e": 1572,
"s": 1473,
"text": "Then the sorted array should be (it’s one of the many solutions where all odds are before evens) −"
},
{
"code": null,
"e": 1627,
"s": 1572,
"text": "const output = [\n1, 3, 5, 7, 9,\n1, 0, 2, 4, 6,\n8, 0\n];"
},
{
"code": null,
"e": 2040,
"s": 1627,
"text": "const arr = [0, 2, 4, 6, 8, 0, 1, 3, 5, 7, 9, 1];\nconst sortOddEven = (arr = []) => {\n let i = 0, j, temp;\n while (i < arr.length - 1) {\n j = i;\n while (!(arr[j] % 2) && arr[j + 1] % 2) {\n temp = arr[j];\n arr[j] = arr[j + 1];\n arr[j + 1] = temp;\n if (!j) {\n break;\n };\n j--;\n };\n i++;\n };\n};\nsortOddEven(arr);\nconsole.log(arr);"
},
{
"code": null,
"e": 2080,
"s": 2040,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2128,
"s": 2080,
"text": "[\n 1, 3, 5, 7, 9,\n 1, 0, 2, 4, 6,\n 8, 0\n]"
}
] |
Python - Tkinter Label
|
This widget implements a display box where you can place text or images. The text displayed by this widget can be updated at any time you want.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text across multiple lines.
Here is the simple syntax to create this widget −
w = Label ( master, option, ... )
master − This represents the parent window.
master − This represents the parent window.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.
anchor
This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text in the available space.
bg
The normal background color displayed behind the label and indicator.
bitmap
Set this option equal to a bitmap or image object and the label will display that graphic.
bd
The size of the border around the indicator. Default is 2 pixels.
cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton.
font
If you are displaying text in this label (with the text or textvariable option, the font option specifies in what font that text will be displayed.
fg
If you are displaying text or a bitmap in this label, this option specifies the color of the text. If you are displaying a bitmap, this is the color that will appear at the position of the 1-bits in the bitmap.
height
The vertical dimension of the new frame.
image
To display a static image in the label widget, set this option to an image object.
justify
Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush left, CENTER for centered (the default), or RIGHT for right-justified.
padx
Extra space added to the left and right of the text within the widget. Default is 1.
pady
Extra space added above and below the text within the widget. Default is 1.
relief
Specifies the appearance of a decorative border around the label. The default is FLAT; for other values.
text
To display one or more lines of text in a label widget, set this option to a string containing the text. Internal newlines ("\n") will force a line break.
textvariable
To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable.
underline
You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline=-1, which means no underlining.
width
Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents.
wraplength
You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines.
Try the following example yourself −
from Tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
When the above code is executed, it produces the following result −
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": 2388,
"s": 2244,
"text": "This widget implements a display box where you can place text or images. The text displayed by this widget can be updated at any time you want."
},
{
"code": null,
"e": 2518,
"s": 2388,
"text": "It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text across multiple lines."
},
{
"code": null,
"e": 2568,
"s": 2518,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2603,
"s": 2568,
"text": "w = Label ( master, option, ... )\n"
},
{
"code": null,
"e": 2647,
"s": 2603,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2691,
"s": 2647,
"text": "master − This represents the parent window."
},
{
"code": null,
"e": 2831,
"s": 2691,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 2971,
"s": 2831,
"text": "options − Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas."
},
{
"code": null,
"e": 2978,
"s": 2971,
"text": "anchor"
},
{
"code": null,
"e": 3156,
"s": 2978,
"text": "This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text in the available space."
},
{
"code": null,
"e": 3159,
"s": 3156,
"text": "bg"
},
{
"code": null,
"e": 3229,
"s": 3159,
"text": "The normal background color displayed behind the label and indicator."
},
{
"code": null,
"e": 3236,
"s": 3229,
"text": "bitmap"
},
{
"code": null,
"e": 3327,
"s": 3236,
"text": "Set this option equal to a bitmap or image object and the label will display that graphic."
},
{
"code": null,
"e": 3331,
"s": 3327,
"text": "bd "
},
{
"code": null,
"e": 3397,
"s": 3331,
"text": "The size of the border around the indicator. Default is 2 pixels."
},
{
"code": null,
"e": 3404,
"s": 3397,
"text": "cursor"
},
{
"code": null,
"e": 3541,
"s": 3404,
"text": "If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern when it is over the checkbutton."
},
{
"code": null,
"e": 3546,
"s": 3541,
"text": "font"
},
{
"code": null,
"e": 3694,
"s": 3546,
"text": "If you are displaying text in this label (with the text or textvariable option, the font option specifies in what font that text will be displayed."
},
{
"code": null,
"e": 3698,
"s": 3694,
"text": "fg "
},
{
"code": null,
"e": 3909,
"s": 3698,
"text": "If you are displaying text or a bitmap in this label, this option specifies the color of the text. If you are displaying a bitmap, this is the color that will appear at the position of the 1-bits in the bitmap."
},
{
"code": null,
"e": 3916,
"s": 3909,
"text": "height"
},
{
"code": null,
"e": 3958,
"s": 3916,
"text": "The vertical dimension of the new frame. "
},
{
"code": null,
"e": 3964,
"s": 3958,
"text": "image"
},
{
"code": null,
"e": 4047,
"s": 3964,
"text": "To display a static image in the label widget, set this option to an image object."
},
{
"code": null,
"e": 4055,
"s": 4047,
"text": "justify"
},
{
"code": null,
"e": 4222,
"s": 4055,
"text": "Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush left, CENTER for centered (the default), or RIGHT for right-justified."
},
{
"code": null,
"e": 4227,
"s": 4222,
"text": "padx"
},
{
"code": null,
"e": 4312,
"s": 4227,
"text": "Extra space added to the left and right of the text within the widget. Default is 1."
},
{
"code": null,
"e": 4317,
"s": 4312,
"text": "pady"
},
{
"code": null,
"e": 4393,
"s": 4317,
"text": "Extra space added above and below the text within the widget. Default is 1."
},
{
"code": null,
"e": 4400,
"s": 4393,
"text": "relief"
},
{
"code": null,
"e": 4505,
"s": 4400,
"text": "Specifies the appearance of a decorative border around the label. The default is FLAT; for other values."
},
{
"code": null,
"e": 4510,
"s": 4505,
"text": "text"
},
{
"code": null,
"e": 4665,
"s": 4510,
"text": "To display one or more lines of text in a label widget, set this option to a string containing the text. Internal newlines (\"\\n\") will force a line break."
},
{
"code": null,
"e": 4678,
"s": 4665,
"text": "textvariable"
},
{
"code": null,
"e": 4800,
"s": 4678,
"text": "To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable."
},
{
"code": null,
"e": 4810,
"s": 4800,
"text": "underline"
},
{
"code": null,
"e": 4980,
"s": 4810,
"text": "You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline=-1, which means no underlining."
},
{
"code": null,
"e": 4986,
"s": 4980,
"text": "width"
},
{
"code": null,
"e": 5106,
"s": 4986,
"text": "Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents."
},
{
"code": null,
"e": 5117,
"s": 5106,
"text": "wraplength"
},
{
"code": null,
"e": 5287,
"s": 5117,
"text": "You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines."
},
{
"code": null,
"e": 5324,
"s": 5287,
"text": "Try the following example yourself −"
},
{
"code": null,
"e": 5498,
"s": 5324,
"text": "from Tkinter import *\n\nroot = Tk()\nvar = StringVar()\nlabel = Label( root, textvariable=var, relief=RAISED )\n\nvar.set(\"Hey!? How are you doing?\")\nlabel.pack()\nroot.mainloop()"
},
{
"code": null,
"e": 5567,
"s": 5498,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5604,
"s": 5567,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5620,
"s": 5604,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5653,
"s": 5620,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5672,
"s": 5653,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5707,
"s": 5672,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5729,
"s": 5707,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5763,
"s": 5729,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5791,
"s": 5763,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5826,
"s": 5791,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5840,
"s": 5826,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5873,
"s": 5840,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5890,
"s": 5873,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5897,
"s": 5890,
"text": " Print"
},
{
"code": null,
"e": 5908,
"s": 5897,
"text": " Add Notes"
}
] |
C library function - tmpfile()
|
The C library function FILE *tmpfile(void) creates a temporary file in binary update mode (wb+). The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates.
Following is the declaration for tmpfile() function.
FILE *tmpfile(void)
NA
NA
If successful, the function returns a stream pointer to the temporary file created. If the file cannot be created, then NULL is returned.
The following example shows the usage of tmpfile() function.
#include <stdio.h>
int main () {
FILE *fp;
fp = tmpfile();
printf("Temporary file created\n");
/* you can use tmp file here */
fclose(fp);
return(0);
}
Let us compile and run the above program to create a temporary file in /tmp folder but once your program is out, it will be deleted automatically and the program will produce the following result −
Temporary file created
12 Lectures
2 hours
Nishant Malik
12 Lectures
2.5 hours
Nishant Malik
48 Lectures
6.5 hours
Asif Hussain
12 Lectures
2 hours
Richa Maheshwari
20 Lectures
3.5 hours
Vandana Annavaram
44 Lectures
1 hours
Amit Diwan
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2223,
"s": 2007,
"text": "The C library function FILE *tmpfile(void) creates a temporary file in binary update mode (wb+). The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates."
},
{
"code": null,
"e": 2276,
"s": 2223,
"text": "Following is the declaration for tmpfile() function."
},
{
"code": null,
"e": 2296,
"s": 2276,
"text": "FILE *tmpfile(void)"
},
{
"code": null,
"e": 2299,
"s": 2296,
"text": "NA"
},
{
"code": null,
"e": 2302,
"s": 2299,
"text": "NA"
},
{
"code": null,
"e": 2440,
"s": 2302,
"text": "If successful, the function returns a stream pointer to the temporary file created. If the file cannot be created, then NULL is returned."
},
{
"code": null,
"e": 2501,
"s": 2440,
"text": "The following example shows the usage of tmpfile() function."
},
{
"code": null,
"e": 2676,
"s": 2501,
"text": "#include <stdio.h>\n\nint main () {\n FILE *fp;\n\n fp = tmpfile();\n printf(\"Temporary file created\\n\");\n\n /* you can use tmp file here */\n\n fclose(fp);\n\n return(0);\n}"
},
{
"code": null,
"e": 2874,
"s": 2676,
"text": "Let us compile and run the above program to create a temporary file in /tmp folder but once your program is out, it will be deleted automatically and the program will produce the following result −"
},
{
"code": null,
"e": 2898,
"s": 2874,
"text": "Temporary file created\n"
},
{
"code": null,
"e": 2931,
"s": 2898,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2946,
"s": 2931,
"text": " Nishant Malik"
},
{
"code": null,
"e": 2981,
"s": 2946,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2996,
"s": 2981,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3031,
"s": 2996,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3045,
"s": 3031,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3078,
"s": 3045,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3096,
"s": 3078,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3131,
"s": 3096,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3150,
"s": 3131,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3183,
"s": 3150,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3195,
"s": 3183,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3202,
"s": 3195,
"text": " Print"
},
{
"code": null,
"e": 3213,
"s": 3202,
"text": " Add Notes"
}
] |
CodeIgniter - File Uploading
|
Using File Uploading class, we can upload files and we can also, restrict the type and size of the file to be uploaded. Follow the steps shown in the given example to understand the file uploading process in CodeIgniter.
Copy the following code and store it at application/view/Upload_form.php.
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<form action = "" method = "">
<input type = "file" name = "userfile" size = "20" />
<br /><br />
<input type = "submit" value = "upload" />
</form>
</body>
</html>
Copy the code given below and store it at application/view/Upload_success.php
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?phpforeach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?phpendforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html>
Copy the code given below and store it at application/controllers/Upload.php. Create “uploads” folder at the root of CodeIgniter i.e. at the parent directory of application folder.
<?php
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
Make the following change in the route file in application/config/routes.php and add the following line at the end of file.
$route['upload'] = 'Upload';
Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.
http://yoursite.com/index.php/upload
It will produce the following screen −
After successfully uploading a file, you will see the following screen −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2540,
"s": 2319,
"text": "Using File Uploading class, we can upload files and we can also, restrict the type and size of the file to be uploaded. Follow the steps shown in the given example to understand the file uploading process in CodeIgniter."
},
{
"code": null,
"e": 2614,
"s": 2540,
"text": "Copy the following code and store it at application/view/Upload_form.php."
},
{
"code": null,
"e": 3000,
"s": 2614,
"text": "<html>\n \n <head> \n <title>Upload Form</title> \n </head>\n\t\n <body> \n <?php echo $error;?> \n <?php echo form_open_multipart('upload/do_upload');?> \n\t\t\n <form action = \"\" method = \"\">\n <input type = \"file\" name = \"userfile\" size = \"20\" /> \n <br /><br /> \n <input type = \"submit\" value = \"upload\" /> \n </form> \n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3078,
"s": 3000,
"text": "Copy the code given below and store it at application/view/Upload_success.php"
},
{
"code": null,
"e": 3485,
"s": 3078,
"text": "<html>\n \n <head> \n <title>Upload Form</title> \n </head>\n\t\n <body> \n <h3>Your file was successfully uploaded!</h3> \n\t\t\n <ul> \n <?phpforeach ($upload_data as $item => $value):?> \n <li><?php echo $item;?>: <?php echo $value;?></li> \n <?phpendforeach; ?>\n </ul> \n\t\t\n <p><?php echo anchor('upload', 'Upload Another File!'); ?></p> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 3666,
"s": 3485,
"text": "Copy the code given below and store it at application/controllers/Upload.php. Create “uploads” folder at the root of CodeIgniter i.e. at the parent directory of application folder."
},
{
"code": null,
"e": 4659,
"s": 3666,
"text": "<?php\n \n class Upload extends CI_Controller {\n\t\n public function __construct() { \n parent::__construct(); \n $this->load->helper(array('form', 'url')); \n }\n\t\t\n public function index() { \n $this->load->view('upload_form', array('error' => ' ' )); \n } \n\t\t\n public function do_upload() { \n $config['upload_path'] = './uploads/'; \n $config['allowed_types'] = 'gif|jpg|png'; \n $config['max_size'] = 100; \n $config['max_width'] = 1024; \n $config['max_height'] = 768; \n $this->load->library('upload', $config);\n\t\t\t\n if ( ! $this->upload->do_upload('userfile')) {\n $error = array('error' => $this->upload->display_errors()); \n $this->load->view('upload_form', $error); \n }\n\t\t\t\n else { \n $data = array('upload_data' => $this->upload->data()); \n $this->load->view('upload_success', $data); \n } \n } \n } \n?>"
},
{
"code": null,
"e": 4783,
"s": 4659,
"text": "Make the following change in the route file in application/config/routes.php and add the following line at the end of file."
},
{
"code": null,
"e": 4813,
"s": 4783,
"text": "$route['upload'] = 'Upload';\n"
},
{
"code": null,
"e": 4931,
"s": 4813,
"text": "Now let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL."
},
{
"code": null,
"e": 4969,
"s": 4931,
"text": "http://yoursite.com/index.php/upload\n"
},
{
"code": null,
"e": 5008,
"s": 4969,
"text": "It will produce the following screen −"
},
{
"code": null,
"e": 5081,
"s": 5008,
"text": "After successfully uploading a file, you will see the following screen −"
},
{
"code": null,
"e": 5088,
"s": 5081,
"text": " Print"
},
{
"code": null,
"e": 5099,
"s": 5088,
"text": " Add Notes"
}
] |
C# Enum IsDefined Method
|
The IsDefined method returns true if a given integral value, or its name as a string, is present in a specified enum.
The following is our enum −
enum Subjects { Maths, Science, English, Economics };
The above is initialized by default i.e.
Maths = 0, Science = 1, English = 2, Economics = 3
Therefore, when we will find 3 using IsDefined(), then it will return True as shown below −
Live Demo
using System;
public class Demo {
enum Subjects { Maths, Science, English, Economics };
public static void Main() {
object ob;
ob = 3;
Console.WriteLine("{0} = {1}", ob, Enum.IsDefined(typeof(Subjects), ob));
}
}
3 = True
|
[
{
"code": null,
"e": 1180,
"s": 1062,
"text": "The IsDefined method returns true if a given integral value, or its name as a string, is present in a specified enum."
},
{
"code": null,
"e": 1208,
"s": 1180,
"text": "The following is our enum −"
},
{
"code": null,
"e": 1262,
"s": 1208,
"text": "enum Subjects { Maths, Science, English, Economics };"
},
{
"code": null,
"e": 1303,
"s": 1262,
"text": "The above is initialized by default i.e."
},
{
"code": null,
"e": 1354,
"s": 1303,
"text": "Maths = 0, Science = 1, English = 2, Economics = 3"
},
{
"code": null,
"e": 1446,
"s": 1354,
"text": "Therefore, when we will find 3 using IsDefined(), then it will return True as shown below −"
},
{
"code": null,
"e": 1457,
"s": 1446,
"text": " Live Demo"
},
{
"code": null,
"e": 1697,
"s": 1457,
"text": "using System;\npublic class Demo {\n enum Subjects { Maths, Science, English, Economics };\n public static void Main() {\n object ob;\n ob = 3;\n Console.WriteLine(\"{0} = {1}\", ob, Enum.IsDefined(typeof(Subjects), ob));\n }\n}"
},
{
"code": null,
"e": 1706,
"s": 1697,
"text": "3 = True"
}
] |
Machine learning model deployment with C++ | by Babatunde | Towards Data Science
|
Recently, I have been fascinated with how interesting it would be to build a mathematically inclined application and deploy it at scale without any restriction to model size, platform, or need for api calls. I know that Python has enough of a library for working with prototypes of machine learning projects, however not many are talking about scaling this project, especially when you don’t want to do that over a web api.
I believe true intelligence shouldn’t rely only on calls to an api for a model to be available in scale. This fascination led me to research what it will take to use C++ for machine learning and general intelligence.
My conviction is that both Matlab and Python’s mathematical strengths are based on an underlying c/c++ code. Hence, fundamentally scaling technology to work with mathematical computations involved in machine learning with a blazing fast scenario in mind will likely require that you are able to dig into low-level programming and most especially with c/c++.
Also, I wondered why most computer science schools ensure that there is a c/c++ curriculum in their course. This emphasises the reasoning of using c/c++ for scalable technology.
After learning c++ using an Udemy hands-on course, now the challenge is to integrate a simple face recognition application in an android.
The write-up will include some preliminary approaches of what you need to build a c++ project and deploy in android or any other os environment.
Components:
Set up a c++ project for machine learning with opencv.Learning a PCA to generate eigenfacesSetting up a .so inference library for multiplatform deploymentDeveloping a jni wrapper for the inference library.Using the library in Android or any java code.
Set up a c++ project for machine learning with opencv.
Learning a PCA to generate eigenfaces
Setting up a .so inference library for multiplatform deployment
Developing a jni wrapper for the inference library.
Using the library in Android or any java code.
The first part will be to learn a machine learning algorithm with OpenCV. In this case, we are going to explore the most basic of face recognition algorithm, using principal component analysis for eigenfaces. The machine learning community is very familiar with this in python especially with tools such as sci-kit learn, but when production and most especially offline/on-device production comes to mind, the need to do this from a different dimension is expedient.
OpenCV comes with a very good api for learning principal component analysis and it is quite straight forward to learn once you have your data all set up.
The key part of your CMakeFile.txt is ensuring that there is an OpenCV library in 0 project and available for your library to compile. Ideally, before requesting that Cmake find OpenCV for you, it is important to have the OpenCV library installed on your machine.
find_package(OpenCV REQUIRED)include_directories(${OpenCV_INCLUDE_DIRS})set(LIBS ${OpenCV_LIBS})target_link_libraries(featureCalculation ${LIBS})
PS: I had to set up my cmake differently for training and inference. I will share both
Now that OpenCV is available, learning PCA is quite straight forward. Here is the logic invole:
Read all image data as an array.Using cv::glob from OpenCV, all filenames ending with a .jpg, .png or/and .jpeg can be read with cv::imread, and the data preprocessing of the image data can proceed.
Crop faces.This is important because PCA does much better with the face image than the whole image. I have found Multi-task Cascaded Convolutional Networks (MTCNN) to be the most reliable yet simple and minimal face detection and cropping model out there. There is an implementation in C++ using the original model with a Caffe network in OpenCV.
Convert cropped faces to gray scale.This part is pretty straight forward. Using cv::cvtColor(originalimagemat, grayscaleimagematcontainer, cv::COLOR_BGR2GRAY) we can convert an original BGR image to grayscale in OpenCV.
Other preprocessing — One other preprocessing is to ensure that the data types are right. This is very important because C++ is heavy on the precision of data types. It is quite easy to introduce bugs at this point hence the reason to carefully ensure that your data types are right. Apart from this, it is a good idea to normalize your image data and resize all images into a consistent shape. PCA works only if the data are in the same dimension. Out of the box from OpenCV, we can employ the following functions to take care of the preprocessing:
cv::resize(originalImage, containermatofnewimage, size) for resizing the image and originalmat::convertTo(newmatnormalized, CV_32FC3, 1/255.0) to normalize the pixel values of the image.
Convert all images to a data table — A data table is somewhat like a single table of data where each element is represented as a row, interestingly we can think of each row of our data table as individual images in its flattened format. The essence of PCA is to project the image values to a few columns with a distinct representation of that image. Therefore, the data table will have rows equals to the number of images in the training dataset while the columns will be the normalized grayscale values of each image.
To create the data table, std::vector can be used to hold all the images (with the hope that they fit in memory) which is then copied to every row of the data matrix. Here is an helper function that does exactly that from a vector of images mat.
cv::Mat createdatamatrix(std::vector<cv::Mat> imageArray) {cv::Mat datamatrix(static_cast<int>(imageArray.size()), imageArray[0].rows * imageArray[0].cols, CV_32F);unsigned int i;for(i=0; i < imageArray.size(); i++) { cv::Mat imageRow = imageArray[i].clone().reshape(1, 1); cv::Mat rowIData = datamatrix.row(i); imageRow.copyTo(rowIData); } return datamatrix;}
cv::reshape() helps transform mat arrays to different shapes, with (1, 1) it literally means we want the data to exist in a single row.
Learn the actual Pricipal component analysis algorithm.Now that we have created the data table with the preprocessed face images, learning the PCA model is usually smooth. As smooth as passing the data table to an OpenCV pca instance with your expected maximum components like such cv::PCA pca(datatable, cv::Mat(), cv::PCA::DATA_AS_ROW, number_of_components). With this, we have a learned PCA written in C++ which is ready for production use.
To transfer this model for use in any environment, open cv has a FileStorage object that allows you to save a mat as it is. Thus I can save this file and pass its filename over jni for OpenCV to recreate the model instances for inference. Well, it simply as sweet as that to serve the model.
To conclude the inference part of the article, I will simply show how to write the mat object using OpenCV. At the end of the day, the values in the saved model come out as either a YAML file or XML depending on the choice most pleasant to the user.
Save the pca model object for inference on production environment.What exactly needs to be saved in the pca object are the mean and eigenvectors of the trained pca, sometimes it may be a good idea to also save the eigenvalues in case you want to construct your own eigenfaces projection, but OpenCV already implemented a pca->project instance that helps in inference and eigenfaces generation. In any case here is how to save your model:
void Facepca::savemodel(cv::PCA pcaModel, const std::stringfilename){ cv::FileStorage fs(filename,cv::FileStorage::WRITE); fs << “mean” << pcaModel.mean; fs << “e_vectors” << pcaModel.eigenvectors; fs << “e_values” << pcaModel.eigenvalues; fs.release();}
Having saved the model, the inference layer will involve loading the saved model whose values are stored in the yml file also via OpenCV and developed to form an inference engine with necessary data preprocessing modules which is finally bundled as a .so file for deployment on a linux based environment. For other platforms, the cpp codes can be compiled to produce either a dll or dylib for windows and mac respectively.
Since we are concerned about deploying the model on an android application more, the focus will be building the .so file inference engine from our saved model.
Load a PCA modelFor inference, we let OpenCV load the existing model file from the saved .yml file after which we feed the eigenvalues, eigenvectors and mean to a new PCA object which we can then call a pca->project on to create a new image’s projection.
Here is a sample code that loads a saved OpenCV FileStorage model.
cv::PCA newPcaModel;cv::PCA loadmodel(cv::PCA newPcaModel, const std::string filename){ cv::FileStorage fs(filename,cv::FileStorage::READ); fs[“mean”] >> newPcaModel.mean ; fs[“e_vectors”] >> newPcaModel.eigenvectors ; fs[“e_values”] >> newPcaModel.eigenvalues ; fs.release(); return newPcaModel;}loadmodel(newPcaModel, “path-to-saved-yml-file”);
Once the model is loaded, the newPcaModel object now contains the saved model from the existing training parameters i.e pca eigenvalues, eigenvectors and mean. Hence when a face projection is done, it is guaranteed that the data returned is relative to the training dataset.
Create new image preprocessing and prediction stage.During inference of a machine learning model, it is important that the incoming image also passes through the same preprocessing as the training dataset.
Several approaches can be used to pass image to the inference engine, it could be that the image is loaded from disk or that the image is passed as a base64 string.
In our case, the likely approach is to use a base64 string since we are also taking into consideration two factors, that a jni will be exposed and also that our final library is for an android application.
With this in mind, we then need to ensure that the library is able to retrieve an image from a base64 string and send it to OpenCV.
Decoding a base64 string in c++ is quite non-trivial, however, a reader can refer to this link on a code snippet that does this.
Once the base64 image string is decoded, we then convert the string to a vector of unsigned character (uchar) which can be thought of as Image values.
OpenCV can decode the vector of uchar into an image using the function call to cv::imdecode(vectorUchar, flag). This process returns a Mat image with which further preprocessing can be done.
The image can then pass through the preprocessing phases of;
Face extraction
Convert cropped faces to grayscale.
Image resize
Image normalization
Create data matrix
Just as described in the training part of this article above.
The last leg of inference on the new image is using the loaded pca object to create a projection of the face in the new image.
The snippet that does that will look like this:
newPcaModel->project(datamatrix.row(0));
The part of recognition or verification happens when you project with a loaded pca object on two faces and compare the projections (eigenfaces) using a distance metrics e.g euclidean distance or cosine similarity.
Package the library with an exposed jni.This part is quite straightforward, once the inference code has been properly structured, most probably within a class, then the jni body can literally call the exposed functions for the model loading, preprocessing and prediction.
However, to create a jni, it is important to understand how the link occurs with java.
The first path is to create a Java class and the functions you want to use in your java class with the input parameters.
This will be what the jni will use as the function name when creating the cpp code. The consistency between the classpath name of the methods in Java with the name in cpp is very important.
Let us assume the method we will be using for our pca feature match is named matchpcafeatures() and our java class can then look like this.
package org.example.codeclass MatchFeatures {static float matchpcafeatures(modelfilename: String, image: String, projectionToCompare: Array[Float])}
With the above java class and method, our jni header file will look something like this.
#include <jni.h>/* Header for class com_example_code_MatchFeatures */#ifndef _Included_com_example_code_MatchFeatures#define _Included_com_example_code_MatchFeatures#ifdef __cplusplusextern “C” {#endifJNIEXPORT jfloat JNICALL Java_com_example_code_MatchFeatures_matchpcafeatures(JNIEnv *, jobject, jstring, jstring, jfloatArray);#ifdef __cplusplus}#endif#endif
You don’t need to bother yet about the details of the extern C the focus is on the name of the method in the jni header file.
Further down, we will look at how to use the java code above to make an inference. Let us first develop the jni bridge for this method.
The last 3 parameters of the jni header are just the same and in the exact position as the parameters in the java method.
Therefore, we will process on those parameters since they are the key requirements from a client to our c++ inference engine.
Below shows how to connect those input parameters and return a value which the java code can take and continue its other processes.
/*** Match features of pca* */JNIEXPORT jfloat JNICALL Java_com_seamfix_qrcode_FaceFeatures_matchpcafeatures(JNIEnv * env, jobject obj, jstring pcafilename, jstring imagestring, jfloatArray projectionToCompare){ const char *pcastring_char; pcastring_char = env->GetStringUTFChars(pcafilename, 0); if(pcastring_char == NULL) { return 0.0f; } const char *imagestring_char; imagestring_char = env->GetStringUTFChars(imagestring, 0); if(imagestring_char == NULL) { return 0.0f; } //Get file name string as a string for cpp std::string stdfilename(pcastring_char); cv::PCA pca; //Class InferencPca holds the preprocesing and inference methods InferencePca ef; std::vector<cv::Mat> imagevec; //Get image as base64 cv::Mat image = ef.readBase64Image(imagestring_char); ef.loadmodel(pca, stdfilename); imagevec.push_back(image); cv::Mat datamatrix = ef.createdatamatrix(imagevec); cv::Mat projection = ef.project(datamatrix.row(0)); //Load the existing vector. std::vector<float> initialProjectionPoints; //Load existing features -- needed to do comparison of faces jsize intArrayLen = env->GetArrayLength(existingfeatures); jfloat *pointvecBody = env->GetFloatArrayElements(existingfeatures, 0); for (int i =0; i < intArrayLen; i++) { initialProjectionPoints.push_back(pointvecBody[i]); } std::vector<float> newProjectionpoints = ef.matToVector(projection); float comparisonScores = ef.compareProjections(newProjectionpoints, initialProjectionPoints); env->ReleaseFloatArrayElements(existingfeatures, pointvecBody, 0); env->ReleaseStringUTFChars(pcafilename, pcastring_char); return comparisonScores;}
With this, we are set to build our .so library and release it to java code to use successfully. The protocol to build the library is stated in the CMakeLists.txt.
It looks like below:
find_package(JNI REQUIRED)#Include jni directoriesinclude_directories(${JNI_INCLUDE_DIRS})file (GLOB_RECURSE SOURCE_FILE src/*.h src/*.cpp)set(LIBS ${JNI_LIBRARIES})add_library(matchprojection SHARED ${SOURCE_FILE})target_link_libraries(matchprojection ${LIBS})
Building the project should generate a lib-matchprojection.so file which can be added to your java project.
However, for android, it is a little tricky in the sense that the build tool is different rather than the official cmake build toolchain, Android has its own build tool for native cpp codes. This is called Native development kit (NDK). This is what will be used to build you c++ native codes for the generated .so to be compatible with Android.
Building .so for android using NDK will be a whole tutorial on its own hence I will be skipping that for now.
But generally, once the build is complete using an NDK, you will have the same lib-matchprojection.so which can be used in your android application.
Using the generated library within the Android application is just the same as using it in any java application.
The idea is to load the native library and then make a call with the required parameter to the methods in the initially created Classes that correspond to the native jni method.
To load the library in any java program including android, ensure the .so library is in the classpath of your program, some will put it under a folder called lib or jniLibs. With this I can use a function call to load the library as below:
System.loads(“native-lib”)
Finally, I can make a call to my methods created earlier with the parameters necessary and the native code then can execute for me.
MatchFeatures mf = new MatchFeatures();float matchscores = mf.matchpcafeatures(storedpacfilepath, imagebase64string, anotherimageprojectionarray);
If you notice carefully, the method was declared native and there is no body for the method, this is because the programmes understand that there is a native cpp method that has been defined with this classpath name.
This approach is a fundamental way to build and deploy a project that includes native codes in a java environment. Also, most complex algorithmic problems, including machine learning and core computer vision projects, can easily be reason around in cpp most because it is fast and there are production-ready libraries.
Even TensorFlow has an api for loading deep learning models in c++ as well as using its tflite models in c++.
Hence, I see this approach of building an inference engine with native code as a way to build robust production-ready engines that will leverage high precision mathematics and most especially the deployment of machine learning models to various environment and in particular android environment in an offline environment.
I work as a data scientist and machine learning engineer at Seamfix Nigeria Ltd., where I focus on ensuring data science features ends up in production.
|
[
{
"code": null,
"e": 596,
"s": 172,
"text": "Recently, I have been fascinated with how interesting it would be to build a mathematically inclined application and deploy it at scale without any restriction to model size, platform, or need for api calls. I know that Python has enough of a library for working with prototypes of machine learning projects, however not many are talking about scaling this project, especially when you don’t want to do that over a web api."
},
{
"code": null,
"e": 813,
"s": 596,
"text": "I believe true intelligence shouldn’t rely only on calls to an api for a model to be available in scale. This fascination led me to research what it will take to use C++ for machine learning and general intelligence."
},
{
"code": null,
"e": 1171,
"s": 813,
"text": "My conviction is that both Matlab and Python’s mathematical strengths are based on an underlying c/c++ code. Hence, fundamentally scaling technology to work with mathematical computations involved in machine learning with a blazing fast scenario in mind will likely require that you are able to dig into low-level programming and most especially with c/c++."
},
{
"code": null,
"e": 1349,
"s": 1171,
"text": "Also, I wondered why most computer science schools ensure that there is a c/c++ curriculum in their course. This emphasises the reasoning of using c/c++ for scalable technology."
},
{
"code": null,
"e": 1487,
"s": 1349,
"text": "After learning c++ using an Udemy hands-on course, now the challenge is to integrate a simple face recognition application in an android."
},
{
"code": null,
"e": 1632,
"s": 1487,
"text": "The write-up will include some preliminary approaches of what you need to build a c++ project and deploy in android or any other os environment."
},
{
"code": null,
"e": 1644,
"s": 1632,
"text": "Components:"
},
{
"code": null,
"e": 1896,
"s": 1644,
"text": "Set up a c++ project for machine learning with opencv.Learning a PCA to generate eigenfacesSetting up a .so inference library for multiplatform deploymentDeveloping a jni wrapper for the inference library.Using the library in Android or any java code."
},
{
"code": null,
"e": 1951,
"s": 1896,
"text": "Set up a c++ project for machine learning with opencv."
},
{
"code": null,
"e": 1989,
"s": 1951,
"text": "Learning a PCA to generate eigenfaces"
},
{
"code": null,
"e": 2053,
"s": 1989,
"text": "Setting up a .so inference library for multiplatform deployment"
},
{
"code": null,
"e": 2105,
"s": 2053,
"text": "Developing a jni wrapper for the inference library."
},
{
"code": null,
"e": 2152,
"s": 2105,
"text": "Using the library in Android or any java code."
},
{
"code": null,
"e": 2619,
"s": 2152,
"text": "The first part will be to learn a machine learning algorithm with OpenCV. In this case, we are going to explore the most basic of face recognition algorithm, using principal component analysis for eigenfaces. The machine learning community is very familiar with this in python especially with tools such as sci-kit learn, but when production and most especially offline/on-device production comes to mind, the need to do this from a different dimension is expedient."
},
{
"code": null,
"e": 2773,
"s": 2619,
"text": "OpenCV comes with a very good api for learning principal component analysis and it is quite straight forward to learn once you have your data all set up."
},
{
"code": null,
"e": 3037,
"s": 2773,
"text": "The key part of your CMakeFile.txt is ensuring that there is an OpenCV library in 0 project and available for your library to compile. Ideally, before requesting that Cmake find OpenCV for you, it is important to have the OpenCV library installed on your machine."
},
{
"code": null,
"e": 3183,
"s": 3037,
"text": "find_package(OpenCV REQUIRED)include_directories(${OpenCV_INCLUDE_DIRS})set(LIBS ${OpenCV_LIBS})target_link_libraries(featureCalculation ${LIBS})"
},
{
"code": null,
"e": 3270,
"s": 3183,
"text": "PS: I had to set up my cmake differently for training and inference. I will share both"
},
{
"code": null,
"e": 3366,
"s": 3270,
"text": "Now that OpenCV is available, learning PCA is quite straight forward. Here is the logic invole:"
},
{
"code": null,
"e": 3565,
"s": 3366,
"text": "Read all image data as an array.Using cv::glob from OpenCV, all filenames ending with a .jpg, .png or/and .jpeg can be read with cv::imread, and the data preprocessing of the image data can proceed."
},
{
"code": null,
"e": 3912,
"s": 3565,
"text": "Crop faces.This is important because PCA does much better with the face image than the whole image. I have found Multi-task Cascaded Convolutional Networks (MTCNN) to be the most reliable yet simple and minimal face detection and cropping model out there. There is an implementation in C++ using the original model with a Caffe network in OpenCV."
},
{
"code": null,
"e": 4132,
"s": 3912,
"text": "Convert cropped faces to gray scale.This part is pretty straight forward. Using cv::cvtColor(originalimagemat, grayscaleimagematcontainer, cv::COLOR_BGR2GRAY) we can convert an original BGR image to grayscale in OpenCV."
},
{
"code": null,
"e": 4682,
"s": 4132,
"text": "Other preprocessing — One other preprocessing is to ensure that the data types are right. This is very important because C++ is heavy on the precision of data types. It is quite easy to introduce bugs at this point hence the reason to carefully ensure that your data types are right. Apart from this, it is a good idea to normalize your image data and resize all images into a consistent shape. PCA works only if the data are in the same dimension. Out of the box from OpenCV, we can employ the following functions to take care of the preprocessing:"
},
{
"code": null,
"e": 4869,
"s": 4682,
"text": "cv::resize(originalImage, containermatofnewimage, size) for resizing the image and originalmat::convertTo(newmatnormalized, CV_32FC3, 1/255.0) to normalize the pixel values of the image."
},
{
"code": null,
"e": 5388,
"s": 4869,
"text": "Convert all images to a data table — A data table is somewhat like a single table of data where each element is represented as a row, interestingly we can think of each row of our data table as individual images in its flattened format. The essence of PCA is to project the image values to a few columns with a distinct representation of that image. Therefore, the data table will have rows equals to the number of images in the training dataset while the columns will be the normalized grayscale values of each image."
},
{
"code": null,
"e": 5634,
"s": 5388,
"text": "To create the data table, std::vector can be used to hold all the images (with the hope that they fit in memory) which is then copied to every row of the data matrix. Here is an helper function that does exactly that from a vector of images mat."
},
{
"code": null,
"e": 6003,
"s": 5634,
"text": "cv::Mat createdatamatrix(std::vector<cv::Mat> imageArray) {cv::Mat datamatrix(static_cast<int>(imageArray.size()), imageArray[0].rows * imageArray[0].cols, CV_32F);unsigned int i;for(i=0; i < imageArray.size(); i++) { cv::Mat imageRow = imageArray[i].clone().reshape(1, 1); cv::Mat rowIData = datamatrix.row(i); imageRow.copyTo(rowIData); } return datamatrix;}"
},
{
"code": null,
"e": 6139,
"s": 6003,
"text": "cv::reshape() helps transform mat arrays to different shapes, with (1, 1) it literally means we want the data to exist in a single row."
},
{
"code": null,
"e": 6583,
"s": 6139,
"text": "Learn the actual Pricipal component analysis algorithm.Now that we have created the data table with the preprocessed face images, learning the PCA model is usually smooth. As smooth as passing the data table to an OpenCV pca instance with your expected maximum components like such cv::PCA pca(datatable, cv::Mat(), cv::PCA::DATA_AS_ROW, number_of_components). With this, we have a learned PCA written in C++ which is ready for production use."
},
{
"code": null,
"e": 6875,
"s": 6583,
"text": "To transfer this model for use in any environment, open cv has a FileStorage object that allows you to save a mat as it is. Thus I can save this file and pass its filename over jni for OpenCV to recreate the model instances for inference. Well, it simply as sweet as that to serve the model."
},
{
"code": null,
"e": 7125,
"s": 6875,
"text": "To conclude the inference part of the article, I will simply show how to write the mat object using OpenCV. At the end of the day, the values in the saved model come out as either a YAML file or XML depending on the choice most pleasant to the user."
},
{
"code": null,
"e": 7563,
"s": 7125,
"text": "Save the pca model object for inference on production environment.What exactly needs to be saved in the pca object are the mean and eigenvectors of the trained pca, sometimes it may be a good idea to also save the eigenvalues in case you want to construct your own eigenfaces projection, but OpenCV already implemented a pca->project instance that helps in inference and eigenfaces generation. In any case here is how to save your model:"
},
{
"code": null,
"e": 7823,
"s": 7563,
"text": "void Facepca::savemodel(cv::PCA pcaModel, const std::stringfilename){ cv::FileStorage fs(filename,cv::FileStorage::WRITE); fs << “mean” << pcaModel.mean; fs << “e_vectors” << pcaModel.eigenvectors; fs << “e_values” << pcaModel.eigenvalues; fs.release();}"
},
{
"code": null,
"e": 8246,
"s": 7823,
"text": "Having saved the model, the inference layer will involve loading the saved model whose values are stored in the yml file also via OpenCV and developed to form an inference engine with necessary data preprocessing modules which is finally bundled as a .so file for deployment on a linux based environment. For other platforms, the cpp codes can be compiled to produce either a dll or dylib for windows and mac respectively."
},
{
"code": null,
"e": 8406,
"s": 8246,
"text": "Since we are concerned about deploying the model on an android application more, the focus will be building the .so file inference engine from our saved model."
},
{
"code": null,
"e": 8661,
"s": 8406,
"text": "Load a PCA modelFor inference, we let OpenCV load the existing model file from the saved .yml file after which we feed the eigenvalues, eigenvectors and mean to a new PCA object which we can then call a pca->project on to create a new image’s projection."
},
{
"code": null,
"e": 8728,
"s": 8661,
"text": "Here is a sample code that loads a saved OpenCV FileStorage model."
},
{
"code": null,
"e": 9087,
"s": 8728,
"text": "cv::PCA newPcaModel;cv::PCA loadmodel(cv::PCA newPcaModel, const std::string filename){ cv::FileStorage fs(filename,cv::FileStorage::READ); fs[“mean”] >> newPcaModel.mean ; fs[“e_vectors”] >> newPcaModel.eigenvectors ; fs[“e_values”] >> newPcaModel.eigenvalues ; fs.release(); return newPcaModel;}loadmodel(newPcaModel, “path-to-saved-yml-file”);"
},
{
"code": null,
"e": 9362,
"s": 9087,
"text": "Once the model is loaded, the newPcaModel object now contains the saved model from the existing training parameters i.e pca eigenvalues, eigenvectors and mean. Hence when a face projection is done, it is guaranteed that the data returned is relative to the training dataset."
},
{
"code": null,
"e": 9568,
"s": 9362,
"text": "Create new image preprocessing and prediction stage.During inference of a machine learning model, it is important that the incoming image also passes through the same preprocessing as the training dataset."
},
{
"code": null,
"e": 9733,
"s": 9568,
"text": "Several approaches can be used to pass image to the inference engine, it could be that the image is loaded from disk or that the image is passed as a base64 string."
},
{
"code": null,
"e": 9939,
"s": 9733,
"text": "In our case, the likely approach is to use a base64 string since we are also taking into consideration two factors, that a jni will be exposed and also that our final library is for an android application."
},
{
"code": null,
"e": 10071,
"s": 9939,
"text": "With this in mind, we then need to ensure that the library is able to retrieve an image from a base64 string and send it to OpenCV."
},
{
"code": null,
"e": 10200,
"s": 10071,
"text": "Decoding a base64 string in c++ is quite non-trivial, however, a reader can refer to this link on a code snippet that does this."
},
{
"code": null,
"e": 10351,
"s": 10200,
"text": "Once the base64 image string is decoded, we then convert the string to a vector of unsigned character (uchar) which can be thought of as Image values."
},
{
"code": null,
"e": 10542,
"s": 10351,
"text": "OpenCV can decode the vector of uchar into an image using the function call to cv::imdecode(vectorUchar, flag). This process returns a Mat image with which further preprocessing can be done."
},
{
"code": null,
"e": 10603,
"s": 10542,
"text": "The image can then pass through the preprocessing phases of;"
},
{
"code": null,
"e": 10619,
"s": 10603,
"text": "Face extraction"
},
{
"code": null,
"e": 10655,
"s": 10619,
"text": "Convert cropped faces to grayscale."
},
{
"code": null,
"e": 10668,
"s": 10655,
"text": "Image resize"
},
{
"code": null,
"e": 10688,
"s": 10668,
"text": "Image normalization"
},
{
"code": null,
"e": 10707,
"s": 10688,
"text": "Create data matrix"
},
{
"code": null,
"e": 10769,
"s": 10707,
"text": "Just as described in the training part of this article above."
},
{
"code": null,
"e": 10896,
"s": 10769,
"text": "The last leg of inference on the new image is using the loaded pca object to create a projection of the face in the new image."
},
{
"code": null,
"e": 10944,
"s": 10896,
"text": "The snippet that does that will look like this:"
},
{
"code": null,
"e": 10985,
"s": 10944,
"text": "newPcaModel->project(datamatrix.row(0));"
},
{
"code": null,
"e": 11199,
"s": 10985,
"text": "The part of recognition or verification happens when you project with a loaded pca object on two faces and compare the projections (eigenfaces) using a distance metrics e.g euclidean distance or cosine similarity."
},
{
"code": null,
"e": 11471,
"s": 11199,
"text": "Package the library with an exposed jni.This part is quite straightforward, once the inference code has been properly structured, most probably within a class, then the jni body can literally call the exposed functions for the model loading, preprocessing and prediction."
},
{
"code": null,
"e": 11558,
"s": 11471,
"text": "However, to create a jni, it is important to understand how the link occurs with java."
},
{
"code": null,
"e": 11679,
"s": 11558,
"text": "The first path is to create a Java class and the functions you want to use in your java class with the input parameters."
},
{
"code": null,
"e": 11869,
"s": 11679,
"text": "This will be what the jni will use as the function name when creating the cpp code. The consistency between the classpath name of the methods in Java with the name in cpp is very important."
},
{
"code": null,
"e": 12009,
"s": 11869,
"text": "Let us assume the method we will be using for our pca feature match is named matchpcafeatures() and our java class can then look like this."
},
{
"code": null,
"e": 12158,
"s": 12009,
"text": "package org.example.codeclass MatchFeatures {static float matchpcafeatures(modelfilename: String, image: String, projectionToCompare: Array[Float])}"
},
{
"code": null,
"e": 12247,
"s": 12158,
"text": "With the above java class and method, our jni header file will look something like this."
},
{
"code": null,
"e": 12608,
"s": 12247,
"text": "#include <jni.h>/* Header for class com_example_code_MatchFeatures */#ifndef _Included_com_example_code_MatchFeatures#define _Included_com_example_code_MatchFeatures#ifdef __cplusplusextern “C” {#endifJNIEXPORT jfloat JNICALL Java_com_example_code_MatchFeatures_matchpcafeatures(JNIEnv *, jobject, jstring, jstring, jfloatArray);#ifdef __cplusplus}#endif#endif"
},
{
"code": null,
"e": 12734,
"s": 12608,
"text": "You don’t need to bother yet about the details of the extern C the focus is on the name of the method in the jni header file."
},
{
"code": null,
"e": 12870,
"s": 12734,
"text": "Further down, we will look at how to use the java code above to make an inference. Let us first develop the jni bridge for this method."
},
{
"code": null,
"e": 12992,
"s": 12870,
"text": "The last 3 parameters of the jni header are just the same and in the exact position as the parameters in the java method."
},
{
"code": null,
"e": 13118,
"s": 12992,
"text": "Therefore, we will process on those parameters since they are the key requirements from a client to our c++ inference engine."
},
{
"code": null,
"e": 13250,
"s": 13118,
"text": "Below shows how to connect those input parameters and return a value which the java code can take and continue its other processes."
},
{
"code": null,
"e": 14947,
"s": 13250,
"text": "/*** Match features of pca* */JNIEXPORT jfloat JNICALL Java_com_seamfix_qrcode_FaceFeatures_matchpcafeatures(JNIEnv * env, jobject obj, jstring pcafilename, jstring imagestring, jfloatArray projectionToCompare){ const char *pcastring_char; pcastring_char = env->GetStringUTFChars(pcafilename, 0); if(pcastring_char == NULL) { return 0.0f; } const char *imagestring_char; imagestring_char = env->GetStringUTFChars(imagestring, 0); if(imagestring_char == NULL) { return 0.0f; } //Get file name string as a string for cpp std::string stdfilename(pcastring_char); cv::PCA pca; //Class InferencPca holds the preprocesing and inference methods InferencePca ef; std::vector<cv::Mat> imagevec; //Get image as base64 cv::Mat image = ef.readBase64Image(imagestring_char); ef.loadmodel(pca, stdfilename); imagevec.push_back(image); cv::Mat datamatrix = ef.createdatamatrix(imagevec); cv::Mat projection = ef.project(datamatrix.row(0)); //Load the existing vector. std::vector<float> initialProjectionPoints; //Load existing features -- needed to do comparison of faces jsize intArrayLen = env->GetArrayLength(existingfeatures); jfloat *pointvecBody = env->GetFloatArrayElements(existingfeatures, 0); for (int i =0; i < intArrayLen; i++) { initialProjectionPoints.push_back(pointvecBody[i]); } std::vector<float> newProjectionpoints = ef.matToVector(projection); float comparisonScores = ef.compareProjections(newProjectionpoints, initialProjectionPoints); env->ReleaseFloatArrayElements(existingfeatures, pointvecBody, 0); env->ReleaseStringUTFChars(pcafilename, pcastring_char); return comparisonScores;}"
},
{
"code": null,
"e": 15110,
"s": 14947,
"text": "With this, we are set to build our .so library and release it to java code to use successfully. The protocol to build the library is stated in the CMakeLists.txt."
},
{
"code": null,
"e": 15131,
"s": 15110,
"text": "It looks like below:"
},
{
"code": null,
"e": 15393,
"s": 15131,
"text": "find_package(JNI REQUIRED)#Include jni directoriesinclude_directories(${JNI_INCLUDE_DIRS})file (GLOB_RECURSE SOURCE_FILE src/*.h src/*.cpp)set(LIBS ${JNI_LIBRARIES})add_library(matchprojection SHARED ${SOURCE_FILE})target_link_libraries(matchprojection ${LIBS})"
},
{
"code": null,
"e": 15501,
"s": 15393,
"text": "Building the project should generate a lib-matchprojection.so file which can be added to your java project."
},
{
"code": null,
"e": 15846,
"s": 15501,
"text": "However, for android, it is a little tricky in the sense that the build tool is different rather than the official cmake build toolchain, Android has its own build tool for native cpp codes. This is called Native development kit (NDK). This is what will be used to build you c++ native codes for the generated .so to be compatible with Android."
},
{
"code": null,
"e": 15956,
"s": 15846,
"text": "Building .so for android using NDK will be a whole tutorial on its own hence I will be skipping that for now."
},
{
"code": null,
"e": 16105,
"s": 15956,
"text": "But generally, once the build is complete using an NDK, you will have the same lib-matchprojection.so which can be used in your android application."
},
{
"code": null,
"e": 16218,
"s": 16105,
"text": "Using the generated library within the Android application is just the same as using it in any java application."
},
{
"code": null,
"e": 16396,
"s": 16218,
"text": "The idea is to load the native library and then make a call with the required parameter to the methods in the initially created Classes that correspond to the native jni method."
},
{
"code": null,
"e": 16636,
"s": 16396,
"text": "To load the library in any java program including android, ensure the .so library is in the classpath of your program, some will put it under a folder called lib or jniLibs. With this I can use a function call to load the library as below:"
},
{
"code": null,
"e": 16663,
"s": 16636,
"text": "System.loads(“native-lib”)"
},
{
"code": null,
"e": 16795,
"s": 16663,
"text": "Finally, I can make a call to my methods created earlier with the parameters necessary and the native code then can execute for me."
},
{
"code": null,
"e": 16942,
"s": 16795,
"text": "MatchFeatures mf = new MatchFeatures();float matchscores = mf.matchpcafeatures(storedpacfilepath, imagebase64string, anotherimageprojectionarray);"
},
{
"code": null,
"e": 17159,
"s": 16942,
"text": "If you notice carefully, the method was declared native and there is no body for the method, this is because the programmes understand that there is a native cpp method that has been defined with this classpath name."
},
{
"code": null,
"e": 17478,
"s": 17159,
"text": "This approach is a fundamental way to build and deploy a project that includes native codes in a java environment. Also, most complex algorithmic problems, including machine learning and core computer vision projects, can easily be reason around in cpp most because it is fast and there are production-ready libraries."
},
{
"code": null,
"e": 17588,
"s": 17478,
"text": "Even TensorFlow has an api for loading deep learning models in c++ as well as using its tflite models in c++."
},
{
"code": null,
"e": 17910,
"s": 17588,
"text": "Hence, I see this approach of building an inference engine with native code as a way to build robust production-ready engines that will leverage high precision mathematics and most especially the deployment of machine learning models to various environment and in particular android environment in an offline environment."
}
] |
Memory Limit Exceeded Error
|
13 Jul, 2021
Memory Limit Exceeded Error: It typically occurs when no memory limit has been set. It means that the program is trying to allocate more memory than the memory limit for the particular problem. For Example, if the memory limit is 256 MB, then there is no need to write code that requires more than 256 MB of memory. Generally, all online platforms have the same memory limit as 256 MB. There might be many more reasons due to which this error can occur.
Program 1:
Below is the C++ program to declaring a global 1D array of size 107:
C++
// C++ program to declare the array// of size 10^7 globally #include <bits/stdc++.h>using namespace std; // Variable N initializedconst int N = 1e7; // Global array is declaredint a[N]; // Driver Codeint main(){ for (int i = 0; i < N; ++i) { a[i] = i; } cout << a[N - 1]; return 0;}
9999999
Explanation: This code will successfully compile and output is 9999999 because the 1-D array has been declared globally of size 107.
Program 2: Below is the C++ program to declare a global 1D array of size 108:
C++
// C++ code declaring a global 1-D// array of size 10^8#include <bits/stdc++.h>using namespace std; // Variable N is initializedconst int N = 1e8; // Global array is declaredint a[N]; // Driver Codeint main(){ for (int i = 0; i < N; ++i) { a[i] = i; } cout << a[N - 1]; return 0;}
Output:
Memory Limit Exceeded
or
Segmentation Fault (SIGSEGV)
Explanation: In the above program, the users will get a memory limit and exceed as an error, but some online platforms can also give an error as a Segmentation Fault(SIGSEGV). This is because users can only declare a global 1-D array of size 107, not more than that. Here, one declared a global 1-D array of size 108 and therefore has an error as the memory limit exceeded (MLE) occurs.
Note:
Note that trying to exceed the memory limit may sometimes result in other errors.
An example would be if users are using malloc in C to allocate memory. If malloc fails because the user is trying to allocate too much, it simply returns a null pointer which, unless checked for it, would probably cause a Run Time Error when the user tries to use it.
Similarly, trying to allocate too much memory in C++ using new would cause a SIGABRT and give Run Time Error.
sweetyty
CPP-Basics
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 506,
"s": 52,
"text": "Memory Limit Exceeded Error: It typically occurs when no memory limit has been set. It means that the program is trying to allocate more memory than the memory limit for the particular problem. For Example, if the memory limit is 256 MB, then there is no need to write code that requires more than 256 MB of memory. Generally, all online platforms have the same memory limit as 256 MB. There might be many more reasons due to which this error can occur."
},
{
"code": null,
"e": 517,
"s": 506,
"text": "Program 1:"
},
{
"code": null,
"e": 586,
"s": 517,
"text": "Below is the C++ program to declaring a global 1D array of size 107:"
},
{
"code": null,
"e": 590,
"s": 586,
"text": "C++"
},
{
"code": "// C++ program to declare the array// of size 10^7 globally #include <bits/stdc++.h>using namespace std; // Variable N initializedconst int N = 1e7; // Global array is declaredint a[N]; // Driver Codeint main(){ for (int i = 0; i < N; ++i) { a[i] = i; } cout << a[N - 1]; return 0;}",
"e": 893,
"s": 590,
"text": null
},
{
"code": null,
"e": 901,
"s": 893,
"text": "9999999"
},
{
"code": null,
"e": 1036,
"s": 903,
"text": "Explanation: This code will successfully compile and output is 9999999 because the 1-D array has been declared globally of size 107."
},
{
"code": null,
"e": 1114,
"s": 1036,
"text": "Program 2: Below is the C++ program to declare a global 1D array of size 108:"
},
{
"code": null,
"e": 1118,
"s": 1114,
"text": "C++"
},
{
"code": "// C++ code declaring a global 1-D// array of size 10^8#include <bits/stdc++.h>using namespace std; // Variable N is initializedconst int N = 1e8; // Global array is declaredint a[N]; // Driver Codeint main(){ for (int i = 0; i < N; ++i) { a[i] = i; } cout << a[N - 1]; return 0;}",
"e": 1418,
"s": 1118,
"text": null
},
{
"code": null,
"e": 1430,
"s": 1422,
"text": "Output:"
},
{
"code": null,
"e": 1454,
"s": 1432,
"text": "Memory Limit Exceeded"
},
{
"code": null,
"e": 1459,
"s": 1456,
"text": "or"
},
{
"code": null,
"e": 1490,
"s": 1461,
"text": "Segmentation Fault (SIGSEGV)"
},
{
"code": null,
"e": 1879,
"s": 1492,
"text": "Explanation: In the above program, the users will get a memory limit and exceed as an error, but some online platforms can also give an error as a Segmentation Fault(SIGSEGV). This is because users can only declare a global 1-D array of size 107, not more than that. Here, one declared a global 1-D array of size 108 and therefore has an error as the memory limit exceeded (MLE) occurs."
},
{
"code": null,
"e": 1888,
"s": 1881,
"text": "Note: "
},
{
"code": null,
"e": 1972,
"s": 1890,
"text": "Note that trying to exceed the memory limit may sometimes result in other errors."
},
{
"code": null,
"e": 2240,
"s": 1972,
"text": "An example would be if users are using malloc in C to allocate memory. If malloc fails because the user is trying to allocate too much, it simply returns a null pointer which, unless checked for it, would probably cause a Run Time Error when the user tries to use it."
},
{
"code": null,
"e": 2350,
"s": 2240,
"text": "Similarly, trying to allocate too much memory in C++ using new would cause a SIGABRT and give Run Time Error."
},
{
"code": null,
"e": 2361,
"s": 2352,
"text": "sweetyty"
},
{
"code": null,
"e": 2372,
"s": 2361,
"text": "CPP-Basics"
},
{
"code": null,
"e": 2376,
"s": 2372,
"text": "C++"
},
{
"code": null,
"e": 2389,
"s": 2376,
"text": "C++ Programs"
},
{
"code": null,
"e": 2393,
"s": 2389,
"text": "CPP"
}
] |
Node.js Date.isValid() API
|
12 Mar, 2021
The date-and-time.Date.isValid() is a minimalist collection of functions for manipulating JS date and time module which is used to validate the particular date and time with its string format.
Required Module: Install the module by npm or used it locally.
By using npm.
npm install date-and-time --save
By using CDN link.
<script src="/path/to/date-and-time.min.js"></script>
Syntax:
isValid(arg1[, arg2])
Parameters: This method takes the following arguments as parameters:
arg1: It is the date and time object.
arg2: It is the string format of the given date.
Return Value: This method returns true if and only if the terms are validated.
Example 1:
index.js
// Node.js program to demonstrate the // Date.isValid() method // Importing date-and-time moduleconst date = require('date-and-time') // Parsing the date and time// by using date.parse() methodconst status = date.isValid('29-02-2015', 'DD-MM-YYYY'); // Display the resultif(status) console.log("Date is valid")else console.log("Date is not invalid")
Run the index.js file using the following command:
node index.js
Output:
Date is not invalid
Example 2:
index.js
// Node.js program to demonstrate the // Date.isValid() method // Importing date-and-time moduleconst date = require('date-and-time') // Pre parsing the date and time// by using preparse() methodconst result = date.preparse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss'); // Validating the terms// by using date.isValid() methodconst status = date.isValid(result); // Display the resultif(status) console.log("Date is valid")else console.log("Date is not invalid")
Run the index.js file using the following command:
node index.js
Output:
Date is valid
Reference: https://github.com/knowledgecode/date-and-time
NodeJS date-time
NodeJS-API
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 221,
"s": 28,
"text": "The date-and-time.Date.isValid() is a minimalist collection of functions for manipulating JS date and time module which is used to validate the particular date and time with its string format."
},
{
"code": null,
"e": 284,
"s": 221,
"text": "Required Module: Install the module by npm or used it locally."
},
{
"code": null,
"e": 298,
"s": 284,
"text": "By using npm."
},
{
"code": null,
"e": 331,
"s": 298,
"text": "npm install date-and-time --save"
},
{
"code": null,
"e": 350,
"s": 331,
"text": "By using CDN link."
},
{
"code": null,
"e": 404,
"s": 350,
"text": "<script src=\"/path/to/date-and-time.min.js\"></script>"
},
{
"code": null,
"e": 412,
"s": 404,
"text": "Syntax:"
},
{
"code": null,
"e": 434,
"s": 412,
"text": "isValid(arg1[, arg2])"
},
{
"code": null,
"e": 503,
"s": 434,
"text": "Parameters: This method takes the following arguments as parameters:"
},
{
"code": null,
"e": 541,
"s": 503,
"text": "arg1: It is the date and time object."
},
{
"code": null,
"e": 590,
"s": 541,
"text": "arg2: It is the string format of the given date."
},
{
"code": null,
"e": 669,
"s": 590,
"text": "Return Value: This method returns true if and only if the terms are validated."
},
{
"code": null,
"e": 680,
"s": 669,
"text": "Example 1:"
},
{
"code": null,
"e": 689,
"s": 680,
"text": "index.js"
},
{
"code": "// Node.js program to demonstrate the // Date.isValid() method // Importing date-and-time moduleconst date = require('date-and-time') // Parsing the date and time// by using date.parse() methodconst status = date.isValid('29-02-2015', 'DD-MM-YYYY'); // Display the resultif(status) console.log(\"Date is valid\")else console.log(\"Date is not invalid\")",
"e": 1045,
"s": 689,
"text": null
},
{
"code": null,
"e": 1096,
"s": 1045,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1110,
"s": 1096,
"text": "node index.js"
},
{
"code": null,
"e": 1118,
"s": 1110,
"text": "Output:"
},
{
"code": null,
"e": 1138,
"s": 1118,
"text": "Date is not invalid"
},
{
"code": null,
"e": 1149,
"s": 1138,
"text": "Example 2:"
},
{
"code": null,
"e": 1158,
"s": 1149,
"text": "index.js"
},
{
"code": "// Node.js program to demonstrate the // Date.isValid() method // Importing date-and-time moduleconst date = require('date-and-time') // Pre parsing the date and time// by using preparse() methodconst result = date.preparse('2015/01/02 23:14:05', 'YYYY/MM/DD HH:mm:ss'); // Validating the terms// by using date.isValid() methodconst status = date.isValid(result); // Display the resultif(status) console.log(\"Date is valid\")else console.log(\"Date is not invalid\")",
"e": 1629,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1680,
"s": 1629,
"text": "Run the index.js file using the following command:"
},
{
"code": null,
"e": 1694,
"s": 1680,
"text": "node index.js"
},
{
"code": null,
"e": 1702,
"s": 1694,
"text": "Output:"
},
{
"code": null,
"e": 1716,
"s": 1702,
"text": "Date is valid"
},
{
"code": null,
"e": 1774,
"s": 1716,
"text": "Reference: https://github.com/knowledgecode/date-and-time"
},
{
"code": null,
"e": 1791,
"s": 1774,
"text": "NodeJS date-time"
},
{
"code": null,
"e": 1802,
"s": 1791,
"text": "NodeJS-API"
},
{
"code": null,
"e": 1810,
"s": 1802,
"text": "Node.js"
},
{
"code": null,
"e": 1827,
"s": 1810,
"text": "Web Technologies"
},
{
"code": null,
"e": 1925,
"s": 1827,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1957,
"s": 1925,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 1992,
"s": 1957,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2062,
"s": 1992,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 2089,
"s": 2062,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 2114,
"s": 2089,
"text": "Mongoose find() Function"
},
{
"code": null,
"e": 2176,
"s": 2114,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2237,
"s": 2176,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2287,
"s": 2237,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2330,
"s": 2287,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Program to convert temperature from degree Celsius to Kelvin
|
24 May, 2022
Given temperature in degree Celsius, convert it into to Kelvin . Examples:
Input : C = 100
Output : k = 373.15
Input : C = 110
Output : k = 383.15
Formula for converting temperature in degree Celsius to kelvin-
K = ( °C + 273.15 )
0 °C = 273.15 kelvin
Below is the program for temperature conversion:
C
C++
Java
Python3
C#
PHP
Javascript
/* C Program to convert temperature from celsius to kelvin */#include <stdio.h> // function takes value in celsius and returns value in kelvinfloat celsius_to_kelvin(float c){ return (c + 273.15);} int main(){ // variable of type float holds value in celsius float c = 50; // passing 'c' as parameter to the function // printing the value in kelvin printf("Temperature in Kelvin(K) : %0.2f",celsius_to_kelvin(c)); return 0;}
// CPP program to convert temperature// from degree Celsius to kelvin#include <bits/stdc++.h>using namespace std; // function to convert temperature// from degree Celsius to Kelvinfloat Celsius_to_Kelvin(float C){ return (C + 273.15);} // driver functionint main(){ // variable to hold the // temperature in Celsius float C = 100; cout << "Temperature in Kelvin ( K ) = " << Celsius_to_Kelvin(C); return 0;}
// Java program to convert temperature// from degree Celsius to kelvinimport java.io.*; class GFG { // function to convert temperature // from degree Celsius to Kelvin static float Celsius_to_Kelvin(float C) { return (float)(C + 273.15); } // Driver function public static void main (String[] args) { // variable to hold the // temperature in Celsius float C = 100; System .out.println ( "Temperature in Kelvin ( K ) = " + Celsius_to_Kelvin(C)); }} // This code is contributed by vt_m.
# Python3 program to convert temperature# from degree Celsius to kelvin # Function to convert temperature# from degree Celsius to Kelvindef Celsius_to_Kelvin(C): return (C + 273.15) # Driver Code # variable to hold the# temperature in CelsiusC = 100 print("Temperature in Kelvin ( K ) = ", Celsius_to_Kelvin(C)) # This code is contributed by Anant Agarwal.
// C# program to convert temperature// from degree Celsius to kelvinusing System; class GFG { // function to convert temperature // from degree Celsius to Kelvin static float Celsius_to_Kelvin(float C) { return (float)(C + 273.15); } // Driver function public static void Main() { // variable to hold the // temperature in Celsius float C = 100; Console.WriteLine("Temperature in Kelvin ( K ) = " + Celsius_to_Kelvin(C)); }} // This code is contributed by vt_m.
<?php// PHP program to convert temperature// from degree Celsius to kelvin // function to convert temperature// from degree Celsius to Kelvinfunction Celsius_to_Kelvin( $C){ return ($C + 273.15);} // Driver Code // variable to hold the // temperature in Celsius $C = 100; echo "Temperature in Kelvin ( K ) = " , Celsius_to_Kelvin($C); // This code is contributed by anuj_67.?>
<script> // Javascript program to convert temperature// from degree Celsius to kelvin // function to convert temperature// from degree Celsius to Kelvinfunction Celsius_to_Kelvin(C){ return (C + 273.15);} // driver function // variable to hold the // temperature in Celsius let C = 100; document.write("Temperature in Kelvin ( K ) = " + Celsius_to_Kelvin(C)); // This code is contributed Mayank Tyagi </script>
Output:
Temperature in Kelvin ( K ) = 373.15
Time Complexity: O(1), as we are not using any loops.
Auxiliary Space: O(1), as we are not using any extra space.
vt_m
mayanktyagi1709
sonawanejaydeep11
sweetyty
rohitsingh07052
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
Operator Overloading in C++
Polymorphism in C++
Types of Operating Systems
Constructors in Java
Exceptions in Java
Friend class and function in C++
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 May, 2022"
},
{
"code": null,
"e": 105,
"s": 28,
"text": "Given temperature in degree Celsius, convert it into to Kelvin . Examples: "
},
{
"code": null,
"e": 178,
"s": 105,
"text": "Input : C = 100\nOutput : k = 373.15\n\nInput : C = 110\nOutput : k = 383.15"
},
{
"code": null,
"e": 246,
"s": 180,
"text": "Formula for converting temperature in degree Celsius to kelvin- "
},
{
"code": null,
"e": 287,
"s": 246,
"text": "K = ( °C + 273.15 )\n0 °C = 273.15 kelvin"
},
{
"code": null,
"e": 338,
"s": 287,
"text": "Below is the program for temperature conversion: "
},
{
"code": null,
"e": 340,
"s": 338,
"text": "C"
},
{
"code": null,
"e": 344,
"s": 340,
"text": "C++"
},
{
"code": null,
"e": 349,
"s": 344,
"text": "Java"
},
{
"code": null,
"e": 357,
"s": 349,
"text": "Python3"
},
{
"code": null,
"e": 360,
"s": 357,
"text": "C#"
},
{
"code": null,
"e": 364,
"s": 360,
"text": "PHP"
},
{
"code": null,
"e": 375,
"s": 364,
"text": "Javascript"
},
{
"code": "/* C Program to convert temperature from celsius to kelvin */#include <stdio.h> // function takes value in celsius and returns value in kelvinfloat celsius_to_kelvin(float c){ return (c + 273.15);} int main(){ // variable of type float holds value in celsius float c = 50; // passing 'c' as parameter to the function // printing the value in kelvin printf(\"Temperature in Kelvin(K) : %0.2f\",celsius_to_kelvin(c)); return 0;}",
"e": 809,
"s": 375,
"text": null
},
{
"code": "// CPP program to convert temperature// from degree Celsius to kelvin#include <bits/stdc++.h>using namespace std; // function to convert temperature// from degree Celsius to Kelvinfloat Celsius_to_Kelvin(float C){ return (C + 273.15);} // driver functionint main(){ // variable to hold the // temperature in Celsius float C = 100; cout << \"Temperature in Kelvin ( K ) = \" << Celsius_to_Kelvin(C); return 0;}",
"e": 1249,
"s": 809,
"text": null
},
{
"code": "// Java program to convert temperature// from degree Celsius to kelvinimport java.io.*; class GFG { // function to convert temperature // from degree Celsius to Kelvin static float Celsius_to_Kelvin(float C) { return (float)(C + 273.15); } // Driver function public static void main (String[] args) { // variable to hold the // temperature in Celsius float C = 100; System .out.println ( \"Temperature in Kelvin ( K ) = \" + Celsius_to_Kelvin(C)); }} // This code is contributed by vt_m.",
"e": 1848,
"s": 1249,
"text": null
},
{
"code": "# Python3 program to convert temperature# from degree Celsius to kelvin # Function to convert temperature# from degree Celsius to Kelvindef Celsius_to_Kelvin(C): return (C + 273.15) # Driver Code # variable to hold the# temperature in CelsiusC = 100 print(\"Temperature in Kelvin ( K ) = \", Celsius_to_Kelvin(C)) # This code is contributed by Anant Agarwal.",
"e": 2247,
"s": 1848,
"text": null
},
{
"code": "// C# program to convert temperature// from degree Celsius to kelvinusing System; class GFG { // function to convert temperature // from degree Celsius to Kelvin static float Celsius_to_Kelvin(float C) { return (float)(C + 273.15); } // Driver function public static void Main() { // variable to hold the // temperature in Celsius float C = 100; Console.WriteLine(\"Temperature in Kelvin ( K ) = \" + Celsius_to_Kelvin(C)); }} // This code is contributed by vt_m.",
"e": 2816,
"s": 2247,
"text": null
},
{
"code": "<?php// PHP program to convert temperature// from degree Celsius to kelvin // function to convert temperature// from degree Celsius to Kelvinfunction Celsius_to_Kelvin( $C){ return ($C + 273.15);} // Driver Code // variable to hold the // temperature in Celsius $C = 100; echo \"Temperature in Kelvin ( K ) = \" , Celsius_to_Kelvin($C); // This code is contributed by anuj_67.?>",
"e": 3232,
"s": 2816,
"text": null
},
{
"code": "<script> // Javascript program to convert temperature// from degree Celsius to kelvin // function to convert temperature// from degree Celsius to Kelvinfunction Celsius_to_Kelvin(C){ return (C + 273.15);} // driver function // variable to hold the // temperature in Celsius let C = 100; document.write(\"Temperature in Kelvin ( K ) = \" + Celsius_to_Kelvin(C)); // This code is contributed Mayank Tyagi </script>",
"e": 3667,
"s": 3232,
"text": null
},
{
"code": null,
"e": 3676,
"s": 3667,
"text": "Output: "
},
{
"code": null,
"e": 3713,
"s": 3676,
"text": "Temperature in Kelvin ( K ) = 373.15"
},
{
"code": null,
"e": 3767,
"s": 3713,
"text": "Time Complexity: O(1), as we are not using any loops."
},
{
"code": null,
"e": 3827,
"s": 3767,
"text": "Auxiliary Space: O(1), as we are not using any extra space."
},
{
"code": null,
"e": 3832,
"s": 3827,
"text": "vt_m"
},
{
"code": null,
"e": 3848,
"s": 3832,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 3866,
"s": 3848,
"text": "sonawanejaydeep11"
},
{
"code": null,
"e": 3875,
"s": 3866,
"text": "sweetyty"
},
{
"code": null,
"e": 3891,
"s": 3875,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 3910,
"s": 3891,
"text": "School Programming"
},
{
"code": null,
"e": 4008,
"s": 3910,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4031,
"s": 4008,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4050,
"s": 4031,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4078,
"s": 4050,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 4098,
"s": 4078,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 4125,
"s": 4098,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 4146,
"s": 4125,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4165,
"s": 4146,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4198,
"s": 4165,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 4243,
"s": 4198,
"text": "Different Methods to Reverse a String in C++"
}
] |
How do you display JavaScript datetime in 12 hour AM/PM format?
|
28 Jun, 2019
JavaScript uses the 24-hour format as default for DateTime. However, daytime in JavaScript can be displayed in 12 hour AM/PM format using several approaches. We will look into a couple in this article.
Approach 1:In this approach, we will change the DateTime format by only using native methods. Simply put, we will apply modulo “%” operator to find the hour in 12-hour format and use conditional “?:” operator to apply “AM” or “PM”.
Program:
<!DOCTYPE html><html> <body> <center> <h1 style="color:green"> GeeksforGeeks </h1> <p> Click the button to change the format using Native method. </p> <div id="old_time"></div> <script> // JavaScript Program to display // current time in 24-hour format var date = new Date(); var hours = (date.getHours() < 10 ? '0' : '') + date.getHours(); var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); var div = document.getElementById('old_time'); div.innerHTML = hours + ":" + minutes; </script> <button onclick="myFunction()"> Change </button> <p id="change"></p> <script> // JavaScript function to // Display 12 hour format function myFunction() { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); // Check whether AM or PM var newformat = hours >= 12 ? 'PM' : 'AM'; // Find current hour in AM-PM Format hours = hours % 12; // To display "0" as "12" hours = hours ? hours : 12; minutes = minutes < 10 ? '0' + minutes : minutes; document.getElementById("change").innerHTML = hours + ':' + minutes + ' ' + newformat; } </script> </center></body> </html>
Before:
After:
Approach 2:In this approach, we will utilize an inbuilt method toLocaleString() to change the format of given date into AM-PM format.
toLocaleString(): It returns a string representation of the date Object. The 2 arguments Locale and options allow for customization of the behavior of the method.
Syntax:
dateObject.toLocaleString([locales[, options]])
Program:
<!DOCTYPE html><html> <body> <center> <h1 style="color:green">GeeksforGeeks</h1> <p>Click the button to change the format.</p> <div id="old_time"></div> <script> var date = new Date(); var hours = (date.getHours() < 10 ? '0' : '') + date.getHours(); var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); var div = document.getElementById('old_time'); div.innerHTML = hours + ":" + minutes; </script> <button onclick="myFunction()"> Change </button> <p id="change"></p> <script> var now = new Date(); var hours = now.getHours(); function myFunction() { var d = new Date(); var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' }); document.getElementById("change").innerHTML = n; } </script> </center></body> </html>
Before:
After:
javascript-date
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 230,
"s": 28,
"text": "JavaScript uses the 24-hour format as default for DateTime. However, daytime in JavaScript can be displayed in 12 hour AM/PM format using several approaches. We will look into a couple in this article."
},
{
"code": null,
"e": 462,
"s": 230,
"text": "Approach 1:In this approach, we will change the DateTime format by only using native methods. Simply put, we will apply modulo “%” operator to find the hour in 12-hour format and use conditional “?:” operator to apply “AM” or “PM”."
},
{
"code": null,
"e": 471,
"s": 462,
"text": "Program:"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\"> GeeksforGeeks </h1> <p> Click the button to change the format using Native method. </p> <div id=\"old_time\"></div> <script> // JavaScript Program to display // current time in 24-hour format var date = new Date(); var hours = (date.getHours() < 10 ? '0' : '') + date.getHours(); var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); var div = document.getElementById('old_time'); div.innerHTML = hours + \":\" + minutes; </script> <button onclick=\"myFunction()\"> Change </button> <p id=\"change\"></p> <script> // JavaScript function to // Display 12 hour format function myFunction() { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); // Check whether AM or PM var newformat = hours >= 12 ? 'PM' : 'AM'; // Find current hour in AM-PM Format hours = hours % 12; // To display \"0\" as \"12\" hours = hours ? hours : 12; minutes = minutes < 10 ? '0' + minutes : minutes; document.getElementById(\"change\").innerHTML = hours + ':' + minutes + ' ' + newformat; } </script> </center></body> </html>",
"e": 2118,
"s": 471,
"text": null
},
{
"code": null,
"e": 2126,
"s": 2118,
"text": "Before:"
},
{
"code": null,
"e": 2133,
"s": 2126,
"text": "After:"
},
{
"code": null,
"e": 2267,
"s": 2133,
"text": "Approach 2:In this approach, we will utilize an inbuilt method toLocaleString() to change the format of given date into AM-PM format."
},
{
"code": null,
"e": 2430,
"s": 2267,
"text": "toLocaleString(): It returns a string representation of the date Object. The 2 arguments Locale and options allow for customization of the behavior of the method."
},
{
"code": null,
"e": 2438,
"s": 2430,
"text": "Syntax:"
},
{
"code": null,
"e": 2487,
"s": 2438,
"text": "dateObject.toLocaleString([locales[, options]])\n"
},
{
"code": null,
"e": 2496,
"s": 2487,
"text": "Program:"
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green\">GeeksforGeeks</h1> <p>Click the button to change the format.</p> <div id=\"old_time\"></div> <script> var date = new Date(); var hours = (date.getHours() < 10 ? '0' : '') + date.getHours(); var minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes(); var div = document.getElementById('old_time'); div.innerHTML = hours + \":\" + minutes; </script> <button onclick=\"myFunction()\"> Change </button> <p id=\"change\"></p> <script> var now = new Date(); var hours = now.getHours(); function myFunction() { var d = new Date(); var n = d.toLocaleString([], { hour: '2-digit', minute: '2-digit' }); document.getElementById(\"change\").innerHTML = n; } </script> </center></body> </html>",
"e": 3564,
"s": 2496,
"text": null
},
{
"code": null,
"e": 3572,
"s": 3564,
"text": "Before:"
},
{
"code": null,
"e": 3579,
"s": 3572,
"text": "After:"
},
{
"code": null,
"e": 3595,
"s": 3579,
"text": "javascript-date"
},
{
"code": null,
"e": 3611,
"s": 3595,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3618,
"s": 3611,
"text": "Picked"
},
{
"code": null,
"e": 3629,
"s": 3618,
"text": "JavaScript"
},
{
"code": null,
"e": 3646,
"s": 3629,
"text": "Web Technologies"
},
{
"code": null,
"e": 3744,
"s": 3646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3805,
"s": 3744,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3877,
"s": 3805,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3917,
"s": 3877,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3969,
"s": 3917,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 4010,
"s": 3969,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 4072,
"s": 4010,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4105,
"s": 4072,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4166,
"s": 4105,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4216,
"s": 4166,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Ruby | String chomp! Method
|
13 Dec, 2019
chomp! is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also removes carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t. If $/ is an empty string, it will remove all trailing newlines from the string. It will return nil if no modifications were made.
Syntax: str.chomp!
Parameters: Here, str is the given string.
Returns: A new string having no record separator from the end or nil if no changes were made.
Example 1:
# Ruby program to demonstrate # the chomp! method # Taking a string and # using the method puts "Ruby".chomp!puts "Ruby\r\n".chomp
Output:
Ruby
Example 2:
# Ruby program to demonstrate # the chomp! method # Taking a string and # using the method puts "String\r\n\r\r\n".chomp!('')puts "Method".chomp!("tho")
Output:
String
Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2019"
},
{
"code": null,
"e": 478,
"s": 28,
"text": "chomp! is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also removes carriage return characters (that is it will remove \\n, \\r, and \\r\\n) if $/ has not been changed from the default Ruby record separator, t. If $/ is an empty string, it will remove all trailing newlines from the string. It will return nil if no modifications were made."
},
{
"code": null,
"e": 497,
"s": 478,
"text": "Syntax: str.chomp!"
},
{
"code": null,
"e": 540,
"s": 497,
"text": "Parameters: Here, str is the given string."
},
{
"code": null,
"e": 634,
"s": 540,
"text": "Returns: A new string having no record separator from the end or nil if no changes were made."
},
{
"code": null,
"e": 645,
"s": 634,
"text": "Example 1:"
},
{
"code": "# Ruby program to demonstrate # the chomp! method # Taking a string and # using the method puts \"Ruby\".chomp!puts \"Ruby\\r\\n\".chomp ",
"e": 784,
"s": 645,
"text": null
},
{
"code": null,
"e": 792,
"s": 784,
"text": "Output:"
},
{
"code": null,
"e": 799,
"s": 792,
"text": "\nRuby\n"
},
{
"code": null,
"e": 810,
"s": 799,
"text": "Example 2:"
},
{
"code": "# Ruby program to demonstrate # the chomp! method # Taking a string and # using the method puts \"String\\r\\n\\r\\r\\n\".chomp!('')puts \"Method\".chomp!(\"tho\")",
"e": 970,
"s": 810,
"text": null
},
{
"code": null,
"e": 978,
"s": 970,
"text": "Output:"
},
{
"code": null,
"e": 988,
"s": 978,
"text": "String\n\n\n"
},
{
"code": null,
"e": 1006,
"s": 988,
"text": "Ruby String-class"
},
{
"code": null,
"e": 1019,
"s": 1006,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1024,
"s": 1019,
"text": "Ruby"
}
] |
Python | os.chmod method
|
21 Sep, 2018
os.chmod() method in Python is used to change the mode of path to the numeric mode.
Syntax:
os.chmod(path, mode)
Parameters:path – path name of the file or directory pathmode – mode may take one of the following values:
stat.S_ISUID : Set user ID on execution
stat.S_ISGID : Set group ID on execution
stat.S_ENFMT : Record locking enforced
stat.S_ISVTX : Save text image after execution
stat.S_IREAD : Read by owner.
stat.S_IWRITE : Write by owner.
stat.S_IEXEC : Execute by owner.
stat.S_IRWXU : Read, write, and execute by owner
stat.S_IRUSR : Read by owner
stat.S_IWUSR : Write by owner.
stat.S_IXUSR : Execute by owner.
stat.S_IRWXG : Read, write, and execute by group
stat.S_IRGRP : Read by group
stat.S_IWGRP : Write by group
stat.S_IXGRP : Execute by group
stat.S_IRWXO : Read, write, and execute by others.
stat.S_IROTH : Read by others
stat.S_IWOTH : Write by others
stat.S_IXOTH : Execute by others
Code #1:
# Python program to explain os.chmod() method # importing necessary librariesimport os, sys, stat # Set given file read by the owner.os.chmod("/Geeks/gfg.txt", stat.S_IREAD)print("File can be read only by owner.") # Set given file read by others.os.chmod("/Geeks/gfg.txt", stat.S_IROTH)print("File access changed, can be read by others now.")
Output:
File can be read only by owner.
File access changed, can be read by others now.
Code #2:
# Python program to explain os.chmod() method # importing necessary librariesimport os, sys, stat # Set given file written by the owner.os.chmod("/Geeks/gfg.txt", stat.S_IWRITE) # Set given file executed by the owner.os.chmod("/Geeks/gfg.txt", stat.S_IXUSR)print("File can be written and executed only by owner.")
Output:
File can be written and executed only by owner.
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Sep, 2018"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "os.chmod() method in Python is used to change the mode of path to the numeric mode."
},
{
"code": null,
"e": 120,
"s": 112,
"text": "Syntax:"
},
{
"code": null,
"e": 141,
"s": 120,
"text": "os.chmod(path, mode)"
},
{
"code": null,
"e": 248,
"s": 141,
"text": "Parameters:path – path name of the file or directory pathmode – mode may take one of the following values:"
},
{
"code": null,
"e": 288,
"s": 248,
"text": "stat.S_ISUID : Set user ID on execution"
},
{
"code": null,
"e": 329,
"s": 288,
"text": "stat.S_ISGID : Set group ID on execution"
},
{
"code": null,
"e": 368,
"s": 329,
"text": "stat.S_ENFMT : Record locking enforced"
},
{
"code": null,
"e": 415,
"s": 368,
"text": "stat.S_ISVTX : Save text image after execution"
},
{
"code": null,
"e": 445,
"s": 415,
"text": "stat.S_IREAD : Read by owner."
},
{
"code": null,
"e": 477,
"s": 445,
"text": "stat.S_IWRITE : Write by owner."
},
{
"code": null,
"e": 510,
"s": 477,
"text": "stat.S_IEXEC : Execute by owner."
},
{
"code": null,
"e": 559,
"s": 510,
"text": "stat.S_IRWXU : Read, write, and execute by owner"
},
{
"code": null,
"e": 588,
"s": 559,
"text": "stat.S_IRUSR : Read by owner"
},
{
"code": null,
"e": 619,
"s": 588,
"text": "stat.S_IWUSR : Write by owner."
},
{
"code": null,
"e": 652,
"s": 619,
"text": "stat.S_IXUSR : Execute by owner."
},
{
"code": null,
"e": 701,
"s": 652,
"text": "stat.S_IRWXG : Read, write, and execute by group"
},
{
"code": null,
"e": 730,
"s": 701,
"text": "stat.S_IRGRP : Read by group"
},
{
"code": null,
"e": 760,
"s": 730,
"text": "stat.S_IWGRP : Write by group"
},
{
"code": null,
"e": 792,
"s": 760,
"text": "stat.S_IXGRP : Execute by group"
},
{
"code": null,
"e": 843,
"s": 792,
"text": "stat.S_IRWXO : Read, write, and execute by others."
},
{
"code": null,
"e": 873,
"s": 843,
"text": "stat.S_IROTH : Read by others"
},
{
"code": null,
"e": 904,
"s": 873,
"text": "stat.S_IWOTH : Write by others"
},
{
"code": null,
"e": 937,
"s": 904,
"text": "stat.S_IXOTH : Execute by others"
},
{
"code": null,
"e": 946,
"s": 937,
"text": "Code #1:"
},
{
"code": "# Python program to explain os.chmod() method # importing necessary librariesimport os, sys, stat # Set given file read by the owner.os.chmod(\"/Geeks/gfg.txt\", stat.S_IREAD)print(\"File can be read only by owner.\") # Set given file read by others.os.chmod(\"/Geeks/gfg.txt\", stat.S_IROTH)print(\"File access changed, can be read by others now.\")",
"e": 1292,
"s": 946,
"text": null
},
{
"code": null,
"e": 1300,
"s": 1292,
"text": "Output:"
},
{
"code": null,
"e": 1381,
"s": 1300,
"text": "File can be read only by owner.\nFile access changed, can be read by others now.\n"
},
{
"code": null,
"e": 1391,
"s": 1381,
"text": " Code #2:"
},
{
"code": "# Python program to explain os.chmod() method # importing necessary librariesimport os, sys, stat # Set given file written by the owner.os.chmod(\"/Geeks/gfg.txt\", stat.S_IWRITE) # Set given file executed by the owner.os.chmod(\"/Geeks/gfg.txt\", stat.S_IXUSR)print(\"File can be written and executed only by owner.\")",
"e": 1708,
"s": 1391,
"text": null
},
{
"code": null,
"e": 1716,
"s": 1708,
"text": "Output:"
},
{
"code": null,
"e": 1764,
"s": 1716,
"text": "File can be written and executed only by owner."
},
{
"code": null,
"e": 1781,
"s": 1764,
"text": "python-os-module"
},
{
"code": null,
"e": 1788,
"s": 1781,
"text": "Python"
},
{
"code": null,
"e": 1886,
"s": 1788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1904,
"s": 1886,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1946,
"s": 1904,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1968,
"s": 1946,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2003,
"s": 1968,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2029,
"s": 2003,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2061,
"s": 2029,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2090,
"s": 2061,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2120,
"s": 2090,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2147,
"s": 2120,
"text": "Python Classes and Objects"
}
] |
ReactJS | useEffect Hook
|
26 Jan, 2022
The motivation behind the introduction of useEffect Hook is to eliminate the side-effects of using class-based components. For example, tasks like updating the DOM, fetching data from API end-points, setting up subscriptions or timers, etc can be lead to unwarranted side-effects. Since the render method is to quick to produce a side-effect one needs to use life cycle methods to observe the side effects. For example, consider updating the document title for a simple counter component to the current value. On the initial render, we set the current clicked value to 0 clicks. So, this section is coded into the componentDidMount() method which is executed only once in the component life cycle. Then we create a button to increment the count state value by one on every click. As the count value state changes, we also need to update the document title again and for that, we need to write the same piece of code in componentDidUpdate(). The componentDidupdate() method is perfect for updating the counter value at any time the state changes but the repetition of code is one of the side-effects.
Javascript
componentDidMount(){ document.title = `you clicked ${this.state.count} times`;} componentDidUpdate(){ document.title = `you clicked ${this.state.count} times`;}
Let us consider another side-effect by setting up a timer. On the componentDidMount() method, we set a timer to log a string “hello” every 5 seconds. We can clear this timer when the component is being removed from the DOM. And we do that in componentWillUnmount() life-cycle method. So the code for the timer looks like below:
Javascript
componentDidMount(){ this.interval = setInterval(this.tick, 1000)} componentWillUnmount(){ clearInterval(this.interval)}
Both the counter and timer when merged to form a single component looks like below:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Javascript
componentDidMount(){ document.title = `you clicked ${this.state.count} times`; this.interval = setInterval(this.tick, 1000) } componentDidUpdate(){ document.title = `you clicked ${this.state.count} times`; clearInterval(this.interval)}
As you observe the code above, we tend to notice that to update the document title we write the same code twice, once in componentDidmount() and once in componentDidUpdate(). The second thing to observe is how the code is split into the component. The code related to the timer, setInterval, and clearInterval which are related are put into different code blocks (i.e. different life-cycle methods). The code to update the DOM and code for setting up the timer which is completely unrelated are put in the same life-cycle method (i.e. in componentDidMount()). It will be much better if there is an option to not repeat code at the same time group together related codes in the same block. This is where the useEffect Hook comes in the picture. The Effect Hook lets you perform side effects in functional components. It is a close replacement for componentDidMount(), componentDidUpdate() and componentWillUnmount() method.
useEffect after render: We know that, the useEffect() is used for causing side effects in functional components and it is also capable for handling componentDidMount(), componentDidUpdate() and componentWillUnmount() life-cycle methods of class based components into functional component. Let’s look at an example on how to use the useEffect hook as a feature that can mimic the above mentioned life-cycle methods but in functional components.
For better understanding lets look how the code looks like in a class component below and we are going to name it “ClassComponentOne”
Filename: src/components/ClassCounterOne.js
Javascript
import React, { Component } from 'react' class ClassCounterOne extends Component { constructor(props){ super(props) this.state = { count: 0 } } componentDidMount(){ document.title = `Clicked ${this.state.count} times`} componentDidUpdate(prevProps, prevState){ document.title = `Clicked ${this.state.count} times`} render() { return ( <div> <button onClick = {() => this.setState( { count: this.state.count + 1})}> Click {this.state.count} times </button> </div> )} export default ClassCounterOne
Now, we include the component in App.js. The code will look like below for App.js
Filename: src/App.js
Javascript
import React from 'react'import './App.css'import ClassCounterOne from './components/classCounterOne' function App(){ return( <div className='App'> <ClassCounterOne /> </div> )} export default App
Now if we look at the browser we can observe that initially the document title is “Clicked 0 times”.
And if we click on the button the count value increments by 1 on each click and updates the title as well.
Now let’s try to replace the functionality with a functional component. For the same purpose create a new file and name it (say, HookCounterOne.js)
The functional component will look like the code below:
Filename: src/components/HookCounterOne.js
Javascript
import React, { useState, useEffect } from 'react' function HookCounterOne() { const [count, setCount] = useState(0) useEffect(() => { document.title = `You clicked ${count} times` return ( <div> <button onClick = {() => setCount(count + 1)}> Click {count} times </button> </div> )}export default HookCounterOne
Now we need to import the above component in our App.js file. After the inclusion of the HookCounterOne component, the code looks like below:
Filename: src/App.js
Javascript
import React from 'react'import './App.css'import ClassCounterOne from './components/classCounterOne' function App(){ return( <div className='App'> <HooKCounterOne /> </div> )} export default App
Now if we look into the browser we can see the initial state as below. Initially, the document title reads “You clicked 0 times”.
And when you click on the button, the count value increments, and the document title is updated. As we can observe the behavior is as expected.
When we specify useEffect we are basically requesting react to execute the function that we pass in the useEffect function as an argument, everytime the component renders. The second thing to make note of is that useeffect is used inside the component as by doing this we can easily access the components state and props without having to write any additional code.
adnanirshad158
girisangam823
react-js
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Jan, 2022"
},
{
"code": null,
"e": 1154,
"s": 54,
"text": "The motivation behind the introduction of useEffect Hook is to eliminate the side-effects of using class-based components. For example, tasks like updating the DOM, fetching data from API end-points, setting up subscriptions or timers, etc can be lead to unwarranted side-effects. Since the render method is to quick to produce a side-effect one needs to use life cycle methods to observe the side effects. For example, consider updating the document title for a simple counter component to the current value. On the initial render, we set the current clicked value to 0 clicks. So, this section is coded into the componentDidMount() method which is executed only once in the component life cycle. Then we create a button to increment the count state value by one on every click. As the count value state changes, we also need to update the document title again and for that, we need to write the same piece of code in componentDidUpdate(). The componentDidupdate() method is perfect for updating the counter value at any time the state changes but the repetition of code is one of the side-effects."
},
{
"code": null,
"e": 1165,
"s": 1154,
"text": "Javascript"
},
{
"code": "componentDidMount(){ document.title = `you clicked ${this.state.count} times`;} componentDidUpdate(){ document.title = `you clicked ${this.state.count} times`;}",
"e": 1332,
"s": 1165,
"text": null
},
{
"code": null,
"e": 1660,
"s": 1332,
"text": "Let us consider another side-effect by setting up a timer. On the componentDidMount() method, we set a timer to log a string “hello” every 5 seconds. We can clear this timer when the component is being removed from the DOM. And we do that in componentWillUnmount() life-cycle method. So the code for the timer looks like below:"
},
{
"code": null,
"e": 1671,
"s": 1660,
"text": "Javascript"
},
{
"code": "componentDidMount(){ this.interval = setInterval(this.tick, 1000)} componentWillUnmount(){ clearInterval(this.interval)}",
"e": 1798,
"s": 1671,
"text": null
},
{
"code": null,
"e": 1882,
"s": 1798,
"text": "Both the counter and timer when merged to form a single component looks like below:"
},
{
"code": null,
"e": 1891,
"s": 1882,
"text": "Chapters"
},
{
"code": null,
"e": 1918,
"s": 1891,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1968,
"s": 1918,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1991,
"s": 1968,
"text": "captions off, selected"
},
{
"code": null,
"e": 1999,
"s": 1991,
"text": "English"
},
{
"code": null,
"e": 2017,
"s": 1999,
"text": "default, selected"
},
{
"code": null,
"e": 2041,
"s": 2017,
"text": "This is a modal window."
},
{
"code": null,
"e": 2110,
"s": 2041,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 2132,
"s": 2110,
"text": "End of dialog window."
},
{
"code": null,
"e": 2143,
"s": 2132,
"text": "Javascript"
},
{
"code": "componentDidMount(){ document.title = `you clicked ${this.state.count} times`; this.interval = setInterval(this.tick, 1000) } componentDidUpdate(){ document.title = `you clicked ${this.state.count} times`; clearInterval(this.interval)}",
"e": 2391,
"s": 2143,
"text": null
},
{
"code": null,
"e": 3314,
"s": 2391,
"text": "As you observe the code above, we tend to notice that to update the document title we write the same code twice, once in componentDidmount() and once in componentDidUpdate(). The second thing to observe is how the code is split into the component. The code related to the timer, setInterval, and clearInterval which are related are put into different code blocks (i.e. different life-cycle methods). The code to update the DOM and code for setting up the timer which is completely unrelated are put in the same life-cycle method (i.e. in componentDidMount()). It will be much better if there is an option to not repeat code at the same time group together related codes in the same block. This is where the useEffect Hook comes in the picture. The Effect Hook lets you perform side effects in functional components. It is a close replacement for componentDidMount(), componentDidUpdate() and componentWillUnmount() method."
},
{
"code": null,
"e": 3759,
"s": 3314,
"text": "useEffect after render: We know that, the useEffect() is used for causing side effects in functional components and it is also capable for handling componentDidMount(), componentDidUpdate() and componentWillUnmount() life-cycle methods of class based components into functional component. Let’s look at an example on how to use the useEffect hook as a feature that can mimic the above mentioned life-cycle methods but in functional components. "
},
{
"code": null,
"e": 3893,
"s": 3759,
"text": "For better understanding lets look how the code looks like in a class component below and we are going to name it “ClassComponentOne”"
},
{
"code": null,
"e": 3939,
"s": 3893,
"text": "Filename: src/components/ClassCounterOne.js "
},
{
"code": null,
"e": 3950,
"s": 3939,
"text": "Javascript"
},
{
"code": "import React, { Component } from 'react' class ClassCounterOne extends Component { constructor(props){ super(props) this.state = { count: 0 } } componentDidMount(){ document.title = `Clicked ${this.state.count} times`} componentDidUpdate(prevProps, prevState){ document.title = `Clicked ${this.state.count} times`} render() { return ( <div> <button onClick = {() => this.setState( { count: this.state.count + 1})}> Click {this.state.count} times </button> </div> )} export default ClassCounterOne",
"e": 4565,
"s": 3950,
"text": null
},
{
"code": null,
"e": 4647,
"s": 4565,
"text": "Now, we include the component in App.js. The code will look like below for App.js"
},
{
"code": null,
"e": 4669,
"s": 4647,
"text": "Filename: src/App.js "
},
{
"code": null,
"e": 4680,
"s": 4669,
"text": "Javascript"
},
{
"code": "import React from 'react'import './App.css'import ClassCounterOne from './components/classCounterOne' function App(){ return( <div className='App'> <ClassCounterOne /> </div> )} export default App",
"e": 4904,
"s": 4680,
"text": null
},
{
"code": null,
"e": 5006,
"s": 4904,
"text": "Now if we look at the browser we can observe that initially the document title is “Clicked 0 times”. "
},
{
"code": null,
"e": 5114,
"s": 5006,
"text": "And if we click on the button the count value increments by 1 on each click and updates the title as well. "
},
{
"code": null,
"e": 5263,
"s": 5114,
"text": "Now let’s try to replace the functionality with a functional component. For the same purpose create a new file and name it (say, HookCounterOne.js) "
},
{
"code": null,
"e": 5319,
"s": 5263,
"text": "The functional component will look like the code below:"
},
{
"code": null,
"e": 5363,
"s": 5319,
"text": "Filename: src/components/HookCounterOne.js "
},
{
"code": null,
"e": 5374,
"s": 5363,
"text": "Javascript"
},
{
"code": "import React, { useState, useEffect } from 'react' function HookCounterOne() { const [count, setCount] = useState(0) useEffect(() => { document.title = `You clicked ${count} times` return ( <div> <button onClick = {() => setCount(count + 1)}> Click {count} times </button> </div> )}export default HookCounterOne",
"e": 5749,
"s": 5374,
"text": null
},
{
"code": null,
"e": 5891,
"s": 5749,
"text": "Now we need to import the above component in our App.js file. After the inclusion of the HookCounterOne component, the code looks like below:"
},
{
"code": null,
"e": 5913,
"s": 5891,
"text": "Filename: src/App.js "
},
{
"code": null,
"e": 5924,
"s": 5913,
"text": "Javascript"
},
{
"code": "import React from 'react'import './App.css'import ClassCounterOne from './components/classCounterOne' function App(){ return( <div className='App'> <HooKCounterOne /> </div> )} export default App",
"e": 6147,
"s": 5924,
"text": null
},
{
"code": null,
"e": 6278,
"s": 6147,
"text": "Now if we look into the browser we can see the initial state as below. Initially, the document title reads “You clicked 0 times”. "
},
{
"code": null,
"e": 6424,
"s": 6278,
"text": "And when you click on the button, the count value increments, and the document title is updated. As we can observe the behavior is as expected. "
},
{
"code": null,
"e": 6791,
"s": 6424,
"text": "When we specify useEffect we are basically requesting react to execute the function that we pass in the useEffect function as an argument, everytime the component renders. The second thing to make note of is that useeffect is used inside the component as by doing this we can easily access the components state and props without having to write any additional code. "
},
{
"code": null,
"e": 6806,
"s": 6791,
"text": "adnanirshad158"
},
{
"code": null,
"e": 6820,
"s": 6806,
"text": "girisangam823"
},
{
"code": null,
"e": 6829,
"s": 6820,
"text": "react-js"
},
{
"code": null,
"e": 6846,
"s": 6829,
"text": "Web Technologies"
},
{
"code": null,
"e": 6862,
"s": 6846,
"text": "Write From Home"
},
{
"code": null,
"e": 6960,
"s": 6862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6993,
"s": 6960,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 7055,
"s": 6993,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 7116,
"s": 7055,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 7166,
"s": 7116,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 7209,
"s": 7166,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 7245,
"s": 7209,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 7281,
"s": 7245,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 7342,
"s": 7281,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 7358,
"s": 7342,
"text": "Python infinity"
}
] |
Python program to print positive numbers in a list
|
26 Oct, 2018
Given a list of numbers, write a Python program to print all positive numbers in given list.
Example:
Input: list1 = [12, -7, 5, 64, -14]
Output: 12, 5, 64
Input: list2 = [12, 14, -95, 3]
Output: [12, 14, 3]
Example #1: Print all positive numbers from given list using for loop
Iterate each element in the list using for loop and check if number is greater than or equal to 0. If the condition satisfies, then only print the number.
# Python program to print positive Numbers in a List # list of numberslist1 = [11, -21, 0, 45, 66, -93] # iterating each number in listfor num in list1: # checking condition if num >= 0: print(num, end = " ")
Output:
11 0 45 66
Example #2: Using while loop
# Python program to print positive Numbers in a List # list of numberslist1 = [-10, 21, -4, -45, -66, 93]num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] >= 0: print(list1[num], end = " ") # increment num num += 1
Output:
21 93
Example #3: Using list comprehension
# Python program to print Positive Numbers in a List # list of numberslist1 = [-10, -21, -4, 45, -66, 93] # using list comprehensionpos_nos = [num for num in list1 if num >= 0] print("Positive numbers in the list: ", *pos_nos)
Output:
Positive numbers in the list: 45 93
Example #4: Using lambda expressions
# Python program to print positive Numbers in a List # list of numbers list1 = [-10, 21, 4, -45, -66, 93, -11] # we can also print positive no's using lambda exp. pos_nos = list(filter(lambda x: (x >= 0), list1)) print("Positive numbers in the list: ", *pos_nos)
Output:
Positive numbers in the list: 21, 4, 93
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Oct, 2018"
},
{
"code": null,
"e": 145,
"s": 52,
"text": "Given a list of numbers, write a Python program to print all positive numbers in given list."
},
{
"code": null,
"e": 154,
"s": 145,
"text": "Example:"
},
{
"code": null,
"e": 261,
"s": 154,
"text": "Input: list1 = [12, -7, 5, 64, -14]\nOutput: 12, 5, 64\n\nInput: list2 = [12, 14, -95, 3]\nOutput: [12, 14, 3]"
},
{
"code": null,
"e": 331,
"s": 261,
"text": "Example #1: Print all positive numbers from given list using for loop"
},
{
"code": null,
"e": 486,
"s": 331,
"text": "Iterate each element in the list using for loop and check if number is greater than or equal to 0. If the condition satisfies, then only print the number."
},
{
"code": "# Python program to print positive Numbers in a List # list of numberslist1 = [11, -21, 0, 45, 66, -93] # iterating each number in listfor num in list1: # checking condition if num >= 0: print(num, end = \" \")",
"e": 715,
"s": 486,
"text": null
},
{
"code": null,
"e": 723,
"s": 715,
"text": "Output:"
},
{
"code": null,
"e": 735,
"s": 723,
"text": "11 0 45 66 "
},
{
"code": null,
"e": 765,
"s": 735,
"text": " Example #2: Using while loop"
},
{
"code": "# Python program to print positive Numbers in a List # list of numberslist1 = [-10, 21, -4, -45, -66, 93]num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] >= 0: print(list1[num], end = \" \") # increment num num += 1 ",
"e": 1060,
"s": 765,
"text": null
},
{
"code": null,
"e": 1068,
"s": 1060,
"text": "Output:"
},
{
"code": null,
"e": 1075,
"s": 1068,
"text": "21 93 "
},
{
"code": null,
"e": 1113,
"s": 1075,
"text": " Example #3: Using list comprehension"
},
{
"code": "# Python program to print Positive Numbers in a List # list of numberslist1 = [-10, -21, -4, 45, -66, 93] # using list comprehensionpos_nos = [num for num in list1 if num >= 0] print(\"Positive numbers in the list: \", *pos_nos)",
"e": 1343,
"s": 1113,
"text": null
},
{
"code": null,
"e": 1351,
"s": 1343,
"text": "Output:"
},
{
"code": null,
"e": 1388,
"s": 1351,
"text": "Positive numbers in the list: 45 93"
},
{
"code": null,
"e": 1426,
"s": 1388,
"text": " Example #4: Using lambda expressions"
},
{
"code": "# Python program to print positive Numbers in a List # list of numbers list1 = [-10, 21, 4, -45, -66, 93, -11] # we can also print positive no's using lambda exp. pos_nos = list(filter(lambda x: (x >= 0), list1)) print(\"Positive numbers in the list: \", *pos_nos) ",
"e": 1696,
"s": 1426,
"text": null
},
{
"code": null,
"e": 1704,
"s": 1696,
"text": "Output:"
},
{
"code": null,
"e": 1745,
"s": 1704,
"text": "Positive numbers in the list: 21, 4, 93"
},
{
"code": null,
"e": 1766,
"s": 1745,
"text": "Python list-programs"
},
{
"code": null,
"e": 1778,
"s": 1766,
"text": "python-list"
},
{
"code": null,
"e": 1785,
"s": 1778,
"text": "Python"
},
{
"code": null,
"e": 1801,
"s": 1785,
"text": "Python Programs"
},
{
"code": null,
"e": 1820,
"s": 1801,
"text": "School Programming"
},
{
"code": null,
"e": 1832,
"s": 1820,
"text": "python-list"
},
{
"code": null,
"e": 1930,
"s": 1832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1972,
"s": 1930,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1994,
"s": 1972,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2020,
"s": 1994,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2052,
"s": 2020,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2081,
"s": 2052,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2103,
"s": 2081,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2142,
"s": 2103,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2180,
"s": 2142,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2229,
"s": 2180,
"text": "Python | Convert string dictionary to dictionary"
}
] |
What does start() function do in multithreading in Java?
|
29 Nov, 2021
We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don’t we directly call the overridden run() function? Why always the start function is called to execute a thread?What happens when a function is called? When a function is called the following operations take place:
The arguments are evaluated.A new stack frame is pushed into the call stack.Parameters are initialized.Method body is executed.Value is returned and current stack frame is popped from the call stack.
The arguments are evaluated.
A new stack frame is pushed into the call stack.
Parameters are initialized.
Method body is executed.
Value is returned and current stack frame is popped from the call stack.
The purpose of start() is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM.Let us see what happens if we don’t call start() and rather call run() directly. We have modified the first program discussed here.
Java
// Java code to see that all threads are// pushed on same stack if we use run()// instead of start().class ThreadTest extends Thread{ public void run() { try { // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception is caught"); } }} // Main Classpublic class Main{ public static void main(String[] args) { int n = 8; for (int i=0; i<n; i++) { ThreadTest object = new ThreadTest(); // start() is replaced with run() for // seeing the purpose of start object.run(); } }}
Output:
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
We can see from above output that we get same ids for all threads because we have directly called run(). The program that calls start() prints different ids (see this)References:
http://www.javatpoint.com/what-if-we-call-run()-method-directly
http://www.leepoint.net/JavaBasics/methods/methods-25-calls.html
This article is contributed by kp93. 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.
varshagumber28
surindertarika1234
Java-Multithreading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Nov, 2021"
},
{
"code": null,
"e": 531,
"s": 52,
"text": "We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don’t we directly call the overridden run() function? Why always the start function is called to execute a thread?What happens when a function is called? When a function is called the following operations take place: "
},
{
"code": null,
"e": 731,
"s": 531,
"text": "The arguments are evaluated.A new stack frame is pushed into the call stack.Parameters are initialized.Method body is executed.Value is returned and current stack frame is popped from the call stack."
},
{
"code": null,
"e": 760,
"s": 731,
"text": "The arguments are evaluated."
},
{
"code": null,
"e": 809,
"s": 760,
"text": "A new stack frame is pushed into the call stack."
},
{
"code": null,
"e": 837,
"s": 809,
"text": "Parameters are initialized."
},
{
"code": null,
"e": 862,
"s": 837,
"text": "Method body is executed."
},
{
"code": null,
"e": 935,
"s": 862,
"text": "Value is returned and current stack frame is popped from the call stack."
},
{
"code": null,
"e": 1215,
"s": 935,
"text": "The purpose of start() is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM.Let us see what happens if we don’t call start() and rather call run() directly. We have modified the first program discussed here. "
},
{
"code": null,
"e": 1220,
"s": 1215,
"text": "Java"
},
{
"code": "// Java code to see that all threads are// pushed on same stack if we use run()// instead of start().class ThreadTest extends Thread{ public void run() { try { // Displaying the thread that is running System.out.println (\"Thread \" + Thread.currentThread().getId() + \" is running\"); } catch (Exception e) { // Throwing an exception System.out.println (\"Exception is caught\"); } }} // Main Classpublic class Main{ public static void main(String[] args) { int n = 8; for (int i=0; i<n; i++) { ThreadTest object = new ThreadTest(); // start() is replaced with run() for // seeing the purpose of start object.run(); } }}",
"e": 1944,
"s": 1220,
"text": null
},
{
"code": null,
"e": 1954,
"s": 1944,
"text": "Output: "
},
{
"code": null,
"e": 2114,
"s": 1954,
"text": "Thread 1 is running\nThread 1 is running\nThread 1 is running\nThread 1 is running\nThread 1 is running\nThread 1 is running\nThread 1 is running\nThread 1 is running"
},
{
"code": null,
"e": 2295,
"s": 2114,
"text": "We can see from above output that we get same ids for all threads because we have directly called run(). The program that calls start() prints different ids (see this)References: "
},
{
"code": null,
"e": 2359,
"s": 2295,
"text": "http://www.javatpoint.com/what-if-we-call-run()-method-directly"
},
{
"code": null,
"e": 2424,
"s": 2359,
"text": "http://www.leepoint.net/JavaBasics/methods/methods-25-calls.html"
},
{
"code": null,
"e": 2837,
"s": 2424,
"text": "This article is contributed by kp93. 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": 2852,
"s": 2837,
"text": "varshagumber28"
},
{
"code": null,
"e": 2871,
"s": 2852,
"text": "surindertarika1234"
},
{
"code": null,
"e": 2891,
"s": 2871,
"text": "Java-Multithreading"
},
{
"code": null,
"e": 2896,
"s": 2891,
"text": "Java"
},
{
"code": null,
"e": 2901,
"s": 2896,
"text": "Java"
}
] |
Generating random number list in Python
|
05 Sep, 2021
Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers. This task is to perform in general using loop and appending the random numbers one by one. But there is always a requirement to perform this in most concise manner. Let’s discuss certain ways in which this can be done.
The naive method to perform this particular task can be shortened using the list comprehension. randrange function is used to perform the task of generating the random numbers.
Python3
# Python3 code to demonstrate# to generate random number list# using list comprehension + randrange()import random # using list comprehension + randrange()# to generate random number listres = [random.randrange(1, 50, 1) for i in range(7)] # printing resultprint ("Random number list is : " + str(res))
Random number list is : [30, 48, 14, 33, 1, 4, 18]
This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list.
Python3
# Python3 code to demonstrate# to generate random number list# using random.sample()import random # using random.sample()# to generate random number listres = random.sample(range(1, 50), 7) # printing resultprint ("Random number list is : " + str(res))
Random number list is : [21, 1, 14, 22, 6, 39, 7]
The random function provided by the numpy module can be more useful for you as it provides little better functionality and performance as compare to the random module.
This function returns random integers from the “discrete uniform” distribution of the integer data type.
Python3
# importing numpy moduleimport numpy as np # print the list of 10 integers from 3 to 7print(list(np.random.randint(low = 3,high=8,size=10))) # print the list of 5 integers from 0 to 2# if high parameter is not passed during# function call then results are from [0, low)print(list(np.random.randint(low = 3,size=5)))
Output:
[5, 3, 6, 7, 4, 5, 7, 7, 7, 7]
[0, 2, 1, 2, 1]
This function return random float values in half open interval [0.0, 1.0).
Python3
import numpy as np # generates list of 4 float valuesprint(np.random.random_sample(size = 4)) # generates 2d list of 4*4print(np.random.random_sample(size = (4,4)))
output:
[0.08035145 0.94966245 0.92860366 0.22102797]
[[0.02937499 0.50073572 0.58278742 0.02577903]
[0.37892104 0.60267882 0.33774815 0.28425059]
[0.57086088 0.07445422 0.86236614 0.33505317]
[0.83514508 0.82818536 0.1917555 0.76293027]]
The benefit of using numpy.random over the random module of python is that it provides few extra probability distributions which can help in scientific research.
By using random.randint() we can add random numbers into a list.
Python3
import random rand_list=[]n=10for i in range(n): rand_list.append(random.randint(3,9))print(rand_list)
[8, 8, 8, 9, 5, 6, 5, 3, 7, 9]
UnworthyProgrammer
pulamolusaimohan
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2021"
},
{
"code": null,
"e": 371,
"s": 28,
"text": "Sometimes, in making programs for gaming or gambling, we come across the task of creating the list all with random numbers. This task is to perform in general using loop and appending the random numbers one by one. But there is always a requirement to perform this in most concise manner. Let’s discuss certain ways in which this can be done."
},
{
"code": null,
"e": 550,
"s": 371,
"text": "The naive method to perform this particular task can be shortened using the list comprehension. randrange function is used to perform the task of generating the random numbers. "
},
{
"code": null,
"e": 558,
"s": 550,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to generate random number list# using list comprehension + randrange()import random # using list comprehension + randrange()# to generate random number listres = [random.randrange(1, 50, 1) for i in range(7)] # printing resultprint (\"Random number list is : \" + str(res))",
"e": 862,
"s": 558,
"text": null
},
{
"code": null,
"e": 914,
"s": 862,
"text": "Random number list is : [30, 48, 14, 33, 1, 4, 18]\n"
},
{
"code": null,
"e": 1108,
"s": 914,
"text": "This single utility function performs the exact required as asked by the problem statement, it generated N no. of random numbers in a list in the specified range and returns the required list. "
},
{
"code": null,
"e": 1116,
"s": 1108,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate# to generate random number list# using random.sample()import random # using random.sample()# to generate random number listres = random.sample(range(1, 50), 7) # printing resultprint (\"Random number list is : \" + str(res))",
"e": 1370,
"s": 1116,
"text": null
},
{
"code": null,
"e": 1421,
"s": 1370,
"text": "Random number list is : [21, 1, 14, 22, 6, 39, 7]\n"
},
{
"code": null,
"e": 1589,
"s": 1421,
"text": "The random function provided by the numpy module can be more useful for you as it provides little better functionality and performance as compare to the random module."
},
{
"code": null,
"e": 1694,
"s": 1589,
"text": "This function returns random integers from the “discrete uniform” distribution of the integer data type."
},
{
"code": null,
"e": 1702,
"s": 1694,
"text": "Python3"
},
{
"code": "# importing numpy moduleimport numpy as np # print the list of 10 integers from 3 to 7print(list(np.random.randint(low = 3,high=8,size=10))) # print the list of 5 integers from 0 to 2# if high parameter is not passed during# function call then results are from [0, low)print(list(np.random.randint(low = 3,size=5)))",
"e": 2019,
"s": 1702,
"text": null
},
{
"code": null,
"e": 2075,
"s": 2019,
"text": "Output: \n[5, 3, 6, 7, 4, 5, 7, 7, 7, 7]\n[0, 2, 1, 2, 1]"
},
{
"code": null,
"e": 2150,
"s": 2075,
"text": "This function return random float values in half open interval [0.0, 1.0)."
},
{
"code": null,
"e": 2158,
"s": 2150,
"text": "Python3"
},
{
"code": "import numpy as np # generates list of 4 float valuesprint(np.random.random_sample(size = 4)) # generates 2d list of 4*4print(np.random.random_sample(size = (4,4)))",
"e": 2323,
"s": 2158,
"text": null
},
{
"code": null,
"e": 2566,
"s": 2323,
"text": "output:\n[0.08035145 0.94966245 0.92860366 0.22102797]\n[[0.02937499 0.50073572 0.58278742 0.02577903]\n [0.37892104 0.60267882 0.33774815 0.28425059]\n [0.57086088 0.07445422 0.86236614 0.33505317]\n [0.83514508 0.82818536 0.1917555 0.76293027]]"
},
{
"code": null,
"e": 2728,
"s": 2566,
"text": "The benefit of using numpy.random over the random module of python is that it provides few extra probability distributions which can help in scientific research."
},
{
"code": null,
"e": 2793,
"s": 2728,
"text": "By using random.randint() we can add random numbers into a list."
},
{
"code": null,
"e": 2801,
"s": 2793,
"text": "Python3"
},
{
"code": "import random rand_list=[]n=10for i in range(n): rand_list.append(random.randint(3,9))print(rand_list)",
"e": 2907,
"s": 2801,
"text": null
},
{
"code": null,
"e": 2939,
"s": 2907,
"text": "[8, 8, 8, 9, 5, 6, 5, 3, 7, 9]\n"
},
{
"code": null,
"e": 2958,
"s": 2939,
"text": "UnworthyProgrammer"
},
{
"code": null,
"e": 2975,
"s": 2958,
"text": "pulamolusaimohan"
},
{
"code": null,
"e": 2996,
"s": 2975,
"text": "Python list-programs"
},
{
"code": null,
"e": 3003,
"s": 2996,
"text": "Python"
},
{
"code": null,
"e": 3019,
"s": 3003,
"text": "Python Programs"
},
{
"code": null,
"e": 3117,
"s": 3019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3135,
"s": 3117,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3177,
"s": 3135,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3199,
"s": 3177,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3234,
"s": 3199,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3266,
"s": 3234,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3309,
"s": 3266,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3331,
"s": 3309,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3370,
"s": 3331,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3408,
"s": 3370,
"text": "Python | Convert a list to dictionary"
}
] |
Interacting with Webpage – Selenium Python
|
10 Sep, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. First of all, we need to find one. WebDriver offers a number of ways to find elements. For example, given an element defined as:
html
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
One can also look for a link by its text, but be careful! The text must be an exact match! One should also be careful when using XPATH in WebDriver. If there’s more than one element that matches the query, then only the first will be returned. If nothing can be found, a NoSuchElementException will be raised. WebDriver has an “Object-based” API, we represent all types of elements using the same interface. This means that although one may see a lot of possible methods one could invoke when one hits IDE’s auto-complete key combination, not all of them will make sense or be valid. To check all methods, checkout Locator Strategies – Selenium Python So after getting an element what next? One might want to enter text into a field, for example,
element.send_keys("some text")
One can simulate pressing the arrow keys by using the “Keys” class:
element.send_keys(" and some", Keys.ARROW_DOWN)
Also note, it is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail. One can easily clear the contents of a text field or textarea with the clear method:
element.clear()
Project Example – Let’s try to search something automatically at geeksforgeeks Program –
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_id("gsc-i-id1") # send keyselement.send_keys("Arrays")
Output-
a7xfor3ver
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Sep, 2020"
},
{
"code": null,
"e": 644,
"s": 52,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. First of all, we need to find one. WebDriver offers a number of ways to find elements. For example, given an element defined as: "
},
{
"code": null,
"e": 649,
"s": 644,
"text": "html"
},
{
"code": "<input type=\"text\" name=\"passwd\" id=\"passwd-id\" />",
"e": 700,
"s": 649,
"text": null
},
{
"code": null,
"e": 782,
"s": 700,
"text": "To find an element one needs to use one of the locating strategies, For example, "
},
{
"code": null,
"e": 947,
"s": 782,
"text": "element = driver.find_element_by_id(\"passwd-id\")\nelement = driver.find_element_by_name(\"passwd\")\nelement = driver.find_element_by_xpath(\"//input[@id='passwd-id']\")\n"
},
{
"code": null,
"e": 995,
"s": 947,
"text": "Also, to find multiple elements, we can use – "
},
{
"code": null,
"e": 1046,
"s": 995,
"text": "elements = driver.find_elements_by_name(\"passwd\")\n"
},
{
"code": null,
"e": 1795,
"s": 1046,
"text": "One can also look for a link by its text, but be careful! The text must be an exact match! One should also be careful when using XPATH in WebDriver. If there’s more than one element that matches the query, then only the first will be returned. If nothing can be found, a NoSuchElementException will be raised. WebDriver has an “Object-based” API, we represent all types of elements using the same interface. This means that although one may see a lot of possible methods one could invoke when one hits IDE’s auto-complete key combination, not all of them will make sense or be valid. To check all methods, checkout Locator Strategies – Selenium Python So after getting an element what next? One might want to enter text into a field, for example, "
},
{
"code": null,
"e": 1827,
"s": 1795,
"text": "element.send_keys(\"some text\")\n"
},
{
"code": null,
"e": 1897,
"s": 1827,
"text": "One can simulate pressing the arrow keys by using the “Keys” class: "
},
{
"code": null,
"e": 1946,
"s": 1897,
"text": "element.send_keys(\" and some\", Keys.ARROW_DOWN)\n"
},
{
"code": null,
"e": 2172,
"s": 1946,
"text": "Also note, it is possible to call send_keys on any element, which makes it possible to test keyboard shortcuts such as those used on Gmail. One can easily clear the contents of a text field or textarea with the clear method: "
},
{
"code": null,
"e": 2189,
"s": 2172,
"text": "element.clear()\n"
},
{
"code": null,
"e": 2280,
"s": 2189,
"text": "Project Example – Let’s try to search something automatically at geeksforgeeks Program – "
},
{
"code": null,
"e": 2288,
"s": 2280,
"text": "Python3"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_id(\"gsc-i-id1\") # send keyselement.send_keys(\"Arrays\")",
"e": 2561,
"s": 2288,
"text": null
},
{
"code": null,
"e": 2571,
"s": 2561,
"text": "Output- "
},
{
"code": null,
"e": 2584,
"s": 2573,
"text": "a7xfor3ver"
},
{
"code": null,
"e": 2600,
"s": 2584,
"text": "Python-selenium"
},
{
"code": null,
"e": 2609,
"s": 2600,
"text": "selenium"
},
{
"code": null,
"e": 2616,
"s": 2609,
"text": "Python"
},
{
"code": null,
"e": 2714,
"s": 2616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2742,
"s": 2714,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2764,
"s": 2742,
"text": "Python map() function"
},
{
"code": null,
"e": 2814,
"s": 2764,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2858,
"s": 2814,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2900,
"s": 2858,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2922,
"s": 2900,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2957,
"s": 2922,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2983,
"s": 2957,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3015,
"s": 2983,
"text": "How to Install PIP on Windows ?"
}
] |
Privacy Enhanced Mail (PEM) and it’s Working
|
08 Jul, 2022
Privacy Enhanced Mail (PEM) is an email security standard to provide secure electronic mail communication over the internet. Security of email messages has become extremely important nowadays. In order to deal with the security issues of emails the internet architecture board has adopted it.
The PEM mainly provides the following services –
Confidentiality –Confidentiality refers to the act of preventing unauthorized access to the information hence protecting it. The confidentiality is obtained in PEM by encrypting the messages by using various standard algorithms such as Data Encryption Standard (DES). DES in cipher block chaining mode is being currently used by PEM.Integrity –Data integrity refers to the consistency of data through out its life cycle. This is obtained by using a unique concept called as message digest where message digest is a hash function which converts the message into an image called digest on taking the message as input. PEM uses RSA encryption, MD2 and MD5 hash functions to generate the digests. An octet value is generated from the hash functions which is then encrypted which is then run against the message digest by the receiver assured of the integrity of the message that is transmitted.
Confidentiality –Confidentiality refers to the act of preventing unauthorized access to the information hence protecting it. The confidentiality is obtained in PEM by encrypting the messages by using various standard algorithms such as Data Encryption Standard (DES). DES in cipher block chaining mode is being currently used by PEM.
Integrity –Data integrity refers to the consistency of data through out its life cycle. This is obtained by using a unique concept called as message digest where message digest is a hash function which converts the message into an image called digest on taking the message as input. PEM uses RSA encryption, MD2 and MD5 hash functions to generate the digests. An octet value is generated from the hash functions which is then encrypted which is then run against the message digest by the receiver assured of the integrity of the message that is transmitted.
Working of PEM :The PEM works basically in 4 main steps.
Canonical Conversion –This step involves the conversion of the message into a standard format that is independent of the computer architecture and the operating system of the sender and the receiver. If the sender and receiver has different computer architecture or operating system. It may lead to generation of different message digest due to difference in their interpretation because of syntactical difference from one operating system to an other.Digital Signature –In this step, the digital signature is generated by encrypting the message digest of an email message with the sender’s private key.Encryption –The encrypted message is generated by encrypting the original message and digital signature together along with the symmetric key as shown in the figure below.This step is very crucial in order to obtain the confidentiality.Base-64 Encoding –This is the last step where the binary output is transformed into character output. The binary output which is 24 bits is divided into 4 equal sets and mapped with the 8 bit character output generating a decimal code. Now PEM uses a separate map table and each number from the code generated is mapped with its corresponding value from the mapping table and binary equivalent corresponding to the 8 bit ASCII of the character is written.
Canonical Conversion –This step involves the conversion of the message into a standard format that is independent of the computer architecture and the operating system of the sender and the receiver. If the sender and receiver has different computer architecture or operating system. It may lead to generation of different message digest due to difference in their interpretation because of syntactical difference from one operating system to an other.
Digital Signature –In this step, the digital signature is generated by encrypting the message digest of an email message with the sender’s private key.
Encryption –The encrypted message is generated by encrypting the original message and digital signature together along with the symmetric key as shown in the figure below.This step is very crucial in order to obtain the confidentiality.
Base-64 Encoding –This is the last step where the binary output is transformed into character output. The binary output which is 24 bits is divided into 4 equal sets and mapped with the 8 bit character output generating a decimal code. Now PEM uses a separate map table and each number from the code generated is mapped with its corresponding value from the mapping table and binary equivalent corresponding to the 8 bit ASCII of the character is written.
pall58183
cryptography
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Secure Socket Layer (SSL)
GSM in Wireless Communication
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
Cryptography and its Types
Bluetooth
Intrusion Detection System (IDS)
Dynamic Host Configuration Protocol (DHCP)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 321,
"s": 28,
"text": "Privacy Enhanced Mail (PEM) is an email security standard to provide secure electronic mail communication over the internet. Security of email messages has become extremely important nowadays. In order to deal with the security issues of emails the internet architecture board has adopted it."
},
{
"code": null,
"e": 370,
"s": 321,
"text": "The PEM mainly provides the following services –"
},
{
"code": null,
"e": 1261,
"s": 370,
"text": "Confidentiality –Confidentiality refers to the act of preventing unauthorized access to the information hence protecting it. The confidentiality is obtained in PEM by encrypting the messages by using various standard algorithms such as Data Encryption Standard (DES). DES in cipher block chaining mode is being currently used by PEM.Integrity –Data integrity refers to the consistency of data through out its life cycle. This is obtained by using a unique concept called as message digest where message digest is a hash function which converts the message into an image called digest on taking the message as input. PEM uses RSA encryption, MD2 and MD5 hash functions to generate the digests. An octet value is generated from the hash functions which is then encrypted which is then run against the message digest by the receiver assured of the integrity of the message that is transmitted."
},
{
"code": null,
"e": 1595,
"s": 1261,
"text": "Confidentiality –Confidentiality refers to the act of preventing unauthorized access to the information hence protecting it. The confidentiality is obtained in PEM by encrypting the messages by using various standard algorithms such as Data Encryption Standard (DES). DES in cipher block chaining mode is being currently used by PEM."
},
{
"code": null,
"e": 2153,
"s": 1595,
"text": "Integrity –Data integrity refers to the consistency of data through out its life cycle. This is obtained by using a unique concept called as message digest where message digest is a hash function which converts the message into an image called digest on taking the message as input. PEM uses RSA encryption, MD2 and MD5 hash functions to generate the digests. An octet value is generated from the hash functions which is then encrypted which is then run against the message digest by the receiver assured of the integrity of the message that is transmitted."
},
{
"code": null,
"e": 2210,
"s": 2153,
"text": "Working of PEM :The PEM works basically in 4 main steps."
},
{
"code": null,
"e": 3505,
"s": 2210,
"text": "Canonical Conversion –This step involves the conversion of the message into a standard format that is independent of the computer architecture and the operating system of the sender and the receiver. If the sender and receiver has different computer architecture or operating system. It may lead to generation of different message digest due to difference in their interpretation because of syntactical difference from one operating system to an other.Digital Signature –In this step, the digital signature is generated by encrypting the message digest of an email message with the sender’s private key.Encryption –The encrypted message is generated by encrypting the original message and digital signature together along with the symmetric key as shown in the figure below.This step is very crucial in order to obtain the confidentiality.Base-64 Encoding –This is the last step where the binary output is transformed into character output. The binary output which is 24 bits is divided into 4 equal sets and mapped with the 8 bit character output generating a decimal code. Now PEM uses a separate map table and each number from the code generated is mapped with its corresponding value from the mapping table and binary equivalent corresponding to the 8 bit ASCII of the character is written."
},
{
"code": null,
"e": 3958,
"s": 3505,
"text": "Canonical Conversion –This step involves the conversion of the message into a standard format that is independent of the computer architecture and the operating system of the sender and the receiver. If the sender and receiver has different computer architecture or operating system. It may lead to generation of different message digest due to difference in their interpretation because of syntactical difference from one operating system to an other."
},
{
"code": null,
"e": 4110,
"s": 3958,
"text": "Digital Signature –In this step, the digital signature is generated by encrypting the message digest of an email message with the sender’s private key."
},
{
"code": null,
"e": 4347,
"s": 4110,
"text": "Encryption –The encrypted message is generated by encrypting the original message and digital signature together along with the symmetric key as shown in the figure below.This step is very crucial in order to obtain the confidentiality."
},
{
"code": null,
"e": 4803,
"s": 4347,
"text": "Base-64 Encoding –This is the last step where the binary output is transformed into character output. The binary output which is 24 bits is divided into 4 equal sets and mapped with the 8 bit character output generating a decimal code. Now PEM uses a separate map table and each number from the code generated is mapped with its corresponding value from the mapping table and binary equivalent corresponding to the 8 bit ASCII of the character is written."
},
{
"code": null,
"e": 4813,
"s": 4803,
"text": "pall58183"
},
{
"code": null,
"e": 4826,
"s": 4813,
"text": "cryptography"
},
{
"code": null,
"e": 4844,
"s": 4826,
"text": "Computer Networks"
},
{
"code": null,
"e": 4857,
"s": 4844,
"text": "cryptography"
},
{
"code": null,
"e": 4875,
"s": 4857,
"text": "Computer Networks"
},
{
"code": null,
"e": 4973,
"s": 4875,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4999,
"s": 4973,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 5029,
"s": 4999,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 5059,
"s": 5029,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 5099,
"s": 5059,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 5145,
"s": 5099,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 5180,
"s": 5145,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 5207,
"s": 5180,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 5217,
"s": 5207,
"text": "Bluetooth"
},
{
"code": null,
"e": 5250,
"s": 5217,
"text": "Intrusion Detection System (IDS)"
}
] |
Scala | Case Class and Case Object
|
28 Feb, 2019
A Case Class is just like a regular class, which has a feature for modeling unchangeable data. It is also constructive in pattern matching. It has been defined with a modifier case, due to this case keyword, we can get some benefits to stop oneself from doing a sections of codes that have to be included in many places with little or no alteration. As we can see below a minimal case class needs the keyword case class, an identifier, and a parameter list which may be vacant.Syntax:
Case class className(parameters)
Note: The Case class has a default apply() method which manages the construction of object.
A Case Object is also like an object, which has more attributes than a regular Object. It is a blend of both case classes and object. A case object has some more features than a regular object.Below two are important features of case object:
It is serializable.
It has a by default hashCode implementation.
Example :
// Scala program of case class and case Objectcase class employee (name:String, age:Int)object Main { // Main method def main(args: Array[String]) { var c = employee("Nidhi", 23) // Display both Parameter println("Name of the employee is " + c.name); println("Age of the employee is " + c.age); } }
Name of the employee is Nidhi
Age of the employee is 23
The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.Example:// Scala program of case class and case Object// affix a method with the name of the classcase class Book (name:String, author:String)object Main{ // Main method def main(args: Array[String]) { var Book1 = Book("Data Structure and Algorithm", "cormen") var Book2 = Book("Computer Networking", "Tanenbaum") // Display strings println("Name of the Book1 is " + Book1.name); println("Author of the Book1 is " + Book1.author); println("Name of the Book2 is " + Book2.name); println("Author of the Book2 is " + Book2.author); }} Output:Name of the Book1 is Data Structure and Algorithm
Author of the Book1 is cormen
Name of the Book2 is Computer Networking
Author of the Book2 is Tanenbaum
// Scala program of case class and case Object// affix a method with the name of the classcase class Book (name:String, author:String)object Main{ // Main method def main(args: Array[String]) { var Book1 = Book("Data Structure and Algorithm", "cormen") var Book2 = Book("Computer Networking", "Tanenbaum") // Display strings println("Name of the Book1 is " + Book1.name); println("Author of the Book1 is " + Book1.author); println("Name of the Book2 is " + Book2.name); println("Author of the Book2 is " + Book2.author); }}
Name of the Book1 is Data Structure and Algorithm
Author of the Book1 is cormen
Name of the Book2 is Computer Networking
Author of the Book2 is Tanenbaum
The second convenience is that by default Scala compiler affixes val or var for all the parameters of constructor so, we won’t be able to reassign a new value to them once that class object is constructed that’s why even in absence of val or var, case class’s constructor parameters will turn out to be class members, that is not practicable for regular classes.Example:Thus, reassignment is not feasible.
The Scala compiler also appends a copy() method to case class that is utilized to create a duplicate of the same object with changing some parameters or without altering them.Example : To create a duplicate of same instance without altering the parameters.// Scala program of case class To create // a duplicate of same instancecase class Student (name:String, age:Int)object Main{ // Main method def main(args: Array[String]) { val s1 = Student("Nidhi", 23) // Display parameter println("Name is " + s1.name); println("Age is " + s1.age); val s2 = s1.copy() // Display copied data println("Copy Name " + s2.name); println("Copy Age " + s2.age); }} Output:Name is Nidhi
Age is 23
Copy Name Nidhi
Copy Age 23
Here, we have created new object s2 by using copy method on s1 object without altering s1 object attributes.Example : To create a duplicate of same object with changing attributes.// Scala program of case class same object // with changing attributescase class Student (name:String, age:Int) object Main{ // Main method def main(args: Array[String]) { val s1 = Student("Nidhi", 23) // Display parameter println("Name is " + s1.name); println("Age is " + s1.age); val s2 = s1.copy(age = 24) // Display copied and changed attributes println("Copy Name is " + s2.name); println("Change Age is " + s2.age); }} Output:Name is Nidhi
Age is 23
Copy Name is Nidhi
Change Age is 24
Here, you need to pass the value in the copy method.
// Scala program of case class To create // a duplicate of same instancecase class Student (name:String, age:Int)object Main{ // Main method def main(args: Array[String]) { val s1 = Student("Nidhi", 23) // Display parameter println("Name is " + s1.name); println("Age is " + s1.age); val s2 = s1.copy() // Display copied data println("Copy Name " + s2.name); println("Copy Age " + s2.age); }}
Name is Nidhi
Age is 23
Copy Name Nidhi
Copy Age 23
Here, we have created new object s2 by using copy method on s1 object without altering s1 object attributes.Example : To create a duplicate of same object with changing attributes.
// Scala program of case class same object // with changing attributescase class Student (name:String, age:Int) object Main{ // Main method def main(args: Array[String]) { val s1 = Student("Nidhi", 23) // Display parameter println("Name is " + s1.name); println("Age is " + s1.age); val s2 = s1.copy(age = 24) // Display copied and changed attributes println("Copy Name is " + s2.name); println("Change Age is " + s2.age); }}
Name is Nidhi
Age is 23
Copy Name is Nidhi
Change Age is 24
Here, you need to pass the value in the copy method.
By default Scala Compiler adds toString, equals methods, companion object with apply and unapply methods, for that reason you don’t need new keyword to construct object of a Case class.
Note:It was not practicable to use more than 22 parameters in scala case classes but now you can use any number of parameters in case classes using Scala Version 2.11.1. This limitation was eliminated from this version of scala.
Picked
Scala
Scala-OOPS
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Map
Scala Lists
Scala | Arrays
Lambda Expression in Scala
How to Install Scala with VSCode?
Enumeration in Scala
How to get the first element of List in Scala
Scala String replace() method with example
HashMap in Scala
Scala List contains() method with example
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2019"
},
{
"code": null,
"e": 513,
"s": 28,
"text": "A Case Class is just like a regular class, which has a feature for modeling unchangeable data. It is also constructive in pattern matching. It has been defined with a modifier case, due to this case keyword, we can get some benefits to stop oneself from doing a sections of codes that have to be included in many places with little or no alteration. As we can see below a minimal case class needs the keyword case class, an identifier, and a parameter list which may be vacant.Syntax:"
},
{
"code": null,
"e": 546,
"s": 513,
"text": "Case class className(parameters)"
},
{
"code": null,
"e": 638,
"s": 546,
"text": "Note: The Case class has a default apply() method which manages the construction of object."
},
{
"code": null,
"e": 880,
"s": 638,
"text": "A Case Object is also like an object, which has more attributes than a regular Object. It is a blend of both case classes and object. A case object has some more features than a regular object.Below two are important features of case object:"
},
{
"code": null,
"e": 900,
"s": 880,
"text": "It is serializable."
},
{
"code": null,
"e": 945,
"s": 900,
"text": "It has a by default hashCode implementation."
},
{
"code": null,
"e": 955,
"s": 945,
"text": "Example :"
},
{
"code": "// Scala program of case class and case Objectcase class employee (name:String, age:Int)object Main { // Main method def main(args: Array[String]) { var c = employee(\"Nidhi\", 23) // Display both Parameter println(\"Name of the employee is \" + c.name); println(\"Age of the employee is \" + c.age); } } ",
"e": 1311,
"s": 955,
"text": null
},
{
"code": null,
"e": 1368,
"s": 1311,
"text": "Name of the employee is Nidhi\nAge of the employee is 23\n"
},
{
"code": null,
"e": 2413,
"s": 1368,
"text": "The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.Example:// Scala program of case class and case Object// affix a method with the name of the classcase class Book (name:String, author:String)object Main{ // Main method def main(args: Array[String]) { var Book1 = Book(\"Data Structure and Algorithm\", \"cormen\") var Book2 = Book(\"Computer Networking\", \"Tanenbaum\") // Display strings println(\"Name of the Book1 is \" + Book1.name); println(\"Author of the Book1 is \" + Book1.author); println(\"Name of the Book2 is \" + Book2.name); println(\"Author of the Book2 is \" + Book2.author); }} Output:Name of the Book1 is Data Structure and Algorithm\nAuthor of the Book1 is cormen\nName of the Book2 is Computer Networking\nAuthor of the Book2 is Tanenbaum\n"
},
{
"code": "// Scala program of case class and case Object// affix a method with the name of the classcase class Book (name:String, author:String)object Main{ // Main method def main(args: Array[String]) { var Book1 = Book(\"Data Structure and Algorithm\", \"cormen\") var Book2 = Book(\"Computer Networking\", \"Tanenbaum\") // Display strings println(\"Name of the Book1 is \" + Book1.name); println(\"Author of the Book1 is \" + Book1.author); println(\"Name of the Book2 is \" + Book2.name); println(\"Author of the Book2 is \" + Book2.author); }} ",
"e": 3009,
"s": 2413,
"text": null
},
{
"code": null,
"e": 3164,
"s": 3009,
"text": "Name of the Book1 is Data Structure and Algorithm\nAuthor of the Book1 is cormen\nName of the Book2 is Computer Networking\nAuthor of the Book2 is Tanenbaum\n"
},
{
"code": null,
"e": 3570,
"s": 3164,
"text": "The second convenience is that by default Scala compiler affixes val or var for all the parameters of constructor so, we won’t be able to reassign a new value to them once that class object is constructed that’s why even in absence of val or var, case class’s constructor parameters will turn out to be class members, that is not practicable for regular classes.Example:Thus, reassignment is not feasible."
},
{
"code": null,
"e": 5181,
"s": 3570,
"text": "The Scala compiler also appends a copy() method to case class that is utilized to create a duplicate of the same object with changing some parameters or without altering them.Example : To create a duplicate of same instance without altering the parameters.// Scala program of case class To create // a duplicate of same instancecase class Student (name:String, age:Int)object Main{ // Main method def main(args: Array[String]) { val s1 = Student(\"Nidhi\", 23) // Display parameter println(\"Name is \" + s1.name); println(\"Age is \" + s1.age); val s2 = s1.copy() // Display copied data println(\"Copy Name \" + s2.name); println(\"Copy Age \" + s2.age); }} Output:Name is Nidhi\nAge is 23\nCopy Name Nidhi\nCopy Age 23\nHere, we have created new object s2 by using copy method on s1 object without altering s1 object attributes.Example : To create a duplicate of same object with changing attributes.// Scala program of case class same object // with changing attributescase class Student (name:String, age:Int) object Main{ // Main method def main(args: Array[String]) { val s1 = Student(\"Nidhi\", 23) // Display parameter println(\"Name is \" + s1.name); println(\"Age is \" + s1.age); val s2 = s1.copy(age = 24) // Display copied and changed attributes println(\"Copy Name is \" + s2.name); println(\"Change Age is \" + s2.age); }} Output:Name is Nidhi\nAge is 23\nCopy Name is Nidhi\nChange Age is 24\nHere, you need to pass the value in the copy method."
},
{
"code": "// Scala program of case class To create // a duplicate of same instancecase class Student (name:String, age:Int)object Main{ // Main method def main(args: Array[String]) { val s1 = Student(\"Nidhi\", 23) // Display parameter println(\"Name is \" + s1.name); println(\"Age is \" + s1.age); val s2 = s1.copy() // Display copied data println(\"Copy Name \" + s2.name); println(\"Copy Age \" + s2.age); }} ",
"e": 5663,
"s": 5181,
"text": null
},
{
"code": null,
"e": 5716,
"s": 5663,
"text": "Name is Nidhi\nAge is 23\nCopy Name Nidhi\nCopy Age 23\n"
},
{
"code": null,
"e": 5897,
"s": 5716,
"text": "Here, we have created new object s2 by using copy method on s1 object without altering s1 object attributes.Example : To create a duplicate of same object with changing attributes."
},
{
"code": "// Scala program of case class same object // with changing attributescase class Student (name:String, age:Int) object Main{ // Main method def main(args: Array[String]) { val s1 = Student(\"Nidhi\", 23) // Display parameter println(\"Name is \" + s1.name); println(\"Age is \" + s1.age); val s2 = s1.copy(age = 24) // Display copied and changed attributes println(\"Copy Name is \" + s2.name); println(\"Change Age is \" + s2.age); }} ",
"e": 6413,
"s": 5897,
"text": null
},
{
"code": null,
"e": 6474,
"s": 6413,
"text": "Name is Nidhi\nAge is 23\nCopy Name is Nidhi\nChange Age is 24\n"
},
{
"code": null,
"e": 6527,
"s": 6474,
"text": "Here, you need to pass the value in the copy method."
},
{
"code": null,
"e": 6713,
"s": 6527,
"text": "By default Scala Compiler adds toString, equals methods, companion object with apply and unapply methods, for that reason you don’t need new keyword to construct object of a Case class."
},
{
"code": null,
"e": 6942,
"s": 6713,
"text": "Note:It was not practicable to use more than 22 parameters in scala case classes but now you can use any number of parameters in case classes using Scala Version 2.11.1. This limitation was eliminated from this version of scala."
},
{
"code": null,
"e": 6949,
"s": 6942,
"text": "Picked"
},
{
"code": null,
"e": 6955,
"s": 6949,
"text": "Scala"
},
{
"code": null,
"e": 6966,
"s": 6955,
"text": "Scala-OOPS"
},
{
"code": null,
"e": 6972,
"s": 6966,
"text": "Scala"
},
{
"code": null,
"e": 7070,
"s": 6972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7080,
"s": 7070,
"text": "Scala Map"
},
{
"code": null,
"e": 7092,
"s": 7080,
"text": "Scala Lists"
},
{
"code": null,
"e": 7107,
"s": 7092,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 7134,
"s": 7107,
"text": "Lambda Expression in Scala"
},
{
"code": null,
"e": 7168,
"s": 7134,
"text": "How to Install Scala with VSCode?"
},
{
"code": null,
"e": 7189,
"s": 7168,
"text": "Enumeration in Scala"
},
{
"code": null,
"e": 7235,
"s": 7189,
"text": "How to get the first element of List in Scala"
},
{
"code": null,
"e": 7278,
"s": 7235,
"text": "Scala String replace() method with example"
},
{
"code": null,
"e": 7295,
"s": 7278,
"text": "HashMap in Scala"
}
] |
Named Return Parameters in Golang
|
25 Jan, 2022
Prerequisite: Functions in GolangIn Golang, Named Return Parameters are generally termed as the named parameters. Golang allows giving the names to the return or result parameters of the functions in the function signature or definition. Or you can say it is the explicit naming of the return variables in the function definition. Basically, it eliminates the requirement of mentioning the variables name with the return statement. By using named return parameters or named parameters one can only use return keyword at the end of the function to return the result to the caller. This concept is generally used when a function has to return multiple values. So for the user comfort and to enhance the code readability, Golang provide this facility.
To declare the named result or return parameters, just use the return type part of the function signature. Below is the general syntax to declare a function in Golang.Syntax to declare a function without named return arguments:
func function_name(Parameter-list)(Return_type){
// function body.....
}
Here, the Return_Type is optional and it contains the types of values that function returns. If you are using Return_Type in your function, then it is necessary to use a return statement in your function.Syntax to declare a function with named return arguments:
func function_name(Parameter-list)(result_parameter1 data-_type, result_parameter2 data_type, ....){ // function body.....return }
Here, (result_parameter1 data-_type, result_parameter2 data_type, ....) is the named return argument list along with their type. You can declare n number of named return parameters.
Example: In the below program, the func calculator(a, b int) (mul int, div int) line of code contains the named return arguments. The return statement at the end of function doesn’t contain any parameters. Go compiler will automatically returns the parameters.
C
// Golang program to demonstrate the// use of Named Return Arguments package main import "fmt" // Main Methodfunc main() { // calling the function, here // function returns two values m, d := calculator(105, 7) fmt.Println("105 x 7 = ", m) fmt.Println("105 / 7 = ", d)} // function having named argumentsfunc calculator(a, b int) (mul int, div int) { // here, simple assignment will // initialize the values to it mul = a * b div = a / b // here you have return keyword // without any resultant parameters return}
Output:
105 x 7 = 735
105 / 7 = 15
If the type of all the named return arguments is common or same then you can specify the common data type. Compare the below code with the example that you read above to get a better understandability.
// function having named arguments
func calculator(a, b int) (mul, div int) {
Here, mul and div variables are both int type. So you can also declare named arguments with common data type like the function variables(i.e. a and b)
Using Named return parameters will enhance the code readability as one can know about the return parameters by just reading the function signature.
After using named return parameters the return statement is generally termed as Naked or Bare return.
By default, Golang defines all the named variables with the zero value and function will able to use them. In case function doesn’t modify the values then automatically zero value will return.
If you will use short declaration operator(:=) to initialize the named return parameters, it will give an error as they are already initialized by the Go compiler. So you can use simple assignment(=) to assign the values to named return parameters.
// function having named arguments
func calculator(a, b int) (mul int, div int) {
// here, it will give an error
// as parameters are already defined
// in function signature
mul := a * b
div := a / b
// here you have return keyword
// without any resultant parameters
return
}
Named return arguments or bare return statements are only good for the short function signature. For longer functions, explicitly return the result parameters(not use named return parameters) to maintain the readability of the code.
In the case of named return arguments, bare or naked return statement is a must.
Akanksha_Rai
saurabh1990aror
Golang
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n25 Jan, 2022"
},
{
"code": null,
"e": 805,
"s": 54,
"text": "Prerequisite: Functions in GolangIn Golang, Named Return Parameters are generally termed as the named parameters. Golang allows giving the names to the return or result parameters of the functions in the function signature or definition. Or you can say it is the explicit naming of the return variables in the function definition. Basically, it eliminates the requirement of mentioning the variables name with the return statement. By using named return parameters or named parameters one can only use return keyword at the end of the function to return the result to the caller. This concept is generally used when a function has to return multiple values. So for the user comfort and to enhance the code readability, Golang provide this facility. "
},
{
"code": null,
"e": 1034,
"s": 805,
"text": "To declare the named result or return parameters, just use the return type part of the function signature. Below is the general syntax to declare a function in Golang.Syntax to declare a function without named return arguments: "
},
{
"code": null,
"e": 1111,
"s": 1034,
"text": "func function_name(Parameter-list)(Return_type){\n // function body.....\n}"
},
{
"code": null,
"e": 1374,
"s": 1111,
"text": "Here, the Return_Type is optional and it contains the types of values that function returns. If you are using Return_Type in your function, then it is necessary to use a return statement in your function.Syntax to declare a function with named return arguments: "
},
{
"code": null,
"e": 1507,
"s": 1374,
"text": "func function_name(Parameter-list)(result_parameter1 data-_type, result_parameter2 data_type, ....){ // function body.....return } "
},
{
"code": null,
"e": 1690,
"s": 1507,
"text": "Here, (result_parameter1 data-_type, result_parameter2 data_type, ....) is the named return argument list along with their type. You can declare n number of named return parameters. "
},
{
"code": null,
"e": 1952,
"s": 1690,
"text": "Example: In the below program, the func calculator(a, b int) (mul int, div int) line of code contains the named return arguments. The return statement at the end of function doesn’t contain any parameters. Go compiler will automatically returns the parameters. "
},
{
"code": null,
"e": 1954,
"s": 1952,
"text": "C"
},
{
"code": "// Golang program to demonstrate the// use of Named Return Arguments package main import \"fmt\" // Main Methodfunc main() { // calling the function, here // function returns two values m, d := calculator(105, 7) fmt.Println(\"105 x 7 = \", m) fmt.Println(\"105 / 7 = \", d)} // function having named argumentsfunc calculator(a, b int) (mul int, div int) { // here, simple assignment will // initialize the values to it mul = a * b div = a / b // here you have return keyword // without any resultant parameters return}",
"e": 2508,
"s": 1954,
"text": null
},
{
"code": null,
"e": 2517,
"s": 2508,
"text": "Output: "
},
{
"code": null,
"e": 2546,
"s": 2517,
"text": "105 x 7 = 735\n105 / 7 = 15"
},
{
"code": null,
"e": 2753,
"s": 2550,
"text": "If the type of all the named return arguments is common or same then you can specify the common data type. Compare the below code with the example that you read above to get a better understandability. "
},
{
"code": null,
"e": 2831,
"s": 2753,
"text": "// function having named arguments\nfunc calculator(a, b int) (mul, div int) {"
},
{
"code": null,
"e": 2982,
"s": 2831,
"text": "Here, mul and div variables are both int type. So you can also declare named arguments with common data type like the function variables(i.e. a and b)"
},
{
"code": null,
"e": 3130,
"s": 2982,
"text": "Using Named return parameters will enhance the code readability as one can know about the return parameters by just reading the function signature."
},
{
"code": null,
"e": 3232,
"s": 3130,
"text": "After using named return parameters the return statement is generally termed as Naked or Bare return."
},
{
"code": null,
"e": 3425,
"s": 3232,
"text": "By default, Golang defines all the named variables with the zero value and function will able to use them. In case function doesn’t modify the values then automatically zero value will return."
},
{
"code": null,
"e": 3675,
"s": 3425,
"text": "If you will use short declaration operator(:=) to initialize the named return parameters, it will give an error as they are already initialized by the Go compiler. So you can use simple assignment(=) to assign the values to named return parameters. "
},
{
"code": null,
"e": 3995,
"s": 3675,
"text": "// function having named arguments\nfunc calculator(a, b int) (mul int, div int) {\n\n // here, it will give an error\n // as parameters are already defined\n // in function signature\n mul := a * b\n div := a / b\n\n // here you have return keyword\n // without any resultant parameters\n return\n}"
},
{
"code": null,
"e": 4228,
"s": 3995,
"text": "Named return arguments or bare return statements are only good for the short function signature. For longer functions, explicitly return the result parameters(not use named return parameters) to maintain the readability of the code."
},
{
"code": null,
"e": 4309,
"s": 4228,
"text": "In the case of named return arguments, bare or naked return statement is a must."
},
{
"code": null,
"e": 4324,
"s": 4311,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4340,
"s": 4324,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4347,
"s": 4340,
"text": "Golang"
},
{
"code": null,
"e": 4359,
"s": 4347,
"text": "Go Language"
}
] |
numpy.subtract() in Python
|
10 Feb, 2019
numpy.subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise.
Syntax : numpy.subtract(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘subtract’)
Parameters :arr1 : [array_like or scalar]1st Input array.arr2 : [array_like or scalar]2nd Input array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray or scalar] The difference of arr1 and arr2, element-wise. Returns a scalar if both arr1 and arr2 are scalars.
Code #1 :
# Python program explaining# numpy.subtract() function import numpy as geekin_num1 = 4in_num2 = 6 print ("1st Input number : ", in_num1)print ("2nd Input number : ", in_num2) out_num = geek.subtract(in_num1, in_num2) print ("Difference of two input number : ", out_num)
1st Input number : 4
2nd Input number : 6
Difference of two input number : -2
Code #2 :
# Python program explaining# numpy.subtract() function import numpy as geek in_arr1 = geek.array([[2, -4, 5], [-6, 2, 0]])in_arr2 = geek.array([[0, -7, 5], [5, -2, 9]]) print ("1st Input array : ", in_arr1)print ("2nd Input array : ", in_arr2) out_arr = geek.subtract(in_arr1, in_arr2) print ("Output array: ", out_arr)
1st Input array : [[ 2 -4 5]
[-6 2 0]]
2nd Input array : [[ 0 -7 5]
[ 5 -2 9]]
Output array: [[ 2 3 0]
[-11 4 -9]]
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Feb, 2019"
},
{
"code": null,
"e": 197,
"s": 53,
"text": "numpy.subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise."
},
{
"code": null,
"e": 356,
"s": 197,
"text": "Syntax : numpy.subtract(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘subtract’)"
},
{
"code": null,
"e": 1035,
"s": 356,
"text": "Parameters :arr1 : [array_like or scalar]1st Input array.arr2 : [array_like or scalar]2nd Input array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored. -> If provided, it must have a shape that the inputs broadcast to. -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function."
},
{
"code": null,
"e": 1163,
"s": 1035,
"text": "Return : [ndarray or scalar] The difference of arr1 and arr2, element-wise. Returns a scalar if both arr1 and arr2 are scalars."
},
{
"code": null,
"e": 1173,
"s": 1163,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.subtract() function import numpy as geekin_num1 = 4in_num2 = 6 print (\"1st Input number : \", in_num1)print (\"2nd Input number : \", in_num2) out_num = geek.subtract(in_num1, in_num2) print (\"Difference of two input number : \", out_num) ",
"e": 1451,
"s": 1173,
"text": null
},
{
"code": null,
"e": 1533,
"s": 1451,
"text": "1st Input number : 4\n2nd Input number : 6\nDifference of two input number : -2\n"
},
{
"code": null,
"e": 1545,
"s": 1535,
"text": "Code #2 :"
},
{
"code": "# Python program explaining# numpy.subtract() function import numpy as geek in_arr1 = geek.array([[2, -4, 5], [-6, 2, 0]])in_arr2 = geek.array([[0, -7, 5], [5, -2, 9]]) print (\"1st Input array : \", in_arr1)print (\"2nd Input array : \", in_arr2) out_arr = geek.subtract(in_arr1, in_arr2) print (\"Output array: \", out_arr) ",
"e": 1876,
"s": 1545,
"text": null
},
{
"code": null,
"e": 2012,
"s": 1876,
"text": "1st Input array : [[ 2 -4 5]\n [-6 2 0]]\n2nd Input array : [[ 0 -7 5]\n [ 5 -2 9]]\nOutput array: [[ 2 3 0]\n [-11 4 -9]]\n\n"
},
{
"code": null,
"e": 2047,
"s": 2012,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 2060,
"s": 2047,
"text": "Python-numpy"
},
{
"code": null,
"e": 2067,
"s": 2060,
"text": "Python"
},
{
"code": null,
"e": 2165,
"s": 2067,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2183,
"s": 2165,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2225,
"s": 2183,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2247,
"s": 2225,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2282,
"s": 2247,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2308,
"s": 2282,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2340,
"s": 2308,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2369,
"s": 2340,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2396,
"s": 2369,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2417,
"s": 2396,
"text": "Python OOPs Concepts"
}
] |
Does Java support goto?
|
01 Sep, 2021
Java does not support goto, it is reserved as a keyword just in case they wanted to add it to a later version.
Unlike C/C++, Java does not have goto statement, but java supports label.
The only place where a label is useful in Java is right before nested loop statements.
We can specify label name with break to break out a specific outer loop.
Similarly, label name can be specified with continue.
Using break with label in Java
Java
// Java code to illustrate// using label and break// instead of goto // file name: Main.javapublic class Main { public static void main(String[] args) { // label for outer loop outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j == 1) break outer; System.out.println(" value of j = " + j); } } // end of outer loop } // end of main()} // end of class Main
value of j = 0
Using continue with label in Java
We can also use continue instead of break. See following program for example.
Java
// Java code to illustrate// using label and continue// instead of goto // file name: Main.javapublic class Main { public static void main(String[] args) { // label for outer loop outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j == 1) continue outer; System.out.println(" value of j = " + j); } } // end of outer loop } // end of main()} // end of class Main
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
value of j = 0
Explanation: Since continue statement skips to the next iteration in the loop, it iterates for 10 times as i iterates from 0 to 9. So the outer loop executes for 10 times and the inner for loop executes 1 time in each of the outer loops.Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. This usually makes goto-ridden code hard to understand and hard to maintain. It also prohibits certain compiler optimization. There are, however, a few places where the goto is a valuable and legitimate construct for flow control. For example, the goto can be useful when you are exiting from a deeply nested set of loops. To handle such situations, Java defines an expanded form of the break statement.The general form of the labelled break statement is:
break label;
Example 1:
Java
// Java codepublic class Label_Break1 { public static void main(String[] args) { boolean t = true; first : { second : { third : { System.out.println("Before the break"); if (t) // break out of second block break second; } System.out.println("This won't execute"); } System.out.println("This is after the second block"); } }}// This code is contributed by Sagar Gupta
Before the break
This is after the second block
Example 2:
Java
// Java codepublic class Label_Break2 { public static void main(String[] args) { outer: for (int i = 0; i < 3; i++) // label { System.out.print("Pass " + i + ": "); for (int j = 0; j < 100; j++) { if (j == 10) { break outer; // Exit both loops } System.out.print(j + " "); } System.out.println("This will not be printed"); } System.out.println("Loops Complete."); }}// This code is contributed by Sagar Gupta
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops Complete.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
subramaniyanvenkatraman
sagargupta6
chhabradhanvi
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 165,
"s": 52,
"text": "Java does not support goto, it is reserved as a keyword just in case they wanted to add it to a later version. "
},
{
"code": null,
"e": 239,
"s": 165,
"text": "Unlike C/C++, Java does not have goto statement, but java supports label."
},
{
"code": null,
"e": 326,
"s": 239,
"text": "The only place where a label is useful in Java is right before nested loop statements."
},
{
"code": null,
"e": 399,
"s": 326,
"text": "We can specify label name with break to break out a specific outer loop."
},
{
"code": null,
"e": 453,
"s": 399,
"text": "Similarly, label name can be specified with continue."
},
{
"code": null,
"e": 484,
"s": 453,
"text": "Using break with label in Java"
},
{
"code": null,
"e": 489,
"s": 484,
"text": "Java"
},
{
"code": "// Java code to illustrate// using label and break// instead of goto // file name: Main.javapublic class Main { public static void main(String[] args) { // label for outer loop outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j == 1) break outer; System.out.println(\" value of j = \" + j); } } // end of outer loop } // end of main()} // end of class Main",
"e": 970,
"s": 489,
"text": null
},
{
"code": null,
"e": 985,
"s": 970,
"text": "value of j = 0"
},
{
"code": null,
"e": 1021,
"s": 987,
"text": "Using continue with label in Java"
},
{
"code": null,
"e": 1100,
"s": 1021,
"text": "We can also use continue instead of break. See following program for example. "
},
{
"code": null,
"e": 1105,
"s": 1100,
"text": "Java"
},
{
"code": "// Java code to illustrate// using label and continue// instead of goto // file name: Main.javapublic class Main { public static void main(String[] args) { // label for outer loop outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (j == 1) continue outer; System.out.println(\" value of j = \" + j); } } // end of outer loop } // end of main()} // end of class Main",
"e": 1592,
"s": 1105,
"text": null
},
{
"code": null,
"e": 1751,
"s": 1592,
"text": "value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0\n value of j = 0"
},
{
"code": null,
"e": 2561,
"s": 1753,
"text": "Explanation: Since continue statement skips to the next iteration in the loop, it iterates for 10 times as i iterates from 0 to 9. So the outer loop executes for 10 times and the inner for loop executes 1 time in each of the outer loops.Java does not have a goto statement because it provides a way to branch in an arbitrary and unstructured manner. This usually makes goto-ridden code hard to understand and hard to maintain. It also prohibits certain compiler optimization. There are, however, a few places where the goto is a valuable and legitimate construct for flow control. For example, the goto can be useful when you are exiting from a deeply nested set of loops. To handle such situations, Java defines an expanded form of the break statement.The general form of the labelled break statement is: "
},
{
"code": null,
"e": 2574,
"s": 2561,
"text": "break label;"
},
{
"code": null,
"e": 2586,
"s": 2574,
"text": "Example 1: "
},
{
"code": null,
"e": 2591,
"s": 2586,
"text": "Java"
},
{
"code": "// Java codepublic class Label_Break1 { public static void main(String[] args) { boolean t = true; first : { second : { third : { System.out.println(\"Before the break\"); if (t) // break out of second block break second; } System.out.println(\"This won't execute\"); } System.out.println(\"This is after the second block\"); } }}// This code is contributed by Sagar Gupta",
"e": 3033,
"s": 2591,
"text": null
},
{
"code": null,
"e": 3081,
"s": 3033,
"text": "Before the break\nThis is after the second block"
},
{
"code": null,
"e": 3095,
"s": 3083,
"text": "Example 2: "
},
{
"code": null,
"e": 3100,
"s": 3095,
"text": "Java"
},
{
"code": "// Java codepublic class Label_Break2 { public static void main(String[] args) { outer: for (int i = 0; i < 3; i++) // label { System.out.print(\"Pass \" + i + \": \"); for (int j = 0; j < 100; j++) { if (j == 10) { break outer; // Exit both loops } System.out.print(j + \" \"); } System.out.println(\"This will not be printed\"); } System.out.println(\"Loops Complete.\"); }}// This code is contributed by Sagar Gupta",
"e": 3659,
"s": 3100,
"text": null
},
{
"code": null,
"e": 3703,
"s": 3659,
"text": "Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops Complete."
},
{
"code": null,
"e": 3831,
"s": 3705,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 3855,
"s": 3831,
"text": "subramaniyanvenkatraman"
},
{
"code": null,
"e": 3867,
"s": 3855,
"text": "sagargupta6"
},
{
"code": null,
"e": 3881,
"s": 3867,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 3886,
"s": 3881,
"text": "Java"
},
{
"code": null,
"e": 3891,
"s": 3886,
"text": "Java"
}
] |
Custom ArrayAdapter with ListView in Android
|
26 Nov, 2020
In the previous article ArrayAdapter in Android with Example, it’s been discussed how the ArrayAdapter works and what are the data sources which can be attached to the ArrayAdapter with ListView. In this article, it’s been discussed how to implement custom ArrayAdapter with the ListView. Have a look at the following image in which a single view in the ArrayAdapter can be customized.
Step 1: Create an Empty Activity project
Create an Empty Activity Android studio project. Refer to Android | How to Create/Start a New Project in Android Studio?
And make sure to select the programming as Java.
Step 2: Working with the activity_main.xml
In the activity_main.xml file, the root view is ListView. Invoke the following code into the activity_main.xml file and mention the appropriate ID for the ListView.
XML
<?xml version="1.0" encoding="utf-8"?><ListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"></ListView>
Step 3: Creating a custom View for ListView
Under layout, the folder creates a layout as custom_list_view.xml and invokes the following code.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" tools:ignore="UselessParent"> <ImageView android:id="@+id/imageView" android:layout_width="84dp" android:layout_height="84dp" android:padding="16dp" tools:ignore="ContentDescription" /> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:gravity="bottom|left" android:textColor="@android:color/black" android:textSize="18sp" android:textStyle="bold" tools:ignore="RtlHardcoded" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:gravity="top|left" android:textColor="@android:color/black" android:textSize="14sp" tools:ignore="RtlHardcoded" /> </LinearLayout> </LinearLayout>
For every single item in the ListView this layout creates the following view for every single item in the array adapter.
Step 4: Create a custom class for custom layout
By creating this custom class we invoke the getter and setter manually for the custom_list_view layout.
Create a custom class called NumbersView under the package folder of the Application.
And invoke the following code.
Java
public class NumbersView { // the resource ID for the imageView private int ivNumbersImageId; // TextView 1 private String mNumberInDigit; // TextView 1 private String mNumbersInText; // create constructor to set the values for all the parameters of the each single view public NumbersView(int NumbersImageId, String NumbersInDigit, String NumbersInText) { ivNumbersImageId = NumbersImageId; mNumberInDigit = NumbersInDigit; mNumbersInText = NumbersInText; } // getter method for returning the ID of the imageview public int getNumbersImageId() { return ivNumbersImageId; } // getter method for returning the ID of the TextView 1 public String getNumberInDigit() { return mNumberInDigit; } // getter method for returning the ID of the TextView 2 public String getNumbersInText() { return mNumbersInText; }}
Step 5: Now create a custom ArrayAdapter class of the type NumbersView
Under the same package name, create a NumbersViewAdapter.java class of the type NumbersView which extends the ArrayAdapter class.
And invoke the following code inside the NumbersViewAdapter.java file. Comments are added for better understanding.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class NumbersViewAdapter extends ArrayAdapter<NumbersView> { // invoke the suitable constructor of the ArrayAdapter class public NumbersViewAdapter(@NonNull Context context, ArrayList<NumbersView> arrayList) { // pass the context and arrayList for the super // constructor of the ArrayAdapter class super(context, 0, arrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // convertView which is recyclable view View currentItemView = convertView; // of the recyclable view is null then inflate the custom layout for the same if (currentItemView == null) { currentItemView = LayoutInflater.from(getContext()).inflate(R.layout.custom_list_view, parent, false); } // get the position of the view from the ArrayAdapter NumbersView currentNumberPosition = getItem(position); // then according to the position of the view assign the desired image for the same ImageView numbersImage = currentItemView.findViewById(R.id.imageView); assert currentNumberPosition != null; numbersImage.setImageResource(currentNumberPosition.getNumbersImageId()); // then according to the position of the view assign the desired TextView 1 for the same TextView textView1 = currentItemView.findViewById(R.id.textView1); textView1.setText(currentNumberPosition.getNumberInDigit()); // then according to the position of the view assign the desired TextView 2 for the same TextView textView2 = currentItemView.findViewById(R.id.textView2); textView2.setText(currentNumberPosition.getNumbersInText()); // then return the recyclable view return currentItemView; }}
Step 6: Working with the MainActivity.java file
In this case, there is a need to create a custom ArrayList of all the items that are Image for ImageView, Text for TextView 1, Text for TextView 2.
Java
import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a arraylist of the type NumbersView final ArrayList<NumbersView> arrayList = new ArrayList<NumbersView>(); // add all the values from 1 to 15 to the arrayList // the items are of the type NumbersView arrayList.add(new NumbersView(R.drawable.geeks_logo, "1", "One")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "2", "Two")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "3", "Three")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "4", "Four")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "5", "Five")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "6", "Six")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "7", "Seven")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "8", "Eight")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "9", "Nine")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "10", "Ten")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "11", "Eleven")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "12", "Twelve")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "13", "Thirteen")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "14", "Fourteen")); arrayList.add(new NumbersView(R.drawable.geeks_logo, "15", "Fifteen")); // Now create the instance of the NumebrsViewAdapter and pass // the context and arrayList created above NumbersViewAdapter numbersArrayAdapter = new NumbersViewAdapter(this, arrayList); // create the instance of the ListView to set the numbersViewAdapter ListView numbersListView = findViewById(R.id.listView); // set the numbersViewAdapter for ListView numbersListView.setAdapter(numbersArrayAdapter); }}
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
Android SDK and it's Components
Broadcast Receiver in Android With Example
How to Communicate Between Fragments in Android?
Arrays in Java
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 438,
"s": 52,
"text": "In the previous article ArrayAdapter in Android with Example, it’s been discussed how the ArrayAdapter works and what are the data sources which can be attached to the ArrayAdapter with ListView. In this article, it’s been discussed how to implement custom ArrayAdapter with the ListView. Have a look at the following image in which a single view in the ArrayAdapter can be customized."
},
{
"code": null,
"e": 479,
"s": 438,
"text": "Step 1: Create an Empty Activity project"
},
{
"code": null,
"e": 600,
"s": 479,
"text": "Create an Empty Activity Android studio project. Refer to Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 649,
"s": 600,
"text": "And make sure to select the programming as Java."
},
{
"code": null,
"e": 692,
"s": 649,
"text": "Step 2: Working with the activity_main.xml"
},
{
"code": null,
"e": 857,
"s": 692,
"text": "In the activity_main.xml file, the root view is ListView. Invoke the following code into the activity_main.xml file and mention the appropriate ID for the ListView."
},
{
"code": null,
"e": 861,
"s": 857,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><ListView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:id=\"@+id/listView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"></ListView>",
"e": 1176,
"s": 861,
"text": null
},
{
"code": null,
"e": 1220,
"s": 1176,
"text": "Step 3: Creating a custom View for ListView"
},
{
"code": null,
"e": 1318,
"s": 1220,
"text": "Under layout, the folder creates a layout as custom_list_view.xml and invokes the following code."
},
{
"code": null,
"e": 1322,
"s": 1318,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"horizontal\" tools:ignore=\"UselessParent\"> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"84dp\" android:layout_height=\"84dp\" android:padding=\"16dp\" tools:ignore=\"ContentDescription\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center_vertical\" android:orientation=\"vertical\"> <TextView android:id=\"@+id/textView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"16dp\" android:gravity=\"bottom|left\" android:textColor=\"@android:color/black\" android:textSize=\"18sp\" android:textStyle=\"bold\" tools:ignore=\"RtlHardcoded\" /> <TextView android:id=\"@+id/textView2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginBottom=\"16dp\" android:gravity=\"top|left\" android:textColor=\"@android:color/black\" android:textSize=\"14sp\" tools:ignore=\"RtlHardcoded\" /> </LinearLayout> </LinearLayout>",
"e": 2823,
"s": 1322,
"text": null
},
{
"code": null,
"e": 2944,
"s": 2823,
"text": "For every single item in the ListView this layout creates the following view for every single item in the array adapter."
},
{
"code": null,
"e": 2992,
"s": 2944,
"text": "Step 4: Create a custom class for custom layout"
},
{
"code": null,
"e": 3096,
"s": 2992,
"text": "By creating this custom class we invoke the getter and setter manually for the custom_list_view layout."
},
{
"code": null,
"e": 3182,
"s": 3096,
"text": "Create a custom class called NumbersView under the package folder of the Application."
},
{
"code": null,
"e": 3213,
"s": 3182,
"text": "And invoke the following code."
},
{
"code": null,
"e": 3218,
"s": 3213,
"text": "Java"
},
{
"code": "public class NumbersView { // the resource ID for the imageView private int ivNumbersImageId; // TextView 1 private String mNumberInDigit; // TextView 1 private String mNumbersInText; // create constructor to set the values for all the parameters of the each single view public NumbersView(int NumbersImageId, String NumbersInDigit, String NumbersInText) { ivNumbersImageId = NumbersImageId; mNumberInDigit = NumbersInDigit; mNumbersInText = NumbersInText; } // getter method for returning the ID of the imageview public int getNumbersImageId() { return ivNumbersImageId; } // getter method for returning the ID of the TextView 1 public String getNumberInDigit() { return mNumberInDigit; } // getter method for returning the ID of the TextView 2 public String getNumbersInText() { return mNumbersInText; }}",
"e": 4135,
"s": 3218,
"text": null
},
{
"code": null,
"e": 4206,
"s": 4135,
"text": "Step 5: Now create a custom ArrayAdapter class of the type NumbersView"
},
{
"code": null,
"e": 4336,
"s": 4206,
"text": "Under the same package name, create a NumbersViewAdapter.java class of the type NumbersView which extends the ArrayAdapter class."
},
{
"code": null,
"e": 4452,
"s": 4336,
"text": "And invoke the following code inside the NumbersViewAdapter.java file. Comments are added for better understanding."
},
{
"code": null,
"e": 4457,
"s": 4452,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class NumbersViewAdapter extends ArrayAdapter<NumbersView> { // invoke the suitable constructor of the ArrayAdapter class public NumbersViewAdapter(@NonNull Context context, ArrayList<NumbersView> arrayList) { // pass the context and arrayList for the super // constructor of the ArrayAdapter class super(context, 0, arrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // convertView which is recyclable view View currentItemView = convertView; // of the recyclable view is null then inflate the custom layout for the same if (currentItemView == null) { currentItemView = LayoutInflater.from(getContext()).inflate(R.layout.custom_list_view, parent, false); } // get the position of the view from the ArrayAdapter NumbersView currentNumberPosition = getItem(position); // then according to the position of the view assign the desired image for the same ImageView numbersImage = currentItemView.findViewById(R.id.imageView); assert currentNumberPosition != null; numbersImage.setImageResource(currentNumberPosition.getNumbersImageId()); // then according to the position of the view assign the desired TextView 1 for the same TextView textView1 = currentItemView.findViewById(R.id.textView1); textView1.setText(currentNumberPosition.getNumberInDigit()); // then according to the position of the view assign the desired TextView 2 for the same TextView textView2 = currentItemView.findViewById(R.id.textView2); textView2.setText(currentNumberPosition.getNumbersInText()); // then return the recyclable view return currentItemView; }}",
"e": 6603,
"s": 4457,
"text": null
},
{
"code": null,
"e": 6651,
"s": 6603,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 6799,
"s": 6651,
"text": "In this case, there is a need to create a custom ArrayList of all the items that are Image for ImageView, Text for TextView 1, Text for TextView 2."
},
{
"code": null,
"e": 6804,
"s": 6799,
"text": "Java"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.widget.ListView;import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // create a arraylist of the type NumbersView final ArrayList<NumbersView> arrayList = new ArrayList<NumbersView>(); // add all the values from 1 to 15 to the arrayList // the items are of the type NumbersView arrayList.add(new NumbersView(R.drawable.geeks_logo, \"1\", \"One\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"2\", \"Two\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"3\", \"Three\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"4\", \"Four\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"5\", \"Five\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"6\", \"Six\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"7\", \"Seven\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"8\", \"Eight\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"9\", \"Nine\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"10\", \"Ten\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"11\", \"Eleven\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"12\", \"Twelve\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"13\", \"Thirteen\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"14\", \"Fourteen\")); arrayList.add(new NumbersView(R.drawable.geeks_logo, \"15\", \"Fifteen\")); // Now create the instance of the NumebrsViewAdapter and pass // the context and arrayList created above NumbersViewAdapter numbersArrayAdapter = new NumbersViewAdapter(this, arrayList); // create the instance of the ListView to set the numbersViewAdapter ListView numbersListView = findViewById(R.id.listView); // set the numbersViewAdapter for ListView numbersListView.setAdapter(numbersArrayAdapter); }}",
"e": 9007,
"s": 6804,
"text": null
},
{
"code": null,
"e": 9015,
"s": 9007,
"text": "android"
},
{
"code": null,
"e": 9039,
"s": 9015,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9047,
"s": 9039,
"text": "Android"
},
{
"code": null,
"e": 9052,
"s": 9047,
"text": "Java"
},
{
"code": null,
"e": 9071,
"s": 9052,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9076,
"s": 9071,
"text": "Java"
},
{
"code": null,
"e": 9084,
"s": 9076,
"text": "Android"
},
{
"code": null,
"e": 9182,
"s": 9084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9251,
"s": 9182,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 9282,
"s": 9251,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 9314,
"s": 9282,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 9357,
"s": 9314,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 9406,
"s": 9357,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 9421,
"s": 9406,
"text": "Arrays in Java"
},
{
"code": null,
"e": 9465,
"s": 9421,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 9490,
"s": 9465,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9541,
"s": 9490,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Spring @Autowired Annotation
|
The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −
Here is the content of TextEditor.java file −
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public void setSpellChecker( SpellChecker spellChecker ){
this.spellChecker = spellChecker;
}
public SpellChecker getSpellChecker( ) {
return spellChecker;
}
public void spellCheck() {
spellChecker.checkSpelling();
}
}
Following is the content of another dependent class file SpellChecker.java:
package com.tutorialspoint;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
TextEditor te = (TextEditor) context.getBean("textEditor");
te.spellCheck();
}
}
Following is the configuration file Beans.xml −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker">
</bean>
</beans>
Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −
Inside SpellChecker constructor.
Inside checkSpelling.
You can use @Autowired annotation on properties to get rid of the setter methods. When you will pass values of autowired properties using <property> Spring will automatically assign those properties with the passed values or references. So with the usage of @Autowired on properties your TextEditor.java file will become as follows −
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
@Autowired
private SpellChecker spellChecker;
public TextEditor() {
System.out.println("Inside TextEditor constructor." );
}
public SpellChecker getSpellChecker( ){
return spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
Following is the configuration file Beans.xml −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- Definition for textEditor bean -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker">
</bean>
</beans>
Once you are done with the above two changes in source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −
Inside TextEditor constructor.
Inside SpellChecker constructor.
Inside checkSpelling.
You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file. Let us check the following example.
Here is the content of TextEditor.java file −
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class TextEditor {
private SpellChecker spellChecker;
@Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("Inside TextEditor constructor." );
this.spellChecker = spellChecker;
}
public void spellCheck(){
spellChecker.checkSpelling();
}
}
Following is the configuration file Beans.xml −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context = "http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id = "textEditor" class = "com.tutorialspoint.TextEditor">
</bean>
<!-- Definition for spellChecker bean -->
<bean id = "spellChecker" class = "com.tutorialspoint.SpellChecker">
</bean>
</beans>
Once you are done with the above two changes in source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:
Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.
By default, the @Autowired annotation implies the dependency is required similar to @Required annotation, however, you can turn off the default behavior by using (required=false) option with @Autowired.
The following example will work even if you do not pass any value for age property but still it will demand for name property. You can try this example yourself because this is similar to @Required annotation example except that only Student.java file has been changed.
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
public class Student {
private Integer age;
private String name;
@Autowired(required=false)
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Autowired
public void setName(String name) {
this.name = name;
}
public String getName() {
|
[
{
"code": null,
"e": 2733,
"s": 2426,
"text": "The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments."
},
{
"code": null,
"e": 2971,
"s": 2733,
"text": "You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method."
},
{
"code": null,
"e": 3076,
"s": 2971,
"text": "Let us have working Eclipse IDE in place and follow the following steps to create a Spring application −"
},
{
"code": null,
"e": 3122,
"s": 3076,
"text": "Here is the content of TextEditor.java file −"
},
{
"code": null,
"e": 3549,
"s": 3122,
"text": "package com.tutorialspoint;\n\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n\n @Autowired\n public void setSpellChecker( SpellChecker spellChecker ){\n this.spellChecker = spellChecker;\n }\n public SpellChecker getSpellChecker( ) {\n return spellChecker;\n }\n public void spellCheck() {\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 3625,
"s": 3549,
"text": "Following is the content of another dependent class file SpellChecker.java:"
},
{
"code": null,
"e": 3867,
"s": 3625,
"text": "package com.tutorialspoint;\n\npublic class SpellChecker {\n public SpellChecker(){\n System.out.println(\"Inside SpellChecker constructor.\" );\n }\n public void checkSpelling(){\n System.out.println(\"Inside checkSpelling.\" );\n }\n}"
},
{
"code": null,
"e": 3919,
"s": 3867,
"text": "Following is the content of the MainApp.java file −"
},
{
"code": null,
"e": 4328,
"s": 3919,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n TextEditor te = (TextEditor) context.getBean(\"textEditor\");\n\n te.spellCheck();\n }\n}"
},
{
"code": null,
"e": 4376,
"s": 4328,
"text": "Following is the configuration file Beans.xml −"
},
{
"code": null,
"e": 5179,
"s": 4376,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://www.springframework.org/schema/context\n http://www.springframework.org/schema/context/spring-context.xsd\">\n\n <context:annotation-config/>\n\n <!-- Definition for textEditor bean without constructor-arg -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\">\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 5361,
"s": 5179,
"text": "Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −"
},
{
"code": null,
"e": 5417,
"s": 5361,
"text": "Inside SpellChecker constructor.\nInside checkSpelling.\n"
},
{
"code": null,
"e": 5751,
"s": 5417,
"text": "You can use @Autowired annotation on properties to get rid of the setter methods. When you will pass values of autowired properties using <property> Spring will automatically assign those properties with the passed values or references. So with the usage of @Autowired on properties your TextEditor.java file will become as follows −"
},
{
"code": null,
"e": 6161,
"s": 5751,
"text": "package com.tutorialspoint;\n\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic class TextEditor {\n @Autowired\n private SpellChecker spellChecker;\n\n public TextEditor() {\n System.out.println(\"Inside TextEditor constructor.\" );\n }\n public SpellChecker getSpellChecker( ){\n return spellChecker;\n }\n public void spellCheck(){\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 6209,
"s": 6161,
"text": "Following is the configuration file Beans.xml −"
},
{
"code": null,
"e": 6987,
"s": 6209,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://www.springframework.org/schema/context\n http://www.springframework.org/schema/context/spring-context.xsd\">\n\n <context:annotation-config/>\n\n <!-- Definition for textEditor bean -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\">\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 7185,
"s": 6987,
"text": "Once you are done with the above two changes in source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message −"
},
{
"code": null,
"e": 7272,
"s": 7185,
"text": "Inside TextEditor constructor.\nInside SpellChecker constructor.\nInside checkSpelling.\n"
},
{
"code": null,
"e": 7556,
"s": 7272,
"text": "You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file. Let us check the following example."
},
{
"code": null,
"e": 7602,
"s": 7556,
"text": "Here is the content of TextEditor.java file −"
},
{
"code": null,
"e": 8001,
"s": 7602,
"text": "package com.tutorialspoint;\n\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic class TextEditor {\n private SpellChecker spellChecker;\n\n @Autowired\n public TextEditor(SpellChecker spellChecker){\n System.out.println(\"Inside TextEditor constructor.\" );\n this.spellChecker = spellChecker;\n }\n public void spellCheck(){\n spellChecker.checkSpelling();\n }\n}"
},
{
"code": null,
"e": 8049,
"s": 8001,
"text": "Following is the configuration file Beans.xml −"
},
{
"code": null,
"e": 8852,
"s": 8049,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans.xsd\n http://www.springframework.org/schema/context\n http://www.springframework.org/schema/context/spring-context.xsd\">\n\n <context:annotation-config/>\n\n <!-- Definition for textEditor bean without constructor-arg -->\n <bean id = \"textEditor\" class = \"com.tutorialspoint.TextEditor\">\n </bean>\n\n <!-- Definition for spellChecker bean -->\n <bean id = \"spellChecker\" class = \"com.tutorialspoint.SpellChecker\">\n </bean>\n\n</beans>"
},
{
"code": null,
"e": 9049,
"s": 8852,
"text": "Once you are done with the above two changes in source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message:"
},
{
"code": null,
"e": 9136,
"s": 9049,
"text": "Inside SpellChecker constructor.\nInside TextEditor constructor.\nInside checkSpelling.\n"
},
{
"code": null,
"e": 9340,
"s": 9136,
"text": "By default, the @Autowired annotation implies the dependency is required similar to @Required annotation, however, you can turn off the default behavior by using (required=false) option with @Autowired."
},
{
"code": null,
"e": 9610,
"s": 9340,
"text": "The following example will work even if you do not pass any value for age property but still it will demand for name property. You can try this example yourself because this is similar to @Required annotation example except that only Student.java file has been changed."
}
] |
Python | Remove all characters except letters and numbers
|
14 Jun, 2022
Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the request and response in HTTP queries are in the form of strings with sometimes some useless data which we need to remove. Let’s discuss some Pythonic ways to remove all the characters except numbers and alphabets. Method #1: Using re.sub
Python3
# Python code to demonstrate# to remove all the characters# except numbers and alphabets import re # initialising stringini_string = "123abcjw:, .@! eiw" # printing initial stringprint ("initial string : ", ini_string) # function to demonstrate removal of characters# which are not numbers and alphabets using re result = re.sub('[\W_]+', '', ini_string) # printing final stringprint ("final string", result)
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw
Method #2: Using isalpha() and isnumeric()
Python3
# Python code to demonstrate# to remove all the characters# except numbers and alphabets import re # initialising stringini_string = "123abcjw:, .@! eiw" # printing initial stringprint ("initial string : ", ini_string) # function to demonstrate removal of characters# which are not numbers and alphabets using regetVals = list([val for val in ini_string if val.isalpha() or val.isnumeric()]) result = "".join(getVals) # printing final stringprint ("final string", result)
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw
Method #3: Using alnum()
Python3
# Python code to demonstrate# to remove all the characters# except numbers and alphabets # initialising stringini_string = "123abcjw:, .@! eiw" # printing initial stringprint ("initial string : ", ini_string) # function to demonstrate removal of characters# which are not numbers and alphabets using regetVals = list([val for val in ini_string if val.isalnum()])result = "".join(getVals) # printing final stringprint ("final string", result)
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw
Method#4: Using filter and in
Python3
# Python code to demonstrate# to remove all the characters# except numbers and alphabets # initialising stringini_string = "123abcjw:, .@! eiw" # printing initial stringprint ("initial string : ", ini_string) k = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";# function to demonstrate removal of characters# which are not numbers and alphabets using filter and ingetVals = list(filter(lambda x: x in k, ini_string))result = "".join(getVals) # printing final stringprint ("final string", result)
Output:
initial string : 123abcjw:, .@! eiw
final string 123abcjweiw
satyam00so
Python Regex-programs
Python string-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 455,
"s": 28,
"text": "Given a string, the task is to remove all the characters except numbers and alphabets. String manipulation is a very important task in a day to day coding and web development. Most of the request and response in HTTP queries are in the form of strings with sometimes some useless data which we need to remove. Let’s discuss some Pythonic ways to remove all the characters except numbers and alphabets. Method #1: Using re.sub "
},
{
"code": null,
"e": 463,
"s": 455,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to remove all the characters# except numbers and alphabets import re # initialising stringini_string = \"123abcjw:, .@! eiw\" # printing initial stringprint (\"initial string : \", ini_string) # function to demonstrate removal of characters# which are not numbers and alphabets using re result = re.sub('[\\W_]+', '', ini_string) # printing final stringprint (\"final string\", result)",
"e": 872,
"s": 463,
"text": null
},
{
"code": null,
"e": 934,
"s": 872,
"text": "initial string : 123abcjw:, .@! eiw\nfinal string 123abcjweiw"
},
{
"code": null,
"e": 980,
"s": 934,
"text": " Method #2: Using isalpha() and isnumeric() "
},
{
"code": null,
"e": 988,
"s": 980,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to remove all the characters# except numbers and alphabets import re # initialising stringini_string = \"123abcjw:, .@! eiw\" # printing initial stringprint (\"initial string : \", ini_string) # function to demonstrate removal of characters# which are not numbers and alphabets using regetVals = list([val for val in ini_string if val.isalpha() or val.isnumeric()]) result = \"\".join(getVals) # printing final stringprint (\"final string\", result)",
"e": 1474,
"s": 988,
"text": null
},
{
"code": null,
"e": 1536,
"s": 1474,
"text": "initial string : 123abcjw:, .@! eiw\nfinal string 123abcjweiw"
},
{
"code": null,
"e": 1564,
"s": 1536,
"text": " Method #3: Using alnum() "
},
{
"code": null,
"e": 1572,
"s": 1564,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to remove all the characters# except numbers and alphabets # initialising stringini_string = \"123abcjw:, .@! eiw\" # printing initial stringprint (\"initial string : \", ini_string) # function to demonstrate removal of characters# which are not numbers and alphabets using regetVals = list([val for val in ini_string if val.isalnum()])result = \"\".join(getVals) # printing final stringprint (\"final string\", result)",
"e": 2014,
"s": 1572,
"text": null
},
{
"code": null,
"e": 2076,
"s": 2014,
"text": "initial string : 123abcjw:, .@! eiw\nfinal string 123abcjweiw"
},
{
"code": null,
"e": 2107,
"s": 2076,
"text": "Method#4: Using filter and in "
},
{
"code": null,
"e": 2115,
"s": 2107,
"text": "Python3"
},
{
"code": "# Python code to demonstrate# to remove all the characters# except numbers and alphabets # initialising stringini_string = \"123abcjw:, .@! eiw\" # printing initial stringprint (\"initial string : \", ini_string) k = \"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";# function to demonstrate removal of characters# which are not numbers and alphabets using filter and ingetVals = list(filter(lambda x: x in k, ini_string))result = \"\".join(getVals) # printing final stringprint (\"final string\", result)",
"e": 2630,
"s": 2115,
"text": null
},
{
"code": null,
"e": 2638,
"s": 2630,
"text": "Output:"
},
{
"code": null,
"e": 2700,
"s": 2638,
"text": "initial string : 123abcjw:, .@! eiw\nfinal string 123abcjweiw"
},
{
"code": null,
"e": 2711,
"s": 2700,
"text": "satyam00so"
},
{
"code": null,
"e": 2733,
"s": 2711,
"text": "Python Regex-programs"
},
{
"code": null,
"e": 2756,
"s": 2733,
"text": "Python string-programs"
},
{
"code": null,
"e": 2769,
"s": 2756,
"text": "python-regex"
},
{
"code": null,
"e": 2776,
"s": 2769,
"text": "Python"
},
{
"code": null,
"e": 2792,
"s": 2776,
"text": "Python Programs"
},
{
"code": null,
"e": 2890,
"s": 2792,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2908,
"s": 2890,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2950,
"s": 2908,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2972,
"s": 2950,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3007,
"s": 2972,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3033,
"s": 3007,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3076,
"s": 3033,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 3098,
"s": 3076,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3137,
"s": 3098,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3175,
"s": 3137,
"text": "Python | Convert a list to dictionary"
}
] |
How to include a font .ttf using CSS ?
|
13 Aug, 2021
Adding .ttf fonts using CSS: In the late 1980s, after getting beaten by adobe’s type 1 fonts, Apple came up with a new font format type which is .ttf(True Type Font). These fonts were so awesome that, they become the most common font formats all over the world in a very short time. In fact, windows itself started using them in there operating system.
Then, if you wish to use these font formats in your web pages, here is a detailed step by step explanation, how to import and use .ttf(true type fonts) in Html using CSS.
1. Download .ttf format file: The .ttf format is quite famous nowadays, these font files are available for free on Google. You can visit font space, font squirrel, etc websites that provide these fonts for free. Keep all the files in the same folder.
2. Create a HTML file: Create a HTML file and add a h2 tag for demonstrating our font style.
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"></head><body> <h2>This font is awesome</h2></body></html>
3. Create a CSS file: For adding external fonts through CSS, we use the @Font-face attribute property to manually define font name and giving source file. Afterward, we can access our defined font in any element required with Font-family property.
@font-face {
font-family: myFirstFont;
src: url(ArianaVioleta-dz2K.ttf);
}
h2 {
font-family: myFirstFont;
color: darkgreen;
}
Final result: This is how our font look on the browser
font in browser
If you didn’t catch the idea in the above example, let’s try with another font style.
HTML File:
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"></head><body> <p>The font on this paragraph looks awesome</p> </body></html>
CSS File:
@font-face {
font-family: myFirstFont;
src: url(ChrustyRock-ORLA.ttf);
}
h2 {
font-family: myFirstFont;
color: darkgreen;
}
Output:
2nd example with a new font
Supported Browser:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
ysachin2314
akshaysingh98088
CSS-Misc
HTML-Misc
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": 28,
"s": 0,
"text": "\n13 Aug, 2021"
},
{
"code": null,
"e": 381,
"s": 28,
"text": "Adding .ttf fonts using CSS: In the late 1980s, after getting beaten by adobe’s type 1 fonts, Apple came up with a new font format type which is .ttf(True Type Font). These fonts were so awesome that, they become the most common font formats all over the world in a very short time. In fact, windows itself started using them in there operating system."
},
{
"code": null,
"e": 552,
"s": 381,
"text": "Then, if you wish to use these font formats in your web pages, here is a detailed step by step explanation, how to import and use .ttf(true type fonts) in Html using CSS."
},
{
"code": null,
"e": 803,
"s": 552,
"text": "1. Download .ttf format file: The .ttf format is quite famous nowadays, these font files are available for free on Google. You can visit font space, font squirrel, etc websites that provide these fonts for free. Keep all the files in the same folder."
},
{
"code": null,
"e": 897,
"s": 803,
"text": "2. Create a HTML file: Create a HTML file and add a h2 tag for demonstrating our font style. "
},
{
"code": null,
"e": 902,
"s": 897,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"style.css\"></head><body> <h2>This font is awesome</h2></body></html>",
"e": 1154,
"s": 902,
"text": null
},
{
"code": null,
"e": 1403,
"s": 1154,
"text": "3. Create a CSS file: For adding external fonts through CSS, we use the @Font-face attribute property to manually define font name and giving source file. Afterward, we can access our defined font in any element required with Font-family property. "
},
{
"code": null,
"e": 1548,
"s": 1403,
"text": "@font-face {\n font-family: myFirstFont;\n src: url(ArianaVioleta-dz2K.ttf);\n}\n \nh2 {\n font-family: myFirstFont;\n color: darkgreen;\n}"
},
{
"code": null,
"e": 1604,
"s": 1548,
"text": " Final result: This is how our font look on the browser"
},
{
"code": null,
"e": 1620,
"s": 1604,
"text": "font in browser"
},
{
"code": null,
"e": 1706,
"s": 1620,
"text": "If you didn’t catch the idea in the above example, let’s try with another font style."
},
{
"code": null,
"e": 1718,
"s": 1706,
"text": "HTML File: "
},
{
"code": null,
"e": 1723,
"s": 1718,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"style.css\"></head><body> <p>The font on this paragraph looks awesome</p> </body></html>",
"e": 1999,
"s": 1723,
"text": null
},
{
"code": null,
"e": 2013,
"s": 2002,
"text": "CSS File: "
},
{
"code": null,
"e": 2151,
"s": 2013,
"text": "@font-face {\n font-family: myFirstFont;\n src: url(ChrustyRock-ORLA.ttf);\n}\n \nh2 {\n font-family: myFirstFont;\n color: darkgreen;\n}"
},
{
"code": null,
"e": 2162,
"s": 2153,
"text": "Output: "
},
{
"code": null,
"e": 2190,
"s": 2162,
"text": "2nd example with a new font"
},
{
"code": null,
"e": 2209,
"s": 2190,
"text": "Supported Browser:"
},
{
"code": null,
"e": 2223,
"s": 2209,
"text": "Google Chrome"
},
{
"code": null,
"e": 2241,
"s": 2223,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2249,
"s": 2241,
"text": "Firefox"
},
{
"code": null,
"e": 2255,
"s": 2249,
"text": "Opera"
},
{
"code": null,
"e": 2262,
"s": 2255,
"text": "Safari"
},
{
"code": null,
"e": 2274,
"s": 2262,
"text": "ysachin2314"
},
{
"code": null,
"e": 2291,
"s": 2274,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 2300,
"s": 2291,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2310,
"s": 2300,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2317,
"s": 2310,
"text": "Picked"
},
{
"code": null,
"e": 2321,
"s": 2317,
"text": "CSS"
},
{
"code": null,
"e": 2326,
"s": 2321,
"text": "HTML"
},
{
"code": null,
"e": 2343,
"s": 2326,
"text": "Web Technologies"
},
{
"code": null,
"e": 2348,
"s": 2343,
"text": "HTML"
},
{
"code": null,
"e": 2446,
"s": 2348,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2485,
"s": 2446,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2524,
"s": 2485,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2563,
"s": 2524,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2592,
"s": 2563,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2629,
"s": 2592,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2653,
"s": 2629,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2706,
"s": 2653,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2766,
"s": 2706,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2827,
"s": 2766,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
HTML <body> Tag
|
17 Mar, 2022
The <body> tag in HTML is used to define the main content present inside an HTML page. It is always enclosed within <html>tag. The <body> tag is the last child of <html> tag. A body tag contains starting as well as an ending tag.
Syntax:
<body> Body Contents... </body>
Attributes: There are many attributes in the <body> tag which are depreciated from HTML5 are listed below:
background: It contains the URL of the background image. It is used to set the background image.
bgcolor: It is used to specify the background color of an image.
alink: It is used to specify the color of the active link.
link: It is used to specify the color of visited links.
text: It specifies the color of the text in a document.
vlink: It specifies the color of visited links.
Example : Using HTML body tag. All then content placed inside the body tag.
HTML
<!DOCTYPE html><html> <!-- body tag starts here --><body> <h1>GeeksforGeeks</h1> <h2>body Tag</h2> <p>This is paragraph text</p> </body><!-- body tag ends here --> </html>
Output:
Example 2: Example to show the functioning of a Body tag along with its CSS implementation.
HTML
<!DOCTYPE html><html> <!-- style on the body tag --><!-- body tag starts here --><body style="background-color:seagreen"> <h1>GeeksforGeeks</h1> <h2>HTML body Tag</h2> <p>This is paragraph Tag</p> </body><!-- body tag ends here --></html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
shubhamyadav4
HTML-Tags
Picked
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 284,
"s": 53,
"text": "The <body> tag in HTML is used to define the main content present inside an HTML page. It is always enclosed within <html>tag. The <body> tag is the last child of <html> tag. A body tag contains starting as well as an ending tag. "
},
{
"code": null,
"e": 293,
"s": 284,
"text": "Syntax: "
},
{
"code": null,
"e": 325,
"s": 293,
"text": "<body> Body Contents... </body>"
},
{
"code": null,
"e": 433,
"s": 325,
"text": "Attributes: There are many attributes in the <body> tag which are depreciated from HTML5 are listed below: "
},
{
"code": null,
"e": 530,
"s": 433,
"text": "background: It contains the URL of the background image. It is used to set the background image."
},
{
"code": null,
"e": 595,
"s": 530,
"text": "bgcolor: It is used to specify the background color of an image."
},
{
"code": null,
"e": 654,
"s": 595,
"text": "alink: It is used to specify the color of the active link."
},
{
"code": null,
"e": 710,
"s": 654,
"text": "link: It is used to specify the color of visited links."
},
{
"code": null,
"e": 766,
"s": 710,
"text": "text: It specifies the color of the text in a document."
},
{
"code": null,
"e": 814,
"s": 766,
"text": "vlink: It specifies the color of visited links."
},
{
"code": null,
"e": 890,
"s": 814,
"text": "Example : Using HTML body tag. All then content placed inside the body tag."
},
{
"code": null,
"e": 895,
"s": 890,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <!-- body tag starts here --><body> <h1>GeeksforGeeks</h1> <h2>body Tag</h2> <p>This is paragraph text</p> </body><!-- body tag ends here --> </html>",
"e": 1083,
"s": 895,
"text": null
},
{
"code": null,
"e": 1093,
"s": 1083,
"text": "Output: "
},
{
"code": null,
"e": 1185,
"s": 1093,
"text": "Example 2: Example to show the functioning of a Body tag along with its CSS implementation."
},
{
"code": null,
"e": 1190,
"s": 1185,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <!-- style on the body tag --><!-- body tag starts here --><body style=\"background-color:seagreen\"> <h1>GeeksforGeeks</h1> <h2>HTML body Tag</h2> <p>This is paragraph Tag</p> </body><!-- body tag ends here --></html>",
"e": 1442,
"s": 1190,
"text": null
},
{
"code": null,
"e": 1452,
"s": 1442,
"text": "Output: "
},
{
"code": null,
"e": 1473,
"s": 1452,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 1487,
"s": 1473,
"text": "Google Chrome"
},
{
"code": null,
"e": 1505,
"s": 1487,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1513,
"s": 1505,
"text": "Firefox"
},
{
"code": null,
"e": 1519,
"s": 1513,
"text": "Opera"
},
{
"code": null,
"e": 1526,
"s": 1519,
"text": "Safari"
},
{
"code": null,
"e": 1540,
"s": 1526,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 1550,
"s": 1540,
"text": "HTML-Tags"
},
{
"code": null,
"e": 1557,
"s": 1550,
"text": "Picked"
},
{
"code": null,
"e": 1562,
"s": 1557,
"text": "HTML"
},
{
"code": null,
"e": 1567,
"s": 1562,
"text": "HTML"
},
{
"code": null,
"e": 1665,
"s": 1567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1713,
"s": 1665,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1775,
"s": 1713,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1825,
"s": 1775,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 1849,
"s": 1825,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1902,
"s": 1849,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 1962,
"s": 1902,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2023,
"s": 1962,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 2073,
"s": 2023,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2112,
"s": 2073,
"text": "Design a Tribute Page using HTML & CSS"
}
] |
MongoDB – Equality Operator $eq
|
27 Mar, 2020
MongoDB provides different types of comparison operators and an equality operator($eq) is one of them. 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.
Important Points:
If the given value is a document, then the order of the fields in the document is important.
If the given value is an array, then MongoDB matches the documents where the field contains an element that exactly matches the specified array.
Syntax:
{field: {$eq: value}}
or
{field: value}
In the following examples, we are working with:
Database: GeeksforGeeksCollection: employeeDocument: five documents that contain the details of the employees in the form of field-value pairs.
Example #1:In this example, we are selecting those documents where the value of the salary field is equal to 30000.
db.employee.find({salary: {$eq: 30000}}).pretty()
It is equivalent to –
db.employee.find({salary: 30000}).pretty()
Example #2:In this example, we are selecting those documents where the first name of the employee is equal to Amu. or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation.
db.employee.find({"name.first": {$eq: "Amu"}}).pretty()
It is equivalent to:
db.employee.find({"name.first": "Amu"}).pretty()
Example #3:In this example, we are selecting those documents where the language array contains an element with value “C++”.
db.employee.find({language: {$eq: "C++"}}).pretty()
It is equivalent to:
db.employee.find({language: "C++"}).pretty()
Example #4:In this example, we are selecting those documents where the language array is equal to the specified array.
db.employee.find({language: {$eq: ["C#", "Java"]}}).pretty()
It is equivalent to:
db.employee.find({language:["C#", "Java"]}).pretty()
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
Mounting a Volume Inside Docker Container
Fuzzy Logic | Introduction
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Mar, 2020"
},
{
"code": null,
"e": 354,
"s": 53,
"text": "MongoDB provides different types of comparison operators and an equality operator($eq) is one of them. 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": 372,
"s": 354,
"text": "Important Points:"
},
{
"code": null,
"e": 465,
"s": 372,
"text": "If the given value is a document, then the order of the fields in the document is important."
},
{
"code": null,
"e": 610,
"s": 465,
"text": "If the given value is an array, then MongoDB matches the documents where the field contains an element that exactly matches the specified array."
},
{
"code": null,
"e": 618,
"s": 610,
"text": "Syntax:"
},
{
"code": null,
"e": 660,
"s": 618,
"text": "{field: {$eq: value}}\nor\n{field: value}\n\n"
},
{
"code": null,
"e": 708,
"s": 660,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 852,
"s": 708,
"text": "Database: GeeksforGeeksCollection: employeeDocument: five documents that contain the details of the employees in the form of field-value pairs."
},
{
"code": null,
"e": 969,
"s": 852,
"text": " Example #1:In this example, we are selecting those documents where the value of the salary field is equal to 30000."
},
{
"code": "db.employee.find({salary: {$eq: 30000}}).pretty()",
"e": 1019,
"s": 969,
"text": null
},
{
"code": null,
"e": 1041,
"s": 1019,
"text": "It is equivalent to –"
},
{
"code": "db.employee.find({salary: 30000}).pretty()",
"e": 1084,
"s": 1041,
"text": null
},
{
"code": null,
"e": 1323,
"s": 1084,
"text": " Example #2:In this example, we are selecting those documents where the first name of the employee is equal to Amu. or in other words, in this example, we are specifying conditions on the field in the embedded document using dot notation."
},
{
"code": "db.employee.find({\"name.first\": {$eq: \"Amu\"}}).pretty()",
"e": 1379,
"s": 1323,
"text": null
},
{
"code": null,
"e": 1400,
"s": 1379,
"text": "It is equivalent to:"
},
{
"code": "db.employee.find({\"name.first\": \"Amu\"}).pretty()",
"e": 1449,
"s": 1400,
"text": null
},
{
"code": null,
"e": 1574,
"s": 1449,
"text": " Example #3:In this example, we are selecting those documents where the language array contains an element with value “C++”."
},
{
"code": "db.employee.find({language: {$eq: \"C++\"}}).pretty()",
"e": 1626,
"s": 1574,
"text": null
},
{
"code": null,
"e": 1647,
"s": 1626,
"text": "It is equivalent to:"
},
{
"code": "db.employee.find({language: \"C++\"}).pretty()",
"e": 1692,
"s": 1647,
"text": null
},
{
"code": null,
"e": 1812,
"s": 1692,
"text": " Example #4:In this example, we are selecting those documents where the language array is equal to the specified array."
},
{
"code": "db.employee.find({language: {$eq: [\"C#\", \"Java\"]}}).pretty()",
"e": 1873,
"s": 1812,
"text": null
},
{
"code": null,
"e": 1894,
"s": 1873,
"text": "It is equivalent to:"
},
{
"code": "db.employee.find({language:[\"C#\", \"Java\"]}).pretty()",
"e": 1947,
"s": 1894,
"text": null
},
{
"code": null,
"e": 1955,
"s": 1947,
"text": "MongoDB"
},
{
"code": null,
"e": 1981,
"s": 1955,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 2079,
"s": 1981,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2115,
"s": 2079,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 2159,
"s": 2115,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 2195,
"s": 2159,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 2219,
"s": 2195,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 2254,
"s": 2219,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 2295,
"s": 2254,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 2343,
"s": 2295,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 2384,
"s": 2343,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 2426,
"s": 2384,
"text": "Mounting a Volume Inside Docker Container"
}
] |
Next Permutation | Practice | GeeksforGeeks
|
Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers. If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N.
Example 1:
Input: N = 6
arr = {1, 2, 3, 6, 5, 4}
Output: {1, 2, 4, 3, 5, 6}
Explaination: The next permutation of the
given array is {1, 2, 4, 3, 5, 6}.
Example 2:
Input: N = 3
arr = {3, 2, 1}
Output: {1, 2, 3}
Explaination: As arr[] is the last
permutation. So, the next permutation
is the lowest one.
Your Task:
You do not need to read input or print anything. Your task is to complete the function nextPermutation() which takes N and arr[ ] as input parameters and returns a list of numbers containing the next permutation.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 10000
0
skumar2009200111 hours ago
c++ sol in 0.01 sec
vector<int> nextPermutation(int N, vector<int> arr){ // code here for(int i=N-1;i>0;i--){ if(arr[i]>arr[i-1]){ for(int j=N-1;j>=i;j--){ if(arr[i-1]<arr[j]){ swap(arr[i-1],arr[j]); break; } } sort(arr.begin()+i,arr.end()); return arr; break; } } sort(arr.begin(),arr.end()); return arr; }
0
aamitprasad6181 day ago
CPP
int ind1=-1;
int ind2=-1;
// int n=nums.size();
for(int i=n-2;i>=0;i--){
if(nums[i] < nums[i+1]){
ind1=i;
break;
}
}
if(ind1<0){
sort(nums.begin(),nums.end());
return nums;
}
for(int i=n-1;i>=0;i--){
if(nums[i]>nums[ind1]){
ind2=i;
break;
}
}
swap(nums[ind1],nums[ind2]);
reverse(nums.begin()+ind1+1,nums.end());
return nums;
0
smondalqwerty1 day ago
vector<int> nextPermutation(int n, vector<int> arr) { int i;
for (i = n - 1; i > 0; i--) { if (arr[i] > arr[i - 1]) { break; } } if (i!=0) { int min = arr[i], k=i;
for (int j = i; j < n; j++) { if (arr[j] > arr[i - 1] && arr[j] < min) { k = j; min = arr[j]; } } swap(arr[i-1],arr[k]); } sort(arr.begin()+i,arr.end());
return arr; }
0
debayanbiswas312 days ago
TC: O(N)
SC: O(1)
vector<int> nextPermutation(int n, vector<int> arr){
// code here
int index1=-1;
int index2=-1;
for(int i=n-1;i>=0;i--)
{
if(arr[i-1]<arr[i])
{
index1=i-1;
break;
}
}
if(index1==-1)
{
reverse(arr.begin(),arr.end());
return arr;
}
int diff=INT_MAX;
for(int i=index1+1;i<n;i++)
{
if(arr[i]<=arr[index1])
{
break;
}
if(arr[i]-arr[index1]<diff)
{
diff=arr[i]-arr[index1];
index2=i;
}
}
swap(arr[index1],arr[index2]);
reverse(arr.begin()+index1+1,arr.end());
return arr;
}
0
ddttx776 days ago
vector<int> rev(vector<int> v, int j)
{
vector<int> ans;
for(int i=v.size()-1;i>=j;i--)
ans.push_back(v[i]);
return ans;
}
vector<int> nextPermutation(int N, vector<int> arr)
{
int i,j;
for(i=N-2;i>=0;i--)
{
if(arr[i]<arr[i+1])
break;
}
if(i<0)
return rev(arr,0);
else
{
for(j=N-1;j>i;j--)
{
if(arr[j]>arr[i])
break;
}
swap(arr[i],arr[j]);
vector<int> temp=rev(arr,i+1);
vector<int> ans;
for(j=0;j<=i;j++)
ans.push_back(arr[j]);
for(j=0;j<temp.size();j++)
ans.push_back(temp[j]);
return ans;
}
}
0
jaydhurat6 days ago
class Solution{
static List<Integer> nextPermutation(int n, int a[]){
// code here
List<Integer> list = new ArrayList<>();
int idx1 = 0;
int idx2 = 0;
int j = 0;
for(int i = n-1;i>=0;i--)
{
if(i+1<n && a[i]<a[i+1])
{
idx1 = i;
break;
}
j=i;
}
if(j==0)
{
for(int i=n-1;i>=0;i--)
{
list.add(a[i]);
}
return list;
}
for(int i = n-1;i>=0;i--)
{
if(a[idx1]<a[i])
{
idx2 = i;
break;
}
}
int temp = a[idx1];
a[idx1] = a[idx2];
a[idx2] = temp;
for(int i = 0;i<=idx1;i++)
{
list.add(a[i]);
}
for(int i=n-1;i>idx1;i--)
{
list.add(a[i]);
}
return list;
}
}
0
tonroyjptt1 week ago
Java Solution
class Solution{ static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void reverse(int[] arr, int i, int j){ while(i<j){ swap(arr, i++, j--); } }
static List<Integer> nextPermutation(int N, int arr[]){ // code here ArrayList<Integer> ans = new ArrayList<>(); int i = arr.length - 2; while(i >= 0 && arr[i] >= arr[i+1]) i--; if(i>=0){ int j = arr.length - 1; while(arr[i] >= arr[j]) j--; swap(arr, i, j); } reverse(arr, i+1, arr.length-1); for(int k=0; k<N; k++){ ans.add(arr[k]); } return ans; }}
0
mahesh_phutane1 week ago
Java Solution
class Solution{
static void swap(int[] arr,int i,int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
static void reverse(int[] arr,int i,int j){
while(i<j){
swap(arr,i++,j--);
}
}
static List<Integer> nextPermutation(int N, int arr[]){
int idx = -1;
List<Integer> ans = new ArrayList<>();
for(int i = N-1;i>0;i--){
if(arr[i]>arr[i-1]){
idx = i;
break;
}
}
if(idx==-1){
Arrays.sort(arr);
}else{
int idx2 = idx;
for(int i = idx+1;i<N;i++){
if(arr[i]>arr[idx-1]&&arr[i]<arr[idx]){
idx2 = i;
}
}
swap(arr,idx-1,idx2);
reverse(arr,idx,N-1);
}
for(int i = 0;i<N;i++){
ans.add(arr[i]);
}
return ans;
}
}
0
prachiacharya20011 week ago
void swap(vector<int>&arr,int i,int j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } void reverse(int i,int j,vector<int>&arr){ while(i<j) swap(arr,i++,j--); } vector<int> nextPermutation(int N, vector<int> arr){ // code here if(arr.size()==NULL||arr.size()<=1) return arr; int i=arr.size()-2; while(i>=0&& arr[i]>=arr[i+1]) i--; if(i>=0){ int j=arr.size()-1; while(arr[j]<=arr[i]) j--; swap(arr,i,j); } reverse(i+1,arr.size()-1,arr); return arr;
0
raushanrakesh0692 weeks ago
Java Script Solution
class Solution { nextPermutation(arr,n){ const swap = (i, j) => [arr[i],arr[j]] = [arr[j],arr[i]]
let len = n - 1, i for (i = len - 1; arr[i] >= arr[i+1];) i-- let j = i + 1, k = len while (j < k) swap(j++,k--) if (i >= 0) { for (j = i + 1; arr[i] >= arr[j];) j++ swap(i,j) } return arr; }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 549,
"s": 238,
"text": "Implement the next permutation, which rearranges the list of numbers into Lexicographically next greater permutation of list of numbers. If such arrangement is not possible, it must be rearranged to the lowest possible order i.e. sorted in an ascending order. You are given an list of numbers arr[ ] of size N."
},
{
"code": null,
"e": 560,
"s": 549,
"text": "Example 1:"
},
{
"code": null,
"e": 703,
"s": 560,
"text": "Input: N = 6\narr = {1, 2, 3, 6, 5, 4}\nOutput: {1, 2, 4, 3, 5, 6}\nExplaination: The next permutation of the \ngiven array is {1, 2, 4, 3, 5, 6}."
},
{
"code": null,
"e": 714,
"s": 703,
"text": "Example 2:"
},
{
"code": null,
"e": 855,
"s": 714,
"text": "Input: N = 3\narr = {3, 2, 1}\nOutput: {1, 2, 3}\nExplaination: As arr[] is the last \npermutation. So, the next permutation \nis the lowest one."
},
{
"code": null,
"e": 1079,
"s": 855,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function nextPermutation() which takes N and arr[ ] as input parameters and returns a list of numbers containing the next permutation."
},
{
"code": null,
"e": 1141,
"s": 1079,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1168,
"s": 1141,
"text": "Constraints:\n1 ≤ N ≤ 10000"
},
{
"code": null,
"e": 1170,
"s": 1168,
"text": "0"
},
{
"code": null,
"e": 1197,
"s": 1170,
"text": "skumar2009200111 hours ago"
},
{
"code": null,
"e": 1217,
"s": 1197,
"text": "c++ sol in 0.01 sec"
},
{
"code": null,
"e": 1707,
"s": 1217,
"text": "vector<int> nextPermutation(int N, vector<int> arr){ // code here for(int i=N-1;i>0;i--){ if(arr[i]>arr[i-1]){ for(int j=N-1;j>=i;j--){ if(arr[i-1]<arr[j]){ swap(arr[i-1],arr[j]); break; } } sort(arr.begin()+i,arr.end()); return arr; break; } } sort(arr.begin(),arr.end()); return arr; }"
},
{
"code": null,
"e": 1709,
"s": 1707,
"text": "0"
},
{
"code": null,
"e": 1733,
"s": 1709,
"text": "aamitprasad6181 day ago"
},
{
"code": null,
"e": 1737,
"s": 1733,
"text": "CPP"
},
{
"code": null,
"e": 2379,
"s": 1739,
"text": "int ind1=-1;\n int ind2=-1;\n \n // int n=nums.size();\n \n for(int i=n-2;i>=0;i--){\n if(nums[i] < nums[i+1]){\n ind1=i;\n break;\n }\n }\n \n if(ind1<0){\n sort(nums.begin(),nums.end());\n return nums;\n }\n \n for(int i=n-1;i>=0;i--){\n if(nums[i]>nums[ind1]){\n ind2=i;\n break;\n }\n }\n \n swap(nums[ind1],nums[ind2]);\n \n reverse(nums.begin()+ind1+1,nums.end());\n \n return nums;\n \n \n "
},
{
"code": null,
"e": 2381,
"s": 2379,
"text": "0"
},
{
"code": null,
"e": 2404,
"s": 2381,
"text": "smondalqwerty1 day ago"
},
{
"code": null,
"e": 2473,
"s": 2404,
"text": "vector<int> nextPermutation(int n, vector<int> arr) { int i;"
},
{
"code": null,
"e": 2657,
"s": 2473,
"text": " for (i = n - 1; i > 0; i--) { if (arr[i] > arr[i - 1]) { break; } } if (i!=0) { int min = arr[i], k=i;"
},
{
"code": null,
"e": 2906,
"s": 2657,
"text": " for (int j = i; j < n; j++) { if (arr[j] > arr[i - 1] && arr[j] < min) { k = j; min = arr[j]; } } swap(arr[i-1],arr[k]); } sort(arr.begin()+i,arr.end());"
},
{
"code": null,
"e": 2929,
"s": 2906,
"text": " return arr; }"
},
{
"code": null,
"e": 2931,
"s": 2929,
"text": "0"
},
{
"code": null,
"e": 2957,
"s": 2931,
"text": "debayanbiswas312 days ago"
},
{
"code": null,
"e": 2966,
"s": 2957,
"text": "TC: O(N)"
},
{
"code": null,
"e": 2975,
"s": 2966,
"text": "SC: O(1)"
},
{
"code": null,
"e": 3812,
"s": 2977,
"text": "vector<int> nextPermutation(int n, vector<int> arr){\n // code here\n int index1=-1;\n int index2=-1;\n for(int i=n-1;i>=0;i--)\n {\n if(arr[i-1]<arr[i])\n {\n index1=i-1;\n break;\n }\n }\n if(index1==-1)\n {\n reverse(arr.begin(),arr.end());\n return arr;\n }\n int diff=INT_MAX;\n for(int i=index1+1;i<n;i++)\n {\n if(arr[i]<=arr[index1])\n {\n break;\n }\n if(arr[i]-arr[index1]<diff)\n {\n diff=arr[i]-arr[index1];\n index2=i;\n }\n }\n \n swap(arr[index1],arr[index2]);\n reverse(arr.begin()+index1+1,arr.end());\n return arr;\n \n \n }"
},
{
"code": null,
"e": 3814,
"s": 3812,
"text": "0"
},
{
"code": null,
"e": 3832,
"s": 3814,
"text": "ddttx776 days ago"
},
{
"code": null,
"e": 4665,
"s": 3832,
"text": "\tvector<int> rev(vector<int> v, int j)\n {\n vector<int> ans;\n for(int i=v.size()-1;i>=j;i--)\n ans.push_back(v[i]);\n return ans;\n }\n vector<int> nextPermutation(int N, vector<int> arr)\n {\n int i,j;\n for(i=N-2;i>=0;i--)\n {\n if(arr[i]<arr[i+1])\n break;\n }\n if(i<0)\n return rev(arr,0);\n else\n {\n for(j=N-1;j>i;j--)\n {\n if(arr[j]>arr[i])\n break;\n }\n swap(arr[i],arr[j]);\n vector<int> temp=rev(arr,i+1);\n vector<int> ans;\n for(j=0;j<=i;j++)\n ans.push_back(arr[j]);\n for(j=0;j<temp.size();j++)\n ans.push_back(temp[j]);\n return ans;\n }\n }"
},
{
"code": null,
"e": 4667,
"s": 4665,
"text": "0"
},
{
"code": null,
"e": 4687,
"s": 4667,
"text": "jaydhurat6 days ago"
},
{
"code": null,
"e": 5692,
"s": 4687,
"text": "class Solution{\n static List<Integer> nextPermutation(int n, int a[]){\n // code here\n List<Integer> list = new ArrayList<>();\n \n int idx1 = 0;\n int idx2 = 0;\n int j = 0;\n \n for(int i = n-1;i>=0;i--)\n {\n if(i+1<n && a[i]<a[i+1])\n {\n idx1 = i;\n break;\n }\n j=i;\n }\n if(j==0)\n {\n for(int i=n-1;i>=0;i--)\n \n {\n list.add(a[i]);\n \n }\n return list;\n }\n \n \n for(int i = n-1;i>=0;i--)\n {\n if(a[idx1]<a[i])\n {\n idx2 = i;\n break;\n }\n }\n int temp = a[idx1];\n a[idx1] = a[idx2];\n a[idx2] = temp;\n \n for(int i = 0;i<=idx1;i++)\n {\n list.add(a[i]);\n }\n for(int i=n-1;i>idx1;i--)\n {\n list.add(a[i]);\n }\n return list;\n }\n}"
},
{
"code": null,
"e": 5694,
"s": 5692,
"text": "0"
},
{
"code": null,
"e": 5715,
"s": 5694,
"text": "tonroyjptt1 week ago"
},
{
"code": null,
"e": 5729,
"s": 5715,
"text": "Java Solution"
},
{
"code": null,
"e": 5975,
"s": 5729,
"text": "class Solution{ static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void reverse(int[] arr, int i, int j){ while(i<j){ swap(arr, i++, j--); } }"
},
{
"code": null,
"e": 6445,
"s": 5975,
"text": " static List<Integer> nextPermutation(int N, int arr[]){ // code here ArrayList<Integer> ans = new ArrayList<>(); int i = arr.length - 2; while(i >= 0 && arr[i] >= arr[i+1]) i--; if(i>=0){ int j = arr.length - 1; while(arr[i] >= arr[j]) j--; swap(arr, i, j); } reverse(arr, i+1, arr.length-1); for(int k=0; k<N; k++){ ans.add(arr[k]); } return ans; }}"
},
{
"code": null,
"e": 6447,
"s": 6445,
"text": "0"
},
{
"code": null,
"e": 6472,
"s": 6447,
"text": "mahesh_phutane1 week ago"
},
{
"code": null,
"e": 6486,
"s": 6472,
"text": "Java Solution"
},
{
"code": null,
"e": 7438,
"s": 6486,
"text": "class Solution{\n static void swap(int[] arr,int i,int j){\n int tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n static void reverse(int[] arr,int i,int j){\n while(i<j){\n swap(arr,i++,j--);\n }\n }\n static List<Integer> nextPermutation(int N, int arr[]){\n int idx = -1;\n List<Integer> ans = new ArrayList<>();\n for(int i = N-1;i>0;i--){\n if(arr[i]>arr[i-1]){\n idx = i;\n break;\n }\n }\n if(idx==-1){\n Arrays.sort(arr);\n }else{\n int idx2 = idx;\n for(int i = idx+1;i<N;i++){\n if(arr[i]>arr[idx-1]&&arr[i]<arr[idx]){\n idx2 = i;\n }\n }\n swap(arr,idx-1,idx2);\n reverse(arr,idx,N-1);\n }\n for(int i = 0;i<N;i++){\n ans.add(arr[i]);\n }\n return ans;\n }\n}"
},
{
"code": null,
"e": 7440,
"s": 7438,
"text": "0"
},
{
"code": null,
"e": 7468,
"s": 7440,
"text": "prachiacharya20011 week ago"
},
{
"code": null,
"e": 8028,
"s": 7468,
"text": " void swap(vector<int>&arr,int i,int j){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } void reverse(int i,int j,vector<int>&arr){ while(i<j) swap(arr,i++,j--); } vector<int> nextPermutation(int N, vector<int> arr){ // code here if(arr.size()==NULL||arr.size()<=1) return arr; int i=arr.size()-2; while(i>=0&& arr[i]>=arr[i+1]) i--; if(i>=0){ int j=arr.size()-1; while(arr[j]<=arr[i]) j--; swap(arr,i,j); } reverse(i+1,arr.size()-1,arr); return arr;"
},
{
"code": null,
"e": 8030,
"s": 8028,
"text": "0"
},
{
"code": null,
"e": 8058,
"s": 8030,
"text": "raushanrakesh0692 weeks ago"
},
{
"code": null,
"e": 8079,
"s": 8058,
"text": "Java Script Solution"
},
{
"code": null,
"e": 8194,
"s": 8081,
"text": "class Solution { nextPermutation(arr,n){ const swap = (i, j) => [arr[i],arr[j]] = [arr[j],arr[i]]"
},
{
"code": null,
"e": 8421,
"s": 8194,
"text": " let len = n - 1, i for (i = len - 1; arr[i] >= arr[i+1];) i-- let j = i + 1, k = len while (j < k) swap(j++,k--) if (i >= 0) { for (j = i + 1; arr[i] >= arr[j];) j++ swap(i,j) } return arr; }} "
},
{
"code": null,
"e": 8569,
"s": 8423,
"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": 8605,
"s": 8569,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8615,
"s": 8605,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8625,
"s": 8615,
"text": "\nContest\n"
},
{
"code": null,
"e": 8688,
"s": 8625,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8873,
"s": 8688,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9157,
"s": 8873,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 9303,
"s": 9157,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 9380,
"s": 9303,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 9421,
"s": 9380,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 9449,
"s": 9421,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 9520,
"s": 9449,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 9707,
"s": 9520,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Hierarchical treeview in Python GUI application
|
18 Jan, 2021
Python uses different GUI applications that are helpful for the users while interacting with the applications they are using. There are basically three GUI(s) that python uses namely Tkinter, wxPython, and PyQt. All of these can operate with windows, Linux, and mac-OS. However, these GUI applications have many widgets i.e, controls that are helpful for the user interaction with the application. Some of the widgets are buttons, list boxes, scrollbar, treeview, etc. Note: For more information, refer to Python GUI – tkinter
This widget is helpful in visualizing and permitting navigation over a hierarchy of items. It can display more than one feature of every item in the hierarchy. It can build a tree view as a user interface like in Windows explorer. Therefore, here we will use Tkinter in order to construct a hierarchical treeview in the Python GUI application. Let’s see an example of constructing a hierarchical treeview in Python GUI application.
The GUI would look like below:
Example:
Python
# Python program to illustrate the usage# of hierarchical treeview in python GUI# application using tkinter # Importing tkinterfrom tkinter import * # Importing ttk from tkinterfrom tkinter import ttk # Creating app windowapp = Tk() # Defining title of the appapp.title("GUI Application of Python") # Defining label of the app and calling a geometry# management method i.e, pack in order to organize# widgets in form of blocks before locating them# in the parent widgetttk.Label(app, text ="Treeview(hierarchical)").pack() # Creating treeview windowtreeview = ttk.Treeview(app) # Calling pack method on the treeviewtreeview.pack() # Inserting items to the treeview# Inserting parenttreeview.insert('', '0', 'item1', text ='GeeksforGeeks') # Inserting childtreeview.insert('', '1', 'item2', text ='Computer Science')treeview.insert('', '2', 'item3', text ='GATE papers')treeview.insert('', 'end', 'item4', text ='Programming Languages') # Inserting more than one attribute of an itemtreeview.insert('item2', 'end', 'Algorithm', text ='Algorithm') treeview.insert('item2', 'end', 'Data structure', text ='Data structure')treeview.insert('item3', 'end', '2018 paper', text ='2018 paper') treeview.insert('item3', 'end', '2019 paper', text ='2019 paper')treeview.insert('item4', 'end', 'Python', text ='Python')treeview.insert('item4', 'end', 'Java', text ='Java') # Placing each child items in parent widgettreeview.move('item2', 'item1', 'end') treeview.move('item3', 'item1', 'end')treeview.move('item4', 'item1', 'end') # Calling main() app.mainloop()
Output:
In the above output, a hierarchical treeview is created. Where, GeeksforGeeks is the parent with Computer Science, GATE papers and Programming Languages as its child. And all the child have their respective attributes attached to them. At last, move() method is called here in order to connect all the children to the parent tree.
abhigoya
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 556,
"s": 28,
"text": "Python uses different GUI applications that are helpful for the users while interacting with the applications they are using. There are basically three GUI(s) that python uses namely Tkinter, wxPython, and PyQt. All of these can operate with windows, Linux, and mac-OS. However, these GUI applications have many widgets i.e, controls that are helpful for the user interaction with the application. Some of the widgets are buttons, list boxes, scrollbar, treeview, etc. Note: For more information, refer to Python GUI – tkinter "
},
{
"code": null,
"e": 989,
"s": 556,
"text": "This widget is helpful in visualizing and permitting navigation over a hierarchy of items. It can display more than one feature of every item in the hierarchy. It can build a tree view as a user interface like in Windows explorer. Therefore, here we will use Tkinter in order to construct a hierarchical treeview in the Python GUI application. Let’s see an example of constructing a hierarchical treeview in Python GUI application. "
},
{
"code": null,
"e": 1020,
"s": 989,
"text": "The GUI would look like below:"
},
{
"code": null,
"e": 1031,
"s": 1020,
"text": "Example: "
},
{
"code": null,
"e": 1038,
"s": 1031,
"text": "Python"
},
{
"code": "# Python program to illustrate the usage# of hierarchical treeview in python GUI# application using tkinter # Importing tkinterfrom tkinter import * # Importing ttk from tkinterfrom tkinter import ttk # Creating app windowapp = Tk() # Defining title of the appapp.title(\"GUI Application of Python\") # Defining label of the app and calling a geometry# management method i.e, pack in order to organize# widgets in form of blocks before locating them# in the parent widgetttk.Label(app, text =\"Treeview(hierarchical)\").pack() # Creating treeview windowtreeview = ttk.Treeview(app) # Calling pack method on the treeviewtreeview.pack() # Inserting items to the treeview# Inserting parenttreeview.insert('', '0', 'item1', text ='GeeksforGeeks') # Inserting childtreeview.insert('', '1', 'item2', text ='Computer Science')treeview.insert('', '2', 'item3', text ='GATE papers')treeview.insert('', 'end', 'item4', text ='Programming Languages') # Inserting more than one attribute of an itemtreeview.insert('item2', 'end', 'Algorithm', text ='Algorithm') treeview.insert('item2', 'end', 'Data structure', text ='Data structure')treeview.insert('item3', 'end', '2018 paper', text ='2018 paper') treeview.insert('item3', 'end', '2019 paper', text ='2019 paper')treeview.insert('item4', 'end', 'Python', text ='Python')treeview.insert('item4', 'end', 'Java', text ='Java') # Placing each child items in parent widgettreeview.move('item2', 'item1', 'end') treeview.move('item3', 'item1', 'end')treeview.move('item4', 'item1', 'end') # Calling main() app.mainloop()",
"e": 2746,
"s": 1038,
"text": null
},
{
"code": null,
"e": 2755,
"s": 2746,
"text": "Output: "
},
{
"code": null,
"e": 3087,
"s": 2755,
"text": "In the above output, a hierarchical treeview is created. Where, GeeksforGeeks is the parent with Computer Science, GATE papers and Programming Languages as its child. And all the child have their respective attributes attached to them. At last, move() method is called here in order to connect all the children to the parent tree. "
},
{
"code": null,
"e": 3096,
"s": 3087,
"text": "abhigoya"
},
{
"code": null,
"e": 3111,
"s": 3096,
"text": "Python-tkinter"
},
{
"code": null,
"e": 3118,
"s": 3111,
"text": "Python"
},
{
"code": null,
"e": 3216,
"s": 3118,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3244,
"s": 3216,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3294,
"s": 3244,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3316,
"s": 3294,
"text": "Python map() function"
},
{
"code": null,
"e": 3360,
"s": 3316,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 3402,
"s": 3360,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3424,
"s": 3402,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3459,
"s": 3424,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3485,
"s": 3459,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3517,
"s": 3485,
"text": "How to Install PIP on Windows ?"
}
] |
cksum command in Linux with examples
|
15 May, 2019
cksum command in Linux is used to display a CRC(Cyclic Redundancy Check) value, the byte size of the file and the name of the file to standard output. CRC is unique for each file and only changes if the file is edited. It is used to check whether the file had accidentally corrupted while transfer. If the CRC is same after the transfer, it means that the file had not accidentally corrupted.
Syntax:
cksum [FileName]
Note: An intruder can corrupt a file in such a way that it produces the same CRC value after the transfer. That is why it is only checked for accidental corruption.
Options:
–help : It displays help information.–version : It displays version information.
–help : It displays help information.
–version : It displays version information.
linux-command
Linux-file-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 421,
"s": 28,
"text": "cksum command in Linux is used to display a CRC(Cyclic Redundancy Check) value, the byte size of the file and the name of the file to standard output. CRC is unique for each file and only changes if the file is edited. It is used to check whether the file had accidentally corrupted while transfer. If the CRC is same after the transfer, it means that the file had not accidentally corrupted."
},
{
"code": null,
"e": 429,
"s": 421,
"text": "Syntax:"
},
{
"code": null,
"e": 446,
"s": 429,
"text": "cksum [FileName]"
},
{
"code": null,
"e": 611,
"s": 446,
"text": "Note: An intruder can corrupt a file in such a way that it produces the same CRC value after the transfer. That is why it is only checked for accidental corruption."
},
{
"code": null,
"e": 620,
"s": 611,
"text": "Options:"
},
{
"code": null,
"e": 701,
"s": 620,
"text": "–help : It displays help information.–version : It displays version information."
},
{
"code": null,
"e": 739,
"s": 701,
"text": "–help : It displays help information."
},
{
"code": null,
"e": 783,
"s": 739,
"text": "–version : It displays version information."
},
{
"code": null,
"e": 797,
"s": 783,
"text": "linux-command"
},
{
"code": null,
"e": 817,
"s": 797,
"text": "Linux-file-commands"
},
{
"code": null,
"e": 824,
"s": 817,
"text": "Picked"
},
{
"code": null,
"e": 848,
"s": 824,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 859,
"s": 848,
"text": "Linux-Unix"
},
{
"code": null,
"e": 878,
"s": 859,
"text": "Technical Scripter"
},
{
"code": null,
"e": 976,
"s": 878,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1002,
"s": 976,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1037,
"s": 1002,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1074,
"s": 1037,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1103,
"s": 1074,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1137,
"s": 1103,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1174,
"s": 1137,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1211,
"s": 1174,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 1250,
"s": 1211,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 1290,
"s": 1250,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
GATE | Gate IT 2008 | Question 69
|
16 Nov, 2020
A Binary Search Tree (BST) stores values in the range 37 to 573. Consider the following sequence of keys.
I. 81, 537, 102, 439, 285, 376, 305
II. 52, 97, 121, 195, 242, 381, 472
III. 142, 248, 520, 386, 345, 270, 307
IV. 550, 149, 507, 395, 463, 402, 270
Suppose the BST has been unsuccessfully searched for key 273. Which all of the above sequences list nodes in the order in which we could have encountered them in the search?(A) II and III only(B) I and III only(C) III and IV only(D) III onlyAnswer: (D)Explanation: Key to be searched 273:
I) 81, 537, 102, 439, 285, 376, 305 is not correctWe cannot go to 376 from 285 as 273 is smaller than 285.
II) 52, 97, 121, 195, 242, 381, 472 is not correct.We cannot go to 472 from 381 as 273 is smaller than 381.
III) 142, 248, 520, 386, 345, 270, 307 is correct
550, 149, 507, 395, 463, 402, 270 is not correct.We cannot go to 463 from 395 in search of 273
Following representation of the binary search trees is given below.
Quiz of this Question
vivekyemul786
Gate IT 2008
GATE-Gate IT 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2001 | Question 50
GATE | GATE CS 1996 | Question 38
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Nov, 2020"
},
{
"code": null,
"e": 160,
"s": 54,
"text": "A Binary Search Tree (BST) stores values in the range 37 to 573. Consider the following sequence of keys."
},
{
"code": null,
"e": 311,
"s": 160,
"text": "I. 81, 537, 102, 439, 285, 376, 305\nII. 52, 97, 121, 195, 242, 381, 472\nIII. 142, 248, 520, 386, 345, 270, 307\nIV. 550, 149, 507, 395, 463, 402, 270 "
},
{
"code": null,
"e": 600,
"s": 311,
"text": "Suppose the BST has been unsuccessfully searched for key 273. Which all of the above sequences list nodes in the order in which we could have encountered them in the search?(A) II and III only(B) I and III only(C) III and IV only(D) III onlyAnswer: (D)Explanation: Key to be searched 273:"
},
{
"code": null,
"e": 707,
"s": 600,
"text": "I) 81, 537, 102, 439, 285, 376, 305 is not correctWe cannot go to 376 from 285 as 273 is smaller than 285."
},
{
"code": null,
"e": 815,
"s": 707,
"text": "II) 52, 97, 121, 195, 242, 381, 472 is not correct.We cannot go to 472 from 381 as 273 is smaller than 381."
},
{
"code": null,
"e": 865,
"s": 815,
"text": "III) 142, 248, 520, 386, 345, 270, 307 is correct"
},
{
"code": null,
"e": 960,
"s": 865,
"text": "550, 149, 507, 395, 463, 402, 270 is not correct.We cannot go to 463 from 395 in search of 273"
},
{
"code": null,
"e": 1028,
"s": 960,
"text": "Following representation of the binary search trees is given below."
},
{
"code": null,
"e": 1050,
"s": 1028,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1064,
"s": 1050,
"text": "vivekyemul786"
},
{
"code": null,
"e": 1077,
"s": 1064,
"text": "Gate IT 2008"
},
{
"code": null,
"e": 1095,
"s": 1077,
"text": "GATE-Gate IT 2008"
},
{
"code": null,
"e": 1100,
"s": 1095,
"text": "GATE"
},
{
"code": null,
"e": 1198,
"s": 1100,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1240,
"s": 1198,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 1302,
"s": 1240,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 1344,
"s": 1302,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 1386,
"s": 1344,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 1420,
"s": 1386,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1454,
"s": 1420,
"text": "GATE | GATE CS 1996 | Question 63"
},
{
"code": null,
"e": 1496,
"s": 1454,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
},
{
"code": null,
"e": 1530,
"s": 1496,
"text": "GATE | GATE-CS-2004 | Question 31"
},
{
"code": null,
"e": 1564,
"s": 1530,
"text": "GATE | GATE-CS-2001 | Question 50"
}
] |
How to Manage Audio Focus in Android?
|
14 Dec, 2020
The audio focus in Android needs to be managed and it is one of the important to handle the audio interruptions. In android, many applications play media simultaneously, and to increase the User Experience the Audio interruptions are handled. For example, if the application is playing Audio, suddenly there is an incoming call then the audio file needs to be stopped and after the call is ended the Audio should continue playing from where it has stopped. In this article, it’s been discussed how to handle the Audio interruptions or how to implement the Audio Focus in Android. Have a look at the following image to get an idea of what things are going to be discussed. Note that we are going to implement this project using the Java language.
Step 1: Create an empty activity project
Create an empty activity Android Studio project. And select Java as a programming language.
To know how to create an empty activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml file
The main layout in this project includes only three buttons which are used to play, pause, and to stop the Audio file playing in the application.
Invoke the following code to implement the UI.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginStart="16dp" android:layout_marginTop="32dp" android:layout_marginEnd="16dp" android:text="Manage Audio Focus (Handling Audio interruptions in Android" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:gravity="center_horizontal" android:orientation="horizontal"> <Button android:id="@+id/stopButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="32dp" android:backgroundTint="@color/colorPrimary" android:drawableStart="@drawable/ic_stop" android:text="STOP" android:textColor="@android:color/white" /> <Button android:id="@+id/playButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="32dp" android:backgroundTint="@color/colorPrimary" android:drawableStart="@drawable/ic_play" android:text="PLAY" android:textColor="@android:color/white" /> <Button android:id="@+id/pasueButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimary" android:drawableStart="@drawable/ic_pause" android:text="PAUSE" android:textColor="@android:color/white" /> </LinearLayout> </RelativeLayout>
Output UI:
Step 3: Working with the MainActivity.java file
The main Callback needs to implemented when there is a change in the Audio focus. Meaning the system has transferred the audio focus to another service that is used by the app, in this case, the Phone application which takes the audio focus from the current application which is playing the audio.
AudioManager.OnAudioFocusChangeListener audioFocusChangeListener -> This handles if there is change in the audio focus which the callback need to implemented according to the focus change from the audio manage.
When the call gets hanged up the focus changes to the current application and MediaPlayer is resumed.
The focus request result which is returned by the Android system is compared to the following constants.
AUDIOFOCUS_GAIN: if the system grants the audio focus gain, then the playback can be continued after the temporary loss of the audio focus.AUDIOFOCUS_LOSS_TRANSIENT: if there is temporary loss of audio focus then the playback of the audio should be paused.AUDIOFOCUS_LOSS: if there is permenant loss of the audio then the mediaplayer should be released (completely stopped).
AUDIOFOCUS_GAIN: if the system grants the audio focus gain, then the playback can be continued after the temporary loss of the audio focus.
AUDIOFOCUS_LOSS_TRANSIENT: if there is temporary loss of audio focus then the playback of the audio should be paused.
AUDIOFOCUS_LOSS: if there is permenant loss of the audio then the mediaplayer should be released (completely stopped).
To implement the Audio focus in the application same as discussed above invoke the following code in the MainActivity.java file. Comments are added for better understanding.
Java
import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.media.AudioAttributes;import android.media.AudioFocusRequest;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.Button;import java.io.IOException; @RequiresApi(api = Build.VERSION_CODES.O)public class MainActivity extends AppCompatActivity { // media player instance to playback // the media file from the raw folder MediaPlayer mediaPlayer; // Audio manager instance to manage or // handle the audio interruptions AudioManager audioManager; // Audio attributes instance to set the playback // attributes for the media player instance // these attributes specify what type of media is // to be played and used to callback the audioFocusChangeListener AudioAttributes playbackAttributes; // media player is handled according to the // change in the focus which Android system grants for AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { mediaPlayer.start(); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) { mediaPlayer.pause(); mediaPlayer.seekTo(0); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { mediaPlayer.release(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the audio system service for // the audioManger instance audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // initiate the audio playback attributes playbackAttributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build(); // set the playback attributes for the focus requester AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setAudioAttributes(playbackAttributes) .setAcceptsDelayedFocusGain(true) .setOnAudioFocusChangeListener(audioFocusChangeListener) .build(); // request the audio focus and // store it in the int variable final int audioFocusRequest = audioManager.requestAudioFocus(focusRequest); // register all three buttons Button bPlay = findViewById(R.id.playButton); Button bPause = findViewById(R.id.pasueButton); Button bStop = findViewById(R.id.stopButton); // initiate the media player instance with // the media file from the raw folder mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music); // handle the PLAY button to play the audio bPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // request the audio focus by the Android system // if the system grants the permission // then start playing the audio file if (audioFocusRequest == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaPlayer.start(); } } }); // handle the PAUSE button to pause the media player bPause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.pause(); } }); // handle the STOP button to stop the media player bStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.stop(); try { // if the mediaplayer is stopped then // it should be again prepared for // next instance of play mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } } }); }}
Note: When there is no requirement of audio focus, abandonAudioFocusRequest method needs to be called with the AudioManager instance and it requires the parameter AudioFocusRequest focusRequest which needs to be passed.
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 801,
"s": 54,
"text": "The audio focus in Android needs to be managed and it is one of the important to handle the audio interruptions. In android, many applications play media simultaneously, and to increase the User Experience the Audio interruptions are handled. For example, if the application is playing Audio, suddenly there is an incoming call then the audio file needs to be stopped and after the call is ended the Audio should continue playing from where it has stopped. In this article, it’s been discussed how to handle the Audio interruptions or how to implement the Audio Focus in Android. Have a look at the following image to get an idea of what things are going to be discussed. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 842,
"s": 801,
"text": "Step 1: Create an empty activity project"
},
{
"code": null,
"e": 934,
"s": 842,
"text": "Create an empty activity Android Studio project. And select Java as a programming language."
},
{
"code": null,
"e": 1069,
"s": 934,
"text": "To know how to create an empty activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?"
},
{
"code": null,
"e": 1117,
"s": 1069,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 1263,
"s": 1117,
"text": "The main layout in this project includes only three buttons which are used to play, pause, and to stop the Audio file playing in the application."
},
{
"code": null,
"e": 1310,
"s": 1263,
"text": "Invoke the following code to implement the UI."
},
{
"code": null,
"e": 1314,
"s": 1310,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginStart=\"16dp\" android:layout_marginTop=\"32dp\" android:layout_marginEnd=\"16dp\" android:text=\"Manage Audio Focus (Handling Audio interruptions in Android\" android:textSize=\"18sp\" android:textStyle=\"bold\" /> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"100dp\" android:gravity=\"center_horizontal\" android:orientation=\"horizontal\"> <Button android:id=\"@+id/stopButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"32dp\" android:backgroundTint=\"@color/colorPrimary\" android:drawableStart=\"@drawable/ic_stop\" android:text=\"STOP\" android:textColor=\"@android:color/white\" /> <Button android:id=\"@+id/playButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginEnd=\"32dp\" android:backgroundTint=\"@color/colorPrimary\" android:drawableStart=\"@drawable/ic_play\" android:text=\"PLAY\" android:textColor=\"@android:color/white\" /> <Button android:id=\"@+id/pasueButton\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:backgroundTint=\"@color/colorPrimary\" android:drawableStart=\"@drawable/ic_pause\" android:text=\"PAUSE\" android:textColor=\"@android:color/white\" /> </LinearLayout> </RelativeLayout>",
"e": 3441,
"s": 1314,
"text": null
},
{
"code": null,
"e": 3452,
"s": 3441,
"text": "Output UI:"
},
{
"code": null,
"e": 3500,
"s": 3452,
"text": "Step 3: Working with the MainActivity.java file"
},
{
"code": null,
"e": 3798,
"s": 3500,
"text": "The main Callback needs to implemented when there is a change in the Audio focus. Meaning the system has transferred the audio focus to another service that is used by the app, in this case, the Phone application which takes the audio focus from the current application which is playing the audio."
},
{
"code": null,
"e": 4009,
"s": 3798,
"text": "AudioManager.OnAudioFocusChangeListener audioFocusChangeListener -> This handles if there is change in the audio focus which the callback need to implemented according to the focus change from the audio manage."
},
{
"code": null,
"e": 4111,
"s": 4009,
"text": "When the call gets hanged up the focus changes to the current application and MediaPlayer is resumed."
},
{
"code": null,
"e": 4216,
"s": 4111,
"text": "The focus request result which is returned by the Android system is compared to the following constants."
},
{
"code": null,
"e": 4591,
"s": 4216,
"text": "AUDIOFOCUS_GAIN: if the system grants the audio focus gain, then the playback can be continued after the temporary loss of the audio focus.AUDIOFOCUS_LOSS_TRANSIENT: if there is temporary loss of audio focus then the playback of the audio should be paused.AUDIOFOCUS_LOSS: if there is permenant loss of the audio then the mediaplayer should be released (completely stopped)."
},
{
"code": null,
"e": 4731,
"s": 4591,
"text": "AUDIOFOCUS_GAIN: if the system grants the audio focus gain, then the playback can be continued after the temporary loss of the audio focus."
},
{
"code": null,
"e": 4849,
"s": 4731,
"text": "AUDIOFOCUS_LOSS_TRANSIENT: if there is temporary loss of audio focus then the playback of the audio should be paused."
},
{
"code": null,
"e": 4968,
"s": 4849,
"text": "AUDIOFOCUS_LOSS: if there is permenant loss of the audio then the mediaplayer should be released (completely stopped)."
},
{
"code": null,
"e": 5142,
"s": 4968,
"text": "To implement the Audio focus in the application same as discussed above invoke the following code in the MainActivity.java file. Comments are added for better understanding."
},
{
"code": null,
"e": 5147,
"s": 5142,
"text": "Java"
},
{
"code": "import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.media.AudioAttributes;import android.media.AudioFocusRequest;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Build;import android.os.Bundle;import android.view.View;import android.widget.Button;import java.io.IOException; @RequiresApi(api = Build.VERSION_CODES.O)public class MainActivity extends AppCompatActivity { // media player instance to playback // the media file from the raw folder MediaPlayer mediaPlayer; // Audio manager instance to manage or // handle the audio interruptions AudioManager audioManager; // Audio attributes instance to set the playback // attributes for the media player instance // these attributes specify what type of media is // to be played and used to callback the audioFocusChangeListener AudioAttributes playbackAttributes; // media player is handled according to the // change in the focus which Android system grants for AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { mediaPlayer.start(); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) { mediaPlayer.pause(); mediaPlayer.seekTo(0); } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { mediaPlayer.release(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the audio system service for // the audioManger instance audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); // initiate the audio playback attributes playbackAttributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build(); // set the playback attributes for the focus requester AudioFocusRequest focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN) .setAudioAttributes(playbackAttributes) .setAcceptsDelayedFocusGain(true) .setOnAudioFocusChangeListener(audioFocusChangeListener) .build(); // request the audio focus and // store it in the int variable final int audioFocusRequest = audioManager.requestAudioFocus(focusRequest); // register all three buttons Button bPlay = findViewById(R.id.playButton); Button bPause = findViewById(R.id.pasueButton); Button bStop = findViewById(R.id.stopButton); // initiate the media player instance with // the media file from the raw folder mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music); // handle the PLAY button to play the audio bPlay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // request the audio focus by the Android system // if the system grants the permission // then start playing the audio file if (audioFocusRequest == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaPlayer.start(); } } }); // handle the PAUSE button to pause the media player bPause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.pause(); } }); // handle the STOP button to stop the media player bStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.stop(); try { // if the mediaplayer is stopped then // it should be again prepared for // next instance of play mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } } }); }}",
"e": 9630,
"s": 5147,
"text": null
},
{
"code": null,
"e": 9850,
"s": 9630,
"text": "Note: When there is no requirement of audio focus, abandonAudioFocusRequest method needs to be called with the AudioManager instance and it requires the parameter AudioFocusRequest focusRequest which needs to be passed."
},
{
"code": null,
"e": 9858,
"s": 9850,
"text": "android"
},
{
"code": null,
"e": 9882,
"s": 9858,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9890,
"s": 9882,
"text": "Android"
},
{
"code": null,
"e": 9895,
"s": 9890,
"text": "Java"
},
{
"code": null,
"e": 9914,
"s": 9895,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9919,
"s": 9914,
"text": "Java"
},
{
"code": null,
"e": 9927,
"s": 9919,
"text": "Android"
}
] |
Industrial Classification of Websites by Machine Learning with hands-on Python | by Ridham Dave | Towards Data Science
|
Hey folks, welcome to my first technical tutorial. In this tutorial, I would like to explain extraction, cleaning and classification of websites into different categories. I will use python environment to run my code for data scraping and use neural network to classify websites.
Text classification is one of the widely used natural language processing(NLP) task in a lot of different areas of Data Science. An efficient text classifier can automatically distinguish the data into categories efficiently with the use NLP algorithms.
Text Classification is an example of supervised machine learning task since a labelled dataset containing text documents and their labels is used for train a classifier.
Some common techniques for text classification are :
Naive Bayes ClassifierLinear ClassifierSupport Vector MachineBagging ModelsBoosting ModelsDeep Neural Networks
Naive Bayes Classifier
Linear Classifier
Support Vector Machine
Bagging Models
Boosting Models
Deep Neural Networks
Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites. Generally, this is done with software that simulates human Web surfing to collect specified bits of information from different websites.
Some techniques that can be used for web scraping are :
Human copy-and-pasteText pattern matchingHTTP programmingHTML parsingDOM parsingVertical aggregationSemantic annotation recognizingComputer vision web-page analysis
Human copy-and-paste
Text pattern matching
HTTP programming
HTML parsing
DOM parsing
Vertical aggregation
Semantic annotation recognizing
Computer vision web-page analysis
In this tutorial, we will try to implement the complete model into three different modules :
Data ScrapingClassification based on keywords for creating a training data setApplying neural network for actual testing model
Data Scraping
Classification based on keywords for creating a training data set
Applying neural network for actual testing model
In this module, I will use Python 3.5 environment to implement my scripts. So follow along for complete reference.
To extract web data many different packages are available, but in this tutorial I will use requests.
import requestsurl='https://medium.com/'try: page = requests.get(url) #to extract page from website html_code = page.content #to extract html code from pageexcept Exception as e: print(e)
In the above code, the requests.get() method will request the page from website using https protocol and load the page into the object “page”. The next line of code will move the HTML code to String html_code. So until now we have extracted the data from websites but it is still in HTML format which is far different than the actual text.
To extract complete text data from the HTML page, we have two highly preferred packages , BeautifulSoup and html2text. Using the html_code string found from the previous step, we can apply any of the following two methods.
from bs4 import BeautifulSouptry: soup = BeautifulSoup(html_code, 'html.parser') #Parse html code texts = soup.findAll(text=True) #find all text text_from_html = ' '.join(texts) #join all textexcept Exception as e: print(e)
In the above snippet, BeautifulSoup package will parse the HTML code and assign the data to soup object. The findall() function finds all visible text from code and return a list of Strings which we store in texts. And finally we join all individual text into a common string using join() function.
import html2texth = html2text.HTML2Text() #Initializing objecth.ignore_links = True #Giving attributes try: text = h.handle(html_code) #handling the HTML code text_from_html=text.replace("\n"," ") #replacing next line charexcept Exception as e: print(e)
In this alternate block, we use package html2text to parse the string and directly get the text from the HTML code. Also we need to replace blank lines with spaces and finally find text_from_html.
Similarly we can use a loop on some 1000+ urls and extract data from those sites as well and store them in a csv(Comma Separated File) format, which we can further use in the classification module.
For any machine learning algorithm, we need some training set and test set for training the model and testing the accuracy of that model. Hence to create the set of data for the model, we already have the text from different websites, we will just classify them according to the keywords, and then apply the results in the next module.
In this tutorial, we are going to classify websites into three categories namely:
Technology, Office, & Education products website(Class_1)Consumer products website(Class_2)Industrial Tools and Hardware products website(Class_3)
Technology, Office, & Education products website(Class_1)
Consumer products website(Class_2)
Industrial Tools and Hardware products website(Class_3)
The approach here is that we will have certain keywords belonging to the particular category, and we will match those keywords with the text and find the class with the maximum Matching_value.
Matching_value = (Number of keywords matched with one industry)/(Total number of keywords matched)
So accordingly we have a list of keywords for the individual categories as follows:
Class_1_keywords = ['Office', 'School', 'phone', 'Technology', 'Electronics', 'Cell', 'Business', 'Education', 'Classroom']Class_1_keywords = ['Restaurant', 'Hospitality', 'Tub', 'Drain', 'Pool', 'Filtration', 'Floor', 'Restroom', 'Consumer', 'Care', 'Bags', 'Disposables']Class_3_keywords = ['Pull', 'Lifts', 'Pneumatic', 'Emergency', 'Finishing', 'Hydraulic', 'Lockout', 'Towers', 'Drywall', 'Tools', 'Packaging', 'Measure', 'Tag ']keywords=Class_1_keywords + Class_2_keywords + Class_3_keywords
Now, we will use KeywordProcessor to find keywords inside the text recieved from the the urls.
KeywordProcessor is available in flashtext package on pypi.
from flashtext.keyword import KeywordProcessorkp0=KeywordProcessor()for word in keywords: kp0.add_keyword(word)kp1=KeywordProcessor()for word in Class_1_keywords: kp1.add_keyword(word)kp2=KeywordProcessor()for word in Class_2_keywords: kp2.add_keyword(word)kp3=KeywordProcessor()for word in Class_3_keywords: kp3.add_keyword(word)
In the above code, we will load KeywordProcessor objects with the keywords which we will use further for finding the matching keywords.
To find percentage value of Matching_value we define a function percentage as follows:
def percentage1(dum0,dumx): try: ans=float(dumx)/float(dum0) ans=ans*100 except: return 0 else: return ans
We will now use extract_keywords(string) method to find keywords present in the text. And we will find length of that list to find the number of matching keywords in the text. The following function will find the percentage and the class with maximum percentage is selected.
def find_class: x=str(text_from_html) y0 = len(kp0.extract_keywords(x)) y1 = len(kp1.extract_keywords(x)) y2 = len(kp2.extract_keywords(x)) y3 = len(kp3.extract_keywords(x)) Total_matches=y0 per1 = float(percentage1(y0,y1)) per2 = float(percentage1(y0,y2)) per3 = float(percentage1(y0,y3)) if y0==0: Category='None' else: if per1>=per2 and per1>=per3: Category='Class_1' elif per2>=per3 and per2>=per1: Category='Class_2' elif per3>=per1 and per3>=per2: Category='Class_3' return Category
Using a loop on the above function, we can find the category of all websites based on the keywords. We will save the classified data into a file Data.csv which we will use further. So now we have our Data Set ready for applying neural network for classification.
In the following implementation, we will create a neural network from scratch and will use NLTK word tokenizer for preprocessing. First we need to import our dataset obtained from the above steps and load it into an list.
import pandas as pddata=pd.read_csv('Data.csv')data = data[pd.notnull(data['tokenized_source'])]data=data[data.Category != 'None']
The above code will load and clean the classified data. The NULL values will be removed.
The following code will create a dictionary of DATA against its class.
for index,row in data.iterrows(): train_data.append({"class":row["Category"], "sentence":row["text"]})
For applying neural network, we need to convert the Language Words into mathematical notations, which will be used for calculations. We will form a list of all the words across all the strings.
words = []classes = []documents = []ignore_words = ['?']# loop through each sentence in our training datafor pattern in training_data: # tokenize each word in the sentence w = nltk.word_tokenize(pattern['sentence']) # add to our words list words.extend(w) # add to documents in our corpus documents.append((w, pattern['class'])) # add to our classes list if pattern['class'] not in classes: classes.append(pattern['class'])# stem and lower each word and remove duplicateswords = [stemmer.stem(w.lower()) for w in words if w not in ignore_words]words = list(set(words))# remove duplicatesclasses = list(set(classes))print (len(documents), "documents")print (len(classes), "classes", classes)print (len(words), "unique stemmed words", words)
For example, the output will be :
1594 documents3 classes ['Class_1', 'Class_3', 'Class_2']unique stemmed words 40000
Now, we will create a list of tokenized words for the pattern and also create a bag of words by using NLTK Lancaster Stemmer.
from nltk.stem.lancaster import LancasterStemmerstemmer = LancasterStemmer()# create our training datatraining = []output = []# create an empty array for our outputoutput_empty = [0] * len(classes)# training set, bag of words for each sentencefor doc in documents: # initialize our bag of words bag = [] # list of tokenized words for the pattern pattern_words = doc[0] # stem each word pattern_words = [stemmer.stem(word.lower()) for word in pattern_words] # create our bag of words array for w in words: bag.append(1) if w in pattern_words else bag.append(0) training.append(bag) # output is a '0' for each tag and '1' for current tag output_row = list(output_empty) output_row[classes.index(doc[1])] = 1 output.append(output_row)print ("# words", len(words))print ("# classes", len(classes))
Output:
# words 41468# classes 3
Now, we do the final preprocessing on the data and create some functions.
Sigmoid Function
def sigmoid(x): output = 1/(1+np.exp(-x)) return output# convert output of sigmoid function to its derivativedef sigmoid_output_to_derivative(output): return output*(1-output)
Cleaning function
def clean_up_sentence(sentence): # tokenize the pattern sentence_words = nltk.word_tokenize(sentence) # stem each word sentence_words = [stemmer.stem(word.lower()) for word in sentence_words] return sentence_words
Bag Of Words function
def bow(sentence, words, show_details=False): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words bag = [0]*len(words) for s in sentence_words: for i,w in enumerate(words): if w == s: bag[i] = 1 if show_details: print ("found in bag: %s" % w) return(np.array(bag))
The final function which will be used in neural network : Think function
def think(sentence, show_details=False): x = bow(sentence.lower(), words, show_details) if show_details: print ("sentence:", sentence, "\n bow:", x) # input layer is our bag of words l0 = x # matrix multiplication of input and hidden layer l1 = sigmoid(np.dot(l0, synapse_0)) # output layer l2 = sigmoid(np.dot(l1, synapse_1)) return l2
Now we are all set to train our model of Neural Network. We are going to implement it through scratch and will be using Logistic regression into each neuron. With just one layer, but with 50000 epochs, we will be training our model. The complete training example will run on CPU.
def train(X, y, hidden_neurons=10, alpha=1, epochs=50000, dropout=False, dropout_percent=0.5): print ("Training with %s neurons, alpha:%s, dropout:%s %s" % (hidden_neurons, str(alpha), dropout, dropout_percent if dropout else '') ) print ("Input matrix: %sx%s Output matrix: %sx%s" % (len(X),len(X[0]),1, len(classes)) ) np.random.seed(1) last_mean_error = 1 # randomly initialize our weights with mean 0 synapse_0 = 2*np.random.random((len(X[0]), hidden_neurons)) - 1 synapse_1 = 2*np.random.random((hidden_neurons, len(classes))) - 1 prev_synapse_0_weight_update = np.zeros_like(synapse_0) prev_synapse_1_weight_update = np.zeros_like(synapse_1) synapse_0_direction_count = np.zeros_like(synapse_0) synapse_1_direction_count = np.zeros_like(synapse_1) for j in iter(range(epochs+1)): # Feed forward through layers 0, 1, and 2 layer_0 = X layer_1 = sigmoid(np.dot(layer_0, synapse_0)) if(dropout): layer_1 *= np.random.binomial([np.ones((len(X),hidden_neurons))],1-dropout_percent)[0] * (1.0/(1-dropout_percent)) layer_2 = sigmoid(np.dot(layer_1, synapse_1)) # how much did we miss the target value? layer_2_error = y - layer_2 if (j% 10000) == 0 and j > 5000: # if this 10k iteration's error is greater than the last iteration, break out if np.mean(np.abs(layer_2_error)) < last_mean_error: print ("delta after "+str(j)+" iterations:" + str(np.mean(np.abs(layer_2_error))) ) last_mean_error = np.mean(np.abs(layer_2_error)) else: print ("break:", np.mean(np.abs(layer_2_error)), ">", last_mean_error ) break # in what direction is the target value? # were we really sure? if so, don't change too much. layer_2_delta = layer_2_error * sigmoid_output_to_derivative(layer_2) # how much did each l1 value contribute to the l2 error (according to the weights)? layer_1_error = layer_2_delta.dot(synapse_1.T) # in what direction is the target l1? # were we really sure? if so, don't change too much. layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1) synapse_1_weight_update = (layer_1.T.dot(layer_2_delta)) synapse_0_weight_update = (layer_0.T.dot(layer_1_delta)) if(j > 0): synapse_0_direction_count += np.abs(((synapse_0_weight_update > 0)+0) - ((prev_synapse_0_weight_update > 0) + 0)) synapse_1_direction_count += np.abs(((synapse_1_weight_update > 0)+0) - ((prev_synapse_1_weight_update > 0) + 0)) synapse_1 += alpha * synapse_1_weight_update synapse_0 += alpha * synapse_0_weight_update prev_synapse_0_weight_update = synapse_0_weight_update prev_synapse_1_weight_update = synapse_1_weight_update now = datetime.datetime.now() # persist synapses synapse = {'synapse0': synapse_0.tolist(), 'synapse1': synapse_1.tolist(), 'datetime': now.strftime("%Y-%m-%d %H:%M"), 'words': words, 'classes': classes } synapse_file = "synapses.json" with open(folder_path+synapse_file, 'w') as outfile: json.dump(synapse, outfile, indent=4, sort_keys=True) print ("saved synapses to:", synapse_file)
And finally we will train the model :
import timeX = np.array(training)y = np.array(output)start_time = time.time()train(X, y, hidden_neurons=10, alpha=0.1, epochs=50000, dropout=False, dropout_percent=0.2)elapsed_time = time.time() - start_timeprint ("processing time:", elapsed_time, "seconds")
Output :
Training with 10 neurons, alpha:0.1, dropout:False Input matrix: 1594x41468 Output matrix: 1x3delta after 10000 iterations:0.0665105275385delta after 20000 iterations:0.0610711168863delta after 30000 iterations:0.0561908365355delta after 40000 iterations:0.0533465919346delta after 50000 iterations:0.0461560407785saved synapses to: synapses.jsonprocessing time: 33060.51151227951 seconds
As we can see, it took almost 11 hours hours to train the model. And after such an intensive calculations, we are ready to test the data.
The function to test the data :
# probability thresholdERROR_THRESHOLD = 0.2# load our calculated synapse valuessynapse_file = 'synapses.json' with open(synapse_file) as data_file: synapse = json.load(data_file) synapse_0 = np.asarray(synapse['synapse0']) synapse_1 = np.asarray(synapse['synapse1'])def classify(sentence, show_details=False): results = think(sentence, show_details) results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD ] results.sort(key=lambda x: x[1], reverse=True) return_results =[[classes[r[0]],r[1]] for r in results] #print ("\n classification: %s" % ( return_results)) return return_results
Lets test the model with its accuracy :
classify("Switchboards Help KA36200 About Us JavaScript seems to be disabled in your browser You must have JavaScript enabled in your browser to utilize the functionality of this website Help Shopping Cart 0 00 You have no items in your shopping cart My Account My Wishlist My Cart My Quote Log In BD Electrical Worldwide Supply Remanufacturing the past SUSTAINING THE FUTURE Hours and Location Michigan Howell")
Output:
[['Class_3', 0.97663437888614435]]
classify(" New Website Testimonial Policies Parts Catalog Contact Support Forum Documentation Themes WordPress Blog Products Spindle Parts Latest News Kennard Parts Suggest Ideas Legal/Disclaimers WordPress Planet News About CDT Home Latest News Testimonial Products Parts Catalog About CDT History Staff Policies Centrum Legal Disclaimers Contact About CDT Custom Drilling Technologies established in 1990 has been providing superior customer service to the printed circuit board industry for almost 20 years We specialize in Excellon Drilling and Routing Equipment Parts and Service Our staff has over sixty years of combined experience in the design building troubleshooting operation programming")
Output:
[['Class_1', 0.9620297535870017]]
As you can see, we are getting pretty high accuracy on these tests. I have tried this model on different data, and have found pretty higher accuracy.
An accuracy of around 95%+ is considered pretty accurate in this type of model with just one layer. For further classification by different models, we can use Keras or Tensorflow. To decrease the time to train the model, we can use a NVIDIA GPU.
And now we can easily scrape data and classify its category, with the help of Deep Neural Network using Back Propogation .
In the further tutorials, I will try to explain Keras and Tensorflow’s working and hands-on.
Please share your feedback about this tutorial in comment section below or via my LinkedIn page: https://www.linkedin.com/in/ridhamdave/ . Also share your doubts regarding this tutorial.
|
[
{
"code": null,
"e": 327,
"s": 47,
"text": "Hey folks, welcome to my first technical tutorial. In this tutorial, I would like to explain extraction, cleaning and classification of websites into different categories. I will use python environment to run my code for data scraping and use neural network to classify websites."
},
{
"code": null,
"e": 581,
"s": 327,
"text": "Text classification is one of the widely used natural language processing(NLP) task in a lot of different areas of Data Science. An efficient text classifier can automatically distinguish the data into categories efficiently with the use NLP algorithms."
},
{
"code": null,
"e": 751,
"s": 581,
"text": "Text Classification is an example of supervised machine learning task since a labelled dataset containing text documents and their labels is used for train a classifier."
},
{
"code": null,
"e": 804,
"s": 751,
"text": "Some common techniques for text classification are :"
},
{
"code": null,
"e": 915,
"s": 804,
"text": "Naive Bayes ClassifierLinear ClassifierSupport Vector MachineBagging ModelsBoosting ModelsDeep Neural Networks"
},
{
"code": null,
"e": 938,
"s": 915,
"text": "Naive Bayes Classifier"
},
{
"code": null,
"e": 956,
"s": 938,
"text": "Linear Classifier"
},
{
"code": null,
"e": 979,
"s": 956,
"text": "Support Vector Machine"
},
{
"code": null,
"e": 994,
"s": 979,
"text": "Bagging Models"
},
{
"code": null,
"e": 1010,
"s": 994,
"text": "Boosting Models"
},
{
"code": null,
"e": 1031,
"s": 1010,
"text": "Deep Neural Networks"
},
{
"code": null,
"e": 1278,
"s": 1031,
"text": "Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites. Generally, this is done with software that simulates human Web surfing to collect specified bits of information from different websites."
},
{
"code": null,
"e": 1334,
"s": 1278,
"text": "Some techniques that can be used for web scraping are :"
},
{
"code": null,
"e": 1499,
"s": 1334,
"text": "Human copy-and-pasteText pattern matchingHTTP programmingHTML parsingDOM parsingVertical aggregationSemantic annotation recognizingComputer vision web-page analysis"
},
{
"code": null,
"e": 1520,
"s": 1499,
"text": "Human copy-and-paste"
},
{
"code": null,
"e": 1542,
"s": 1520,
"text": "Text pattern matching"
},
{
"code": null,
"e": 1559,
"s": 1542,
"text": "HTTP programming"
},
{
"code": null,
"e": 1572,
"s": 1559,
"text": "HTML parsing"
},
{
"code": null,
"e": 1584,
"s": 1572,
"text": "DOM parsing"
},
{
"code": null,
"e": 1605,
"s": 1584,
"text": "Vertical aggregation"
},
{
"code": null,
"e": 1637,
"s": 1605,
"text": "Semantic annotation recognizing"
},
{
"code": null,
"e": 1671,
"s": 1637,
"text": "Computer vision web-page analysis"
},
{
"code": null,
"e": 1764,
"s": 1671,
"text": "In this tutorial, we will try to implement the complete model into three different modules :"
},
{
"code": null,
"e": 1891,
"s": 1764,
"text": "Data ScrapingClassification based on keywords for creating a training data setApplying neural network for actual testing model"
},
{
"code": null,
"e": 1905,
"s": 1891,
"text": "Data Scraping"
},
{
"code": null,
"e": 1971,
"s": 1905,
"text": "Classification based on keywords for creating a training data set"
},
{
"code": null,
"e": 2020,
"s": 1971,
"text": "Applying neural network for actual testing model"
},
{
"code": null,
"e": 2135,
"s": 2020,
"text": "In this module, I will use Python 3.5 environment to implement my scripts. So follow along for complete reference."
},
{
"code": null,
"e": 2236,
"s": 2135,
"text": "To extract web data many different packages are available, but in this tutorial I will use requests."
},
{
"code": null,
"e": 2447,
"s": 2236,
"text": "import requestsurl='https://medium.com/'try: page = requests.get(url) #to extract page from website html_code = page.content #to extract html code from pageexcept Exception as e: print(e)"
},
{
"code": null,
"e": 2787,
"s": 2447,
"text": "In the above code, the requests.get() method will request the page from website using https protocol and load the page into the object “page”. The next line of code will move the HTML code to String html_code. So until now we have extracted the data from websites but it is still in HTML format which is far different than the actual text."
},
{
"code": null,
"e": 3010,
"s": 2787,
"text": "To extract complete text data from the HTML page, we have two highly preferred packages , BeautifulSoup and html2text. Using the html_code string found from the previous step, we can apply any of the following two methods."
},
{
"code": null,
"e": 3281,
"s": 3010,
"text": "from bs4 import BeautifulSouptry: soup = BeautifulSoup(html_code, 'html.parser') #Parse html code texts = soup.findAll(text=True) #find all text text_from_html = ' '.join(texts) #join all textexcept Exception as e: print(e)"
},
{
"code": null,
"e": 3580,
"s": 3281,
"text": "In the above snippet, BeautifulSoup package will parse the HTML code and assign the data to soup object. The findall() function finds all visible text from code and return a list of Strings which we store in texts. And finally we join all individual text into a common string using join() function."
},
{
"code": null,
"e": 3891,
"s": 3580,
"text": "import html2texth = html2text.HTML2Text() #Initializing objecth.ignore_links = True #Giving attributes try: text = h.handle(html_code) #handling the HTML code text_from_html=text.replace(\"\\n\",\" \") #replacing next line charexcept Exception as e: print(e)"
},
{
"code": null,
"e": 4088,
"s": 3891,
"text": "In this alternate block, we use package html2text to parse the string and directly get the text from the HTML code. Also we need to replace blank lines with spaces and finally find text_from_html."
},
{
"code": null,
"e": 4286,
"s": 4088,
"text": "Similarly we can use a loop on some 1000+ urls and extract data from those sites as well and store them in a csv(Comma Separated File) format, which we can further use in the classification module."
},
{
"code": null,
"e": 4622,
"s": 4286,
"text": "For any machine learning algorithm, we need some training set and test set for training the model and testing the accuracy of that model. Hence to create the set of data for the model, we already have the text from different websites, we will just classify them according to the keywords, and then apply the results in the next module."
},
{
"code": null,
"e": 4704,
"s": 4622,
"text": "In this tutorial, we are going to classify websites into three categories namely:"
},
{
"code": null,
"e": 4851,
"s": 4704,
"text": "Technology, Office, & Education products website(Class_1)Consumer products website(Class_2)Industrial Tools and Hardware products website(Class_3)"
},
{
"code": null,
"e": 4909,
"s": 4851,
"text": "Technology, Office, & Education products website(Class_1)"
},
{
"code": null,
"e": 4944,
"s": 4909,
"text": "Consumer products website(Class_2)"
},
{
"code": null,
"e": 5000,
"s": 4944,
"text": "Industrial Tools and Hardware products website(Class_3)"
},
{
"code": null,
"e": 5193,
"s": 5000,
"text": "The approach here is that we will have certain keywords belonging to the particular category, and we will match those keywords with the text and find the class with the maximum Matching_value."
},
{
"code": null,
"e": 5292,
"s": 5193,
"text": "Matching_value = (Number of keywords matched with one industry)/(Total number of keywords matched)"
},
{
"code": null,
"e": 5376,
"s": 5292,
"text": "So accordingly we have a list of keywords for the individual categories as follows:"
},
{
"code": null,
"e": 5874,
"s": 5376,
"text": "Class_1_keywords = ['Office', 'School', 'phone', 'Technology', 'Electronics', 'Cell', 'Business', 'Education', 'Classroom']Class_1_keywords = ['Restaurant', 'Hospitality', 'Tub', 'Drain', 'Pool', 'Filtration', 'Floor', 'Restroom', 'Consumer', 'Care', 'Bags', 'Disposables']Class_3_keywords = ['Pull', 'Lifts', 'Pneumatic', 'Emergency', 'Finishing', 'Hydraulic', 'Lockout', 'Towers', 'Drywall', 'Tools', 'Packaging', 'Measure', 'Tag ']keywords=Class_1_keywords + Class_2_keywords + Class_3_keywords"
},
{
"code": null,
"e": 5969,
"s": 5874,
"text": "Now, we will use KeywordProcessor to find keywords inside the text recieved from the the urls."
},
{
"code": null,
"e": 6029,
"s": 5969,
"text": "KeywordProcessor is available in flashtext package on pypi."
},
{
"code": null,
"e": 6372,
"s": 6029,
"text": "from flashtext.keyword import KeywordProcessorkp0=KeywordProcessor()for word in keywords: kp0.add_keyword(word)kp1=KeywordProcessor()for word in Class_1_keywords: kp1.add_keyword(word)kp2=KeywordProcessor()for word in Class_2_keywords: kp2.add_keyword(word)kp3=KeywordProcessor()for word in Class_3_keywords: kp3.add_keyword(word)"
},
{
"code": null,
"e": 6508,
"s": 6372,
"text": "In the above code, we will load KeywordProcessor objects with the keywords which we will use further for finding the matching keywords."
},
{
"code": null,
"e": 6595,
"s": 6508,
"text": "To find percentage value of Matching_value we define a function percentage as follows:"
},
{
"code": null,
"e": 6739,
"s": 6595,
"text": "def percentage1(dum0,dumx): try: ans=float(dumx)/float(dum0) ans=ans*100 except: return 0 else: return ans"
},
{
"code": null,
"e": 7014,
"s": 6739,
"text": "We will now use extract_keywords(string) method to find keywords present in the text. And we will find length of that list to find the number of matching keywords in the text. The following function will find the percentage and the class with maximum percentage is selected."
},
{
"code": null,
"e": 7603,
"s": 7014,
"text": "def find_class: x=str(text_from_html) y0 = len(kp0.extract_keywords(x)) y1 = len(kp1.extract_keywords(x)) y2 = len(kp2.extract_keywords(x)) y3 = len(kp3.extract_keywords(x)) Total_matches=y0 per1 = float(percentage1(y0,y1)) per2 = float(percentage1(y0,y2)) per3 = float(percentage1(y0,y3)) if y0==0: Category='None' else: if per1>=per2 and per1>=per3: Category='Class_1' elif per2>=per3 and per2>=per1: Category='Class_2' elif per3>=per1 and per3>=per2: Category='Class_3' return Category"
},
{
"code": null,
"e": 7866,
"s": 7603,
"text": "Using a loop on the above function, we can find the category of all websites based on the keywords. We will save the classified data into a file Data.csv which we will use further. So now we have our Data Set ready for applying neural network for classification."
},
{
"code": null,
"e": 8088,
"s": 7866,
"text": "In the following implementation, we will create a neural network from scratch and will use NLTK word tokenizer for preprocessing. First we need to import our dataset obtained from the above steps and load it into an list."
},
{
"code": null,
"e": 8219,
"s": 8088,
"text": "import pandas as pddata=pd.read_csv('Data.csv')data = data[pd.notnull(data['tokenized_source'])]data=data[data.Category != 'None']"
},
{
"code": null,
"e": 8308,
"s": 8219,
"text": "The above code will load and clean the classified data. The NULL values will be removed."
},
{
"code": null,
"e": 8379,
"s": 8308,
"text": "The following code will create a dictionary of DATA against its class."
},
{
"code": null,
"e": 8485,
"s": 8379,
"text": "for index,row in data.iterrows(): train_data.append({\"class\":row[\"Category\"], \"sentence\":row[\"text\"]})"
},
{
"code": null,
"e": 8679,
"s": 8485,
"text": "For applying neural network, we need to convert the Language Words into mathematical notations, which will be used for calculations. We will form a list of all the words across all the strings."
},
{
"code": null,
"e": 9450,
"s": 8679,
"text": "words = []classes = []documents = []ignore_words = ['?']# loop through each sentence in our training datafor pattern in training_data: # tokenize each word in the sentence w = nltk.word_tokenize(pattern['sentence']) # add to our words list words.extend(w) # add to documents in our corpus documents.append((w, pattern['class'])) # add to our classes list if pattern['class'] not in classes: classes.append(pattern['class'])# stem and lower each word and remove duplicateswords = [stemmer.stem(w.lower()) for w in words if w not in ignore_words]words = list(set(words))# remove duplicatesclasses = list(set(classes))print (len(documents), \"documents\")print (len(classes), \"classes\", classes)print (len(words), \"unique stemmed words\", words)"
},
{
"code": null,
"e": 9484,
"s": 9450,
"text": "For example, the output will be :"
},
{
"code": null,
"e": 9568,
"s": 9484,
"text": "1594 documents3 classes ['Class_1', 'Class_3', 'Class_2']unique stemmed words 40000"
},
{
"code": null,
"e": 9694,
"s": 9568,
"text": "Now, we will create a list of tokenized words for the pattern and also create a bag of words by using NLTK Lancaster Stemmer."
},
{
"code": null,
"e": 10534,
"s": 9694,
"text": "from nltk.stem.lancaster import LancasterStemmerstemmer = LancasterStemmer()# create our training datatraining = []output = []# create an empty array for our outputoutput_empty = [0] * len(classes)# training set, bag of words for each sentencefor doc in documents: # initialize our bag of words bag = [] # list of tokenized words for the pattern pattern_words = doc[0] # stem each word pattern_words = [stemmer.stem(word.lower()) for word in pattern_words] # create our bag of words array for w in words: bag.append(1) if w in pattern_words else bag.append(0) training.append(bag) # output is a '0' for each tag and '1' for current tag output_row = list(output_empty) output_row[classes.index(doc[1])] = 1 output.append(output_row)print (\"# words\", len(words))print (\"# classes\", len(classes))"
},
{
"code": null,
"e": 10542,
"s": 10534,
"text": "Output:"
},
{
"code": null,
"e": 10567,
"s": 10542,
"text": "# words 41468# classes 3"
},
{
"code": null,
"e": 10641,
"s": 10567,
"text": "Now, we do the final preprocessing on the data and create some functions."
},
{
"code": null,
"e": 10658,
"s": 10641,
"text": "Sigmoid Function"
},
{
"code": null,
"e": 10843,
"s": 10658,
"text": "def sigmoid(x): output = 1/(1+np.exp(-x)) return output# convert output of sigmoid function to its derivativedef sigmoid_output_to_derivative(output): return output*(1-output)"
},
{
"code": null,
"e": 10861,
"s": 10843,
"text": "Cleaning function"
},
{
"code": null,
"e": 11090,
"s": 10861,
"text": "def clean_up_sentence(sentence): # tokenize the pattern sentence_words = nltk.word_tokenize(sentence) # stem each word sentence_words = [stemmer.stem(word.lower()) for word in sentence_words] return sentence_words"
},
{
"code": null,
"e": 11112,
"s": 11090,
"text": "Bag Of Words function"
},
{
"code": null,
"e": 11496,
"s": 11112,
"text": "def bow(sentence, words, show_details=False): # tokenize the pattern sentence_words = clean_up_sentence(sentence) # bag of words bag = [0]*len(words) for s in sentence_words: for i,w in enumerate(words): if w == s: bag[i] = 1 if show_details: print (\"found in bag: %s\" % w) return(np.array(bag))"
},
{
"code": null,
"e": 11569,
"s": 11496,
"text": "The final function which will be used in neural network : Think function"
},
{
"code": null,
"e": 11940,
"s": 11569,
"text": "def think(sentence, show_details=False): x = bow(sentence.lower(), words, show_details) if show_details: print (\"sentence:\", sentence, \"\\n bow:\", x) # input layer is our bag of words l0 = x # matrix multiplication of input and hidden layer l1 = sigmoid(np.dot(l0, synapse_0)) # output layer l2 = sigmoid(np.dot(l1, synapse_1)) return l2"
},
{
"code": null,
"e": 12220,
"s": 11940,
"text": "Now we are all set to train our model of Neural Network. We are going to implement it through scratch and will be using Logistic regression into each neuron. With just one layer, but with 50000 epochs, we will be training our model. The complete training example will run on CPU."
},
{
"code": null,
"e": 15611,
"s": 12220,
"text": "def train(X, y, hidden_neurons=10, alpha=1, epochs=50000, dropout=False, dropout_percent=0.5): print (\"Training with %s neurons, alpha:%s, dropout:%s %s\" % (hidden_neurons, str(alpha), dropout, dropout_percent if dropout else '') ) print (\"Input matrix: %sx%s Output matrix: %sx%s\" % (len(X),len(X[0]),1, len(classes)) ) np.random.seed(1) last_mean_error = 1 # randomly initialize our weights with mean 0 synapse_0 = 2*np.random.random((len(X[0]), hidden_neurons)) - 1 synapse_1 = 2*np.random.random((hidden_neurons, len(classes))) - 1 prev_synapse_0_weight_update = np.zeros_like(synapse_0) prev_synapse_1_weight_update = np.zeros_like(synapse_1) synapse_0_direction_count = np.zeros_like(synapse_0) synapse_1_direction_count = np.zeros_like(synapse_1) for j in iter(range(epochs+1)): # Feed forward through layers 0, 1, and 2 layer_0 = X layer_1 = sigmoid(np.dot(layer_0, synapse_0)) if(dropout): layer_1 *= np.random.binomial([np.ones((len(X),hidden_neurons))],1-dropout_percent)[0] * (1.0/(1-dropout_percent)) layer_2 = sigmoid(np.dot(layer_1, synapse_1)) # how much did we miss the target value? layer_2_error = y - layer_2 if (j% 10000) == 0 and j > 5000: # if this 10k iteration's error is greater than the last iteration, break out if np.mean(np.abs(layer_2_error)) < last_mean_error: print (\"delta after \"+str(j)+\" iterations:\" + str(np.mean(np.abs(layer_2_error))) ) last_mean_error = np.mean(np.abs(layer_2_error)) else: print (\"break:\", np.mean(np.abs(layer_2_error)), \">\", last_mean_error ) break # in what direction is the target value? # were we really sure? if so, don't change too much. layer_2_delta = layer_2_error * sigmoid_output_to_derivative(layer_2) # how much did each l1 value contribute to the l2 error (according to the weights)? layer_1_error = layer_2_delta.dot(synapse_1.T) # in what direction is the target l1? # were we really sure? if so, don't change too much. layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1) synapse_1_weight_update = (layer_1.T.dot(layer_2_delta)) synapse_0_weight_update = (layer_0.T.dot(layer_1_delta)) if(j > 0): synapse_0_direction_count += np.abs(((synapse_0_weight_update > 0)+0) - ((prev_synapse_0_weight_update > 0) + 0)) synapse_1_direction_count += np.abs(((synapse_1_weight_update > 0)+0) - ((prev_synapse_1_weight_update > 0) + 0)) synapse_1 += alpha * synapse_1_weight_update synapse_0 += alpha * synapse_0_weight_update prev_synapse_0_weight_update = synapse_0_weight_update prev_synapse_1_weight_update = synapse_1_weight_update now = datetime.datetime.now() # persist synapses synapse = {'synapse0': synapse_0.tolist(), 'synapse1': synapse_1.tolist(), 'datetime': now.strftime(\"%Y-%m-%d %H:%M\"), 'words': words, 'classes': classes } synapse_file = \"synapses.json\" with open(folder_path+synapse_file, 'w') as outfile: json.dump(synapse, outfile, indent=4, sort_keys=True) print (\"saved synapses to:\", synapse_file)"
},
{
"code": null,
"e": 15649,
"s": 15611,
"text": "And finally we will train the model :"
},
{
"code": null,
"e": 15908,
"s": 15649,
"text": "import timeX = np.array(training)y = np.array(output)start_time = time.time()train(X, y, hidden_neurons=10, alpha=0.1, epochs=50000, dropout=False, dropout_percent=0.2)elapsed_time = time.time() - start_timeprint (\"processing time:\", elapsed_time, \"seconds\")"
},
{
"code": null,
"e": 15917,
"s": 15908,
"text": "Output :"
},
{
"code": null,
"e": 16306,
"s": 15917,
"text": "Training with 10 neurons, alpha:0.1, dropout:False Input matrix: 1594x41468 Output matrix: 1x3delta after 10000 iterations:0.0665105275385delta after 20000 iterations:0.0610711168863delta after 30000 iterations:0.0561908365355delta after 40000 iterations:0.0533465919346delta after 50000 iterations:0.0461560407785saved synapses to: synapses.jsonprocessing time: 33060.51151227951 seconds"
},
{
"code": null,
"e": 16444,
"s": 16306,
"text": "As we can see, it took almost 11 hours hours to train the model. And after such an intensive calculations, we are ready to test the data."
},
{
"code": null,
"e": 16476,
"s": 16444,
"text": "The function to test the data :"
},
{
"code": null,
"e": 17107,
"s": 16476,
"text": "# probability thresholdERROR_THRESHOLD = 0.2# load our calculated synapse valuessynapse_file = 'synapses.json' with open(synapse_file) as data_file: synapse = json.load(data_file) synapse_0 = np.asarray(synapse['synapse0']) synapse_1 = np.asarray(synapse['synapse1'])def classify(sentence, show_details=False): results = think(sentence, show_details) results = [[i,r] for i,r in enumerate(results) if r>ERROR_THRESHOLD ] results.sort(key=lambda x: x[1], reverse=True) return_results =[[classes[r[0]],r[1]] for r in results] #print (\"\\n classification: %s\" % ( return_results)) return return_results"
},
{
"code": null,
"e": 17147,
"s": 17107,
"text": "Lets test the model with its accuracy :"
},
{
"code": null,
"e": 17560,
"s": 17147,
"text": "classify(\"Switchboards Help KA36200 About Us JavaScript seems to be disabled in your browser You must have JavaScript enabled in your browser to utilize the functionality of this website Help Shopping Cart 0 00 You have no items in your shopping cart My Account My Wishlist My Cart My Quote Log In BD Electrical Worldwide Supply Remanufacturing the past SUSTAINING THE FUTURE Hours and Location Michigan Howell\")"
},
{
"code": null,
"e": 17568,
"s": 17560,
"text": "Output:"
},
{
"code": null,
"e": 17603,
"s": 17568,
"text": "[['Class_3', 0.97663437888614435]]"
},
{
"code": null,
"e": 18306,
"s": 17603,
"text": "classify(\" New Website Testimonial Policies Parts Catalog Contact Support Forum Documentation Themes WordPress Blog Products Spindle Parts Latest News Kennard Parts Suggest Ideas Legal/Disclaimers WordPress Planet News About CDT Home Latest News Testimonial Products Parts Catalog About CDT History Staff Policies Centrum Legal Disclaimers Contact About CDT Custom Drilling Technologies established in 1990 has been providing superior customer service to the printed circuit board industry for almost 20 years We specialize in Excellon Drilling and Routing Equipment Parts and Service Our staff has over sixty years of combined experience in the design building troubleshooting operation programming\")"
},
{
"code": null,
"e": 18314,
"s": 18306,
"text": "Output:"
},
{
"code": null,
"e": 18348,
"s": 18314,
"text": "[['Class_1', 0.9620297535870017]]"
},
{
"code": null,
"e": 18498,
"s": 18348,
"text": "As you can see, we are getting pretty high accuracy on these tests. I have tried this model on different data, and have found pretty higher accuracy."
},
{
"code": null,
"e": 18744,
"s": 18498,
"text": "An accuracy of around 95%+ is considered pretty accurate in this type of model with just one layer. For further classification by different models, we can use Keras or Tensorflow. To decrease the time to train the model, we can use a NVIDIA GPU."
},
{
"code": null,
"e": 18867,
"s": 18744,
"text": "And now we can easily scrape data and classify its category, with the help of Deep Neural Network using Back Propogation ."
},
{
"code": null,
"e": 18960,
"s": 18867,
"text": "In the further tutorials, I will try to explain Keras and Tensorflow’s working and hands-on."
}
] |
How I developed my Web App for Data Visualization with Python | by Papa Moryba Kouate | Towards Data Science
|
Introduction
I am not a web developer, but as a data analyst I think it is very useful to have a web application for data visualization where you can deploy your data and show the world your results. So, I decided to develop my own data dashboard in which I will upload my future results. You can see it here. For a better visualization of graphs I suggest you to look my Web App with your PC not with your smartphone.
In this article, I’d like to give you some inputs to create your own web app for data visualization.
For what concerns the techniques to develop it, the only requirement is to know the markup language HTML and the programming language Python.
You need not know CSS or JavaScript. In fact, to develop my web app I used Flask as a web framework and Bootstrap as a front-end framework.
If you need some suggestions for structuring your repository, you can take as an example my repository on GitHub.
During this article, I will focus on all the steps you need to deploy your Web app.
For the deployment I used a Linux terminal that I think it is very comfortable for development. If your OS is windows, you can go to this link and see the counterparts commands.
The first thing you have to do when you are in your terminal is to update your Anaconda version. In this link you can find a list of many versions.
Use curl command to download the last version of Anaconda.
curl -O https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
Press Enter until the end. Then, you have to say yes for the license agreement.
When you arrive at the point that you can see below, follow the first instruction and press Enter or in alternative you can follow the third instruction and select a location different from the default location.
Out:
Anaconda3 will now be installed into this location:/home/your_name/anacond - Press ENTER to confirm the location - Press CTRL-C to abort the installation - Or specify a different location below[/home/yor_name/anaconda3]>>>
When the process finished, type yes to confirm the path where Anaconda will be installed. After that, you can activate your installation in the following way.
source ~/.bashrc
In this part you have to create a virtual environment. Before starting, be sure you are into the folder that contains the files of your web app. So use this command to create your environment.
python3 -m venv my_environment
Then you can active it by using this command:
source my_environment/bin/activate
Now you are in your environment. In my personal case to realize my web app I installed flask, pandas, Plotly and gunicorn with the following command:
pip install flask pandas plotly gunicorn
Now, you need to register on the cloud platform Heroku in this link.
Then, install all the command-line tools of Heroku in this way:
curl https://cli-assets.heroku.com/install-ubuntu.sh | sh
Login and apply with this simple command:
heroku login
You have to insert the username and the password of your Heroku profile.
The next step is to create a file which aim is to tell Heroku what to do when you are starting your web app. In my file I have put the following state:
web gunigorn app:app
Then, specify the libraries that are going to be needed. So, you have to put all the information in a file called requirements.txt that permit Heroku to know where to look. The command is:
pip freeze > requirements.txt
Now we have to initialize the repository:
git init .git add .git commit -m 'first commit'
You can make the configuration by specifying your email address and your name in this way:
git config user.email “username@something.com”git config user.name “Your Name”
The last step is to create your web app with the following command.
heroku create name_of_your_web_app
Push the files by using this command:
git push heroku master
Every time you want to update your data on your web app, remember to follow the following simple indications.
Go into your environment by using this command:
source my_environment/bin/activate
Then, use these commands to update your Data Dashboard
pip freeze > requirements.txtgit add .git commit -m “make some changes”git push heroku master
This is a simple way that permits you to have your own data dashboard and show your results to everyone in the world and I think that is amazing.
If you meet some problems of creating your web app, feel free to write me privately or in the comments.
We're so pumped to have you!
Already have an account? Sign In
We can also get in touch in my telegram group Data Science for Beginners.
|
[
{
"code": null,
"e": 185,
"s": 172,
"text": "Introduction"
},
{
"code": null,
"e": 591,
"s": 185,
"text": "I am not a web developer, but as a data analyst I think it is very useful to have a web application for data visualization where you can deploy your data and show the world your results. So, I decided to develop my own data dashboard in which I will upload my future results. You can see it here. For a better visualization of graphs I suggest you to look my Web App with your PC not with your smartphone."
},
{
"code": null,
"e": 692,
"s": 591,
"text": "In this article, I’d like to give you some inputs to create your own web app for data visualization."
},
{
"code": null,
"e": 834,
"s": 692,
"text": "For what concerns the techniques to develop it, the only requirement is to know the markup language HTML and the programming language Python."
},
{
"code": null,
"e": 974,
"s": 834,
"text": "You need not know CSS or JavaScript. In fact, to develop my web app I used Flask as a web framework and Bootstrap as a front-end framework."
},
{
"code": null,
"e": 1088,
"s": 974,
"text": "If you need some suggestions for structuring your repository, you can take as an example my repository on GitHub."
},
{
"code": null,
"e": 1172,
"s": 1088,
"text": "During this article, I will focus on all the steps you need to deploy your Web app."
},
{
"code": null,
"e": 1350,
"s": 1172,
"text": "For the deployment I used a Linux terminal that I think it is very comfortable for development. If your OS is windows, you can go to this link and see the counterparts commands."
},
{
"code": null,
"e": 1498,
"s": 1350,
"text": "The first thing you have to do when you are in your terminal is to update your Anaconda version. In this link you can find a list of many versions."
},
{
"code": null,
"e": 1557,
"s": 1498,
"text": "Use curl command to download the last version of Anaconda."
},
{
"code": null,
"e": 1633,
"s": 1557,
"text": "curl -O https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh"
},
{
"code": null,
"e": 1713,
"s": 1633,
"text": "Press Enter until the end. Then, you have to say yes for the license agreement."
},
{
"code": null,
"e": 1925,
"s": 1713,
"text": "When you arrive at the point that you can see below, follow the first instruction and press Enter or in alternative you can follow the third instruction and select a location different from the default location."
},
{
"code": null,
"e": 1930,
"s": 1925,
"text": "Out:"
},
{
"code": null,
"e": 2156,
"s": 1930,
"text": "Anaconda3 will now be installed into this location:/home/your_name/anacond - Press ENTER to confirm the location - Press CTRL-C to abort the installation - Or specify a different location below[/home/yor_name/anaconda3]>>>"
},
{
"code": null,
"e": 2315,
"s": 2156,
"text": "When the process finished, type yes to confirm the path where Anaconda will be installed. After that, you can activate your installation in the following way."
},
{
"code": null,
"e": 2332,
"s": 2315,
"text": "source ~/.bashrc"
},
{
"code": null,
"e": 2525,
"s": 2332,
"text": "In this part you have to create a virtual environment. Before starting, be sure you are into the folder that contains the files of your web app. So use this command to create your environment."
},
{
"code": null,
"e": 2556,
"s": 2525,
"text": "python3 -m venv my_environment"
},
{
"code": null,
"e": 2602,
"s": 2556,
"text": "Then you can active it by using this command:"
},
{
"code": null,
"e": 2637,
"s": 2602,
"text": "source my_environment/bin/activate"
},
{
"code": null,
"e": 2787,
"s": 2637,
"text": "Now you are in your environment. In my personal case to realize my web app I installed flask, pandas, Plotly and gunicorn with the following command:"
},
{
"code": null,
"e": 2828,
"s": 2787,
"text": "pip install flask pandas plotly gunicorn"
},
{
"code": null,
"e": 2897,
"s": 2828,
"text": "Now, you need to register on the cloud platform Heroku in this link."
},
{
"code": null,
"e": 2961,
"s": 2897,
"text": "Then, install all the command-line tools of Heroku in this way:"
},
{
"code": null,
"e": 3019,
"s": 2961,
"text": "curl https://cli-assets.heroku.com/install-ubuntu.sh | sh"
},
{
"code": null,
"e": 3061,
"s": 3019,
"text": "Login and apply with this simple command:"
},
{
"code": null,
"e": 3074,
"s": 3061,
"text": "heroku login"
},
{
"code": null,
"e": 3147,
"s": 3074,
"text": "You have to insert the username and the password of your Heroku profile."
},
{
"code": null,
"e": 3299,
"s": 3147,
"text": "The next step is to create a file which aim is to tell Heroku what to do when you are starting your web app. In my file I have put the following state:"
},
{
"code": null,
"e": 3320,
"s": 3299,
"text": "web gunigorn app:app"
},
{
"code": null,
"e": 3509,
"s": 3320,
"text": "Then, specify the libraries that are going to be needed. So, you have to put all the information in a file called requirements.txt that permit Heroku to know where to look. The command is:"
},
{
"code": null,
"e": 3539,
"s": 3509,
"text": "pip freeze > requirements.txt"
},
{
"code": null,
"e": 3581,
"s": 3539,
"text": "Now we have to initialize the repository:"
},
{
"code": null,
"e": 3629,
"s": 3581,
"text": "git init .git add .git commit -m 'first commit'"
},
{
"code": null,
"e": 3720,
"s": 3629,
"text": "You can make the configuration by specifying your email address and your name in this way:"
},
{
"code": null,
"e": 3799,
"s": 3720,
"text": "git config user.email “username@something.com”git config user.name “Your Name”"
},
{
"code": null,
"e": 3867,
"s": 3799,
"text": "The last step is to create your web app with the following command."
},
{
"code": null,
"e": 3902,
"s": 3867,
"text": "heroku create name_of_your_web_app"
},
{
"code": null,
"e": 3940,
"s": 3902,
"text": "Push the files by using this command:"
},
{
"code": null,
"e": 3963,
"s": 3940,
"text": "git push heroku master"
},
{
"code": null,
"e": 4073,
"s": 3963,
"text": "Every time you want to update your data on your web app, remember to follow the following simple indications."
},
{
"code": null,
"e": 4121,
"s": 4073,
"text": "Go into your environment by using this command:"
},
{
"code": null,
"e": 4156,
"s": 4121,
"text": "source my_environment/bin/activate"
},
{
"code": null,
"e": 4211,
"s": 4156,
"text": "Then, use these commands to update your Data Dashboard"
},
{
"code": null,
"e": 4305,
"s": 4211,
"text": "pip freeze > requirements.txtgit add .git commit -m “make some changes”git push heroku master"
},
{
"code": null,
"e": 4451,
"s": 4305,
"text": "This is a simple way that permits you to have your own data dashboard and show your results to everyone in the world and I think that is amazing."
},
{
"code": null,
"e": 4555,
"s": 4451,
"text": "If you meet some problems of creating your web app, feel free to write me privately or in the comments."
},
{
"code": null,
"e": 4584,
"s": 4555,
"text": "We're so pumped to have you!"
},
{
"code": null,
"e": 4619,
"s": 4584,
"text": "\nAlready have an account? Sign In\n"
}
] |
Python Pandas - Series
|
Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called index.
A pandas Series can be created using the following constructor −
pandas.Series( data, index, dtype, copy)
The parameters of the constructor are as follows −
data
data takes various forms like ndarray, list, constants
index
Index values must be unique and hashable, same length as data. Default np.arrange(n) if no index is passed.
dtype
dtype is for data type. If None, data type will be inferred
copy
Copy data. Default False
A series can be created using various inputs like −
Array
Dict
Scalar value or constant
A basic series, which can be created is an Empty Series.
#import the pandas library and aliasing as pd
import pandas as pd
s = pd.Series()
print s
Its output is as follows −
Series([], dtype: float64)
If data is an ndarray, then index passed must be of the same length. If no index is passed, then by default index will be range(n) where n is array length, i.e., [0,1,2,3.... range(len(array))-1].
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data)
print s
Its output is as follows −
0 a
1 b
2 c
3 d
dtype: object
We did not pass any index, so by default, it assigned the indexes ranging from 0 to len(data)-1, i.e., 0 to 3.
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print s
Its output is as follows −
100 a
101 b
102 c
103 d
dtype: object
We passed the index values here. Now we can see the customized indexed values in the output.
A dict can be passed as input and if no index is specified, then the dictionary keys are taken in a sorted order to construct index. If index is passed, the values in data corresponding to the labels in the index will be pulled out.
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
print s
Its output is as follows −
a 0.0
b 1.0
c 2.0
dtype: float64
Observe − Dictionary keys are used to construct index.
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print s
Its output is as follows −
b 1.0
c 2.0
d NaN
a 0.0
dtype: float64
Observe − Index order is persisted and the missing element is filled with NaN (Not a
Number).
If data is a scalar value, an index must be provided. The value will be repeated to match
the length of index
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
s = pd.Series(5, index=[0, 1, 2, 3])
print s
Its output is as follows −
0 5
1 5
2 5
3 5
dtype: int64
Data in the series can be accessed similar to that in an ndarray.
Retrieve the first element. As we already know, the counting starts from zero for the array,
which means the first element is stored at zeroth position and so on.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#retrieve the first element
print s[0]
Its output is as follows −
1
Retrieve the first three elements in the Series. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index)
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#retrieve the first three element
print s[:3]
Its output is as follows −
a 1
b 2
c 3
dtype: int64
Retrieve the last three elements.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#retrieve the last three element
print s[-3:]
Its output is as follows −
c 3
d 4
e 5
dtype: int64
A Series is like a fixed-size dict in that you can get and set values by index label.
Retrieve a single element using index label value.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#retrieve a single element
print s['a']
Its output is as follows −
1
Retrieve multiple elements using a list of index label values.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#retrieve multiple elements
print s[['a','c','d']]
Its output is as follows −
a 1
c 3
d 4
dtype: int64
If a label is not contained, an exception is raised.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
#retrieve multiple elements
print s['f']
Its output is as follows −
...
KeyError: 'f'
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": 2616,
"s": 2443,
"text": "Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float, python objects, etc.). The axis labels are collectively called index."
},
{
"code": null,
"e": 2681,
"s": 2616,
"text": "A pandas Series can be created using the following constructor −"
},
{
"code": null,
"e": 2723,
"s": 2681,
"text": "pandas.Series( data, index, dtype, copy)\n"
},
{
"code": null,
"e": 2774,
"s": 2723,
"text": "The parameters of the constructor are as follows −"
},
{
"code": null,
"e": 2779,
"s": 2774,
"text": "data"
},
{
"code": null,
"e": 2834,
"s": 2779,
"text": "data takes various forms like ndarray, list, constants"
},
{
"code": null,
"e": 2840,
"s": 2834,
"text": "index"
},
{
"code": null,
"e": 2948,
"s": 2840,
"text": "Index values must be unique and hashable, same length as data. Default np.arrange(n) if no index is passed."
},
{
"code": null,
"e": 2954,
"s": 2948,
"text": "dtype"
},
{
"code": null,
"e": 3014,
"s": 2954,
"text": "dtype is for data type. If None, data type will be inferred"
},
{
"code": null,
"e": 3019,
"s": 3014,
"text": "copy"
},
{
"code": null,
"e": 3044,
"s": 3019,
"text": "Copy data. Default False"
},
{
"code": null,
"e": 3096,
"s": 3044,
"text": "A series can be created using various inputs like −"
},
{
"code": null,
"e": 3102,
"s": 3096,
"text": "Array"
},
{
"code": null,
"e": 3107,
"s": 3102,
"text": "Dict"
},
{
"code": null,
"e": 3132,
"s": 3107,
"text": "Scalar value or constant"
},
{
"code": null,
"e": 3189,
"s": 3132,
"text": "A basic series, which can be created is an Empty Series."
},
{
"code": null,
"e": 3279,
"s": 3189,
"text": "#import the pandas library and aliasing as pd\nimport pandas as pd\ns = pd.Series()\nprint s"
},
{
"code": null,
"e": 3306,
"s": 3279,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3334,
"s": 3306,
"text": "Series([], dtype: float64)\n"
},
{
"code": null,
"e": 3531,
"s": 3334,
"text": "If data is an ndarray, then index passed must be of the same length. If no index is passed, then by default index will be range(n) where n is array length, i.e., [0,1,2,3.... range(len(array))-1]."
},
{
"code": null,
"e": 3679,
"s": 3531,
"text": "#import the pandas library and aliasing as pd\nimport pandas as pd\nimport numpy as np\ndata = np.array(['a','b','c','d'])\ns = pd.Series(data)\nprint s"
},
{
"code": null,
"e": 3706,
"s": 3679,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3745,
"s": 3706,
"text": "0 a\n1 b\n2 c\n3 d\ndtype: object\n"
},
{
"code": null,
"e": 3856,
"s": 3745,
"text": "We did not pass any index, so by default, it assigned the indexes ranging from 0 to len(data)-1, i.e., 0 to 3."
},
{
"code": null,
"e": 4028,
"s": 3856,
"text": "#import the pandas library and aliasing as pd\nimport pandas as pd\nimport numpy as np\ndata = np.array(['a','b','c','d'])\ns = pd.Series(data,index=[100,101,102,103])\nprint s"
},
{
"code": null,
"e": 4055,
"s": 4028,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4098,
"s": 4055,
"text": "100 a\n101 b\n102 c\n103 d\ndtype: object\n"
},
{
"code": null,
"e": 4191,
"s": 4098,
"text": "We passed the index values here. Now we can see the customized indexed values in the output."
},
{
"code": null,
"e": 4424,
"s": 4191,
"text": "A dict can be passed as input and if no index is specified, then the dictionary keys are taken in a sorted order to construct index. If index is passed, the values in data corresponding to the labels in the index will be pulled out."
},
{
"code": null,
"e": 4575,
"s": 4424,
"text": "#import the pandas library and aliasing as pd\nimport pandas as pd\nimport numpy as np\ndata = {'a' : 0., 'b' : 1., 'c' : 2.}\ns = pd.Series(data)\nprint s"
},
{
"code": null,
"e": 4602,
"s": 4575,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4636,
"s": 4602,
"text": "a 0.0\nb 1.0\nc 2.0\ndtype: float64\n"
},
{
"code": null,
"e": 4691,
"s": 4636,
"text": "Observe − Dictionary keys are used to construct index."
},
{
"code": null,
"e": 4866,
"s": 4691,
"text": "#import the pandas library and aliasing as pd\nimport pandas as pd\nimport numpy as np\ndata = {'a' : 0., 'b' : 1., 'c' : 2.}\ns = pd.Series(data,index=['b','c','d','a'])\nprint s"
},
{
"code": null,
"e": 4893,
"s": 4866,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4933,
"s": 4893,
"text": "b 1.0\nc 2.0\nd NaN\na 0.0\ndtype: float64\n"
},
{
"code": null,
"e": 5027,
"s": 4933,
"text": "Observe − Index order is persisted and the missing element is filled with NaN (Not a\nNumber)."
},
{
"code": null,
"e": 5137,
"s": 5027,
"text": "If data is a scalar value, an index must be provided. The value will be repeated to match\nthe length of index"
},
{
"code": null,
"e": 5267,
"s": 5137,
"text": "#import the pandas library and aliasing as pd\nimport pandas as pd\nimport numpy as np\ns = pd.Series(5, index=[0, 1, 2, 3])\nprint s"
},
{
"code": null,
"e": 5294,
"s": 5267,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5328,
"s": 5294,
"text": "0 5\n1 5\n2 5\n3 5\ndtype: int64\n"
},
{
"code": null,
"e": 5394,
"s": 5328,
"text": "Data in the series can be accessed similar to that in an ndarray."
},
{
"code": null,
"e": 5557,
"s": 5394,
"text": "Retrieve the first element. As we already know, the counting starts from zero for the array,\nwhich means the first element is stored at zeroth position and so on."
},
{
"code": null,
"e": 5674,
"s": 5557,
"text": "import pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve the first element\nprint s[0]"
},
{
"code": null,
"e": 5701,
"s": 5674,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5704,
"s": 5701,
"text": "1\n"
},
{
"code": null,
"e": 5951,
"s": 5704,
"text": "Retrieve the first three elements in the Series. If a : is inserted in front of it, all items from that index onwards will be extracted. If two parameters (with : between them) is used, items between the two indexes (not including the stop index)"
},
{
"code": null,
"e": 6075,
"s": 5951,
"text": "import pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve the first three element\nprint s[:3]"
},
{
"code": null,
"e": 6102,
"s": 6075,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6131,
"s": 6102,
"text": "a 1\nb 2\nc 3\ndtype: int64\n"
},
{
"code": null,
"e": 6165,
"s": 6131,
"text": "Retrieve the last three elements."
},
{
"code": null,
"e": 6289,
"s": 6165,
"text": "import pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve the last three element\nprint s[-3:]"
},
{
"code": null,
"e": 6316,
"s": 6289,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6345,
"s": 6316,
"text": "c 3\nd 4\ne 5\ndtype: int64\n"
},
{
"code": null,
"e": 6431,
"s": 6345,
"text": "A Series is like a fixed-size dict in that you can get and set values by index label."
},
{
"code": null,
"e": 6482,
"s": 6431,
"text": "Retrieve a single element using index label value."
},
{
"code": null,
"e": 6600,
"s": 6482,
"text": "import pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve a single element\nprint s['a']"
},
{
"code": null,
"e": 6627,
"s": 6600,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6630,
"s": 6627,
"text": "1\n"
},
{
"code": null,
"e": 6693,
"s": 6630,
"text": "Retrieve multiple elements using a list of index label values."
},
{
"code": null,
"e": 6822,
"s": 6693,
"text": "import pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve multiple elements\nprint s[['a','c','d']]"
},
{
"code": null,
"e": 6849,
"s": 6822,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 6878,
"s": 6849,
"text": "a 1\nc 3\nd 4\ndtype: int64\n"
},
{
"code": null,
"e": 6931,
"s": 6878,
"text": "If a label is not contained, an exception is raised."
},
{
"code": null,
"e": 7050,
"s": 6931,
"text": "import pandas as pd\ns = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])\n\n#retrieve multiple elements\nprint s['f']"
},
{
"code": null,
"e": 7077,
"s": 7050,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 7096,
"s": 7077,
"text": "...\nKeyError: 'f'\n"
},
{
"code": null,
"e": 7133,
"s": 7096,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7149,
"s": 7133,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7182,
"s": 7149,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7201,
"s": 7182,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7236,
"s": 7201,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7258,
"s": 7236,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7292,
"s": 7258,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7320,
"s": 7292,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7355,
"s": 7320,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7369,
"s": 7355,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7402,
"s": 7369,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7419,
"s": 7402,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7426,
"s": 7419,
"text": " Print"
},
{
"code": null,
"e": 7437,
"s": 7426,
"text": " Add Notes"
}
] |
Higher-Order Arrow Functions in JavaScript - GeeksforGeeks
|
11 Oct, 2019
Prerequisite: Arrow Functions
A Higher-Order function is a function that receives a function as an argument otherwise returns function as output. Higher-Order Arrow function implies using arrow functions (in ES6) along with Higher-Order functions.
Needs of Higher Order Arrow Function:
In general way, the programmer instructs on how to perform the function rather than what is needed which increases the length of code and making it error prone.
Whereas in the Higher Order Arrow Functions implementation, the code is much short, concise, succinct, easy to debug and focuses on what is required rather than how to achieve it.
We can directly work with current value instead of accessing it individually using its index (i.e arr[0]).
There is no need to create predefined array and push back the changes.
The mutation of objects can be avoided and maintenance of for loop is not required.
Why to avoid forEach() ?The forEach() function does not return any value so results need to be pushed in a predefined array whereas this is not the case in map() function.
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use forEach() functionvar StudentRollNo = []; Students.forEach(function (Student) { StudentRollNo.push(Student.rollNo);}); // Display rollNo dataconsole.log(StudentRollNo);</script>
Output:
The Higher-Order functions are:
map() Function: It works on a given array like changing/transforming the whole array and then simply return it. It does not break the flow for few conditions. The map() function takes two arguments. The first is callback which gives the current value of the iteration, index of iteration, original array from which the map was called. The other argument is not mandatory which is the value to use as this in the callback. One drawback of using the map() function is that its performance is good only with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() functionvar StudentRollNo = Students.map(function (Student) { return Student.rollNo}); // Display rollNo dataconsole.log(StudentRollNo);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() function with arrow functionsconst StudentRollNo = Students.map(Student => Student.rollNo); // Display Roll no dataconsole.log(StudentRollNo);</script>Output:Note: For more information refer to: Maps in JavaScriptreduce() Function: It is similar to map() function in terms of callback for every element of array. But the difference is that it reduce passes the result of this callback from original array to another. The result is termed as accumulator which can be of anything integer, character, string, object, map etc and should be passed while invoking. The callback now gets the accumulator, current value, index of iteration, whole array.In simple words, the accumulator accumulates all the return values. Its value is the collection of previously returned accumulations.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() functionvar totalPrizes = Students.reduce(function (accumulator, Student) { return accumulator + Student.prizesWon;}, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() function with arrow functionsconst totalPrizes = Students.reduce( (accumulator, Student) => accumulator + Student.prizesWon, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5find() Function: It also works on an array and returns the first array element which satisfies the condition given in the function. It is similar to map() function. Its performance is not much efficient in case of large data sets although it works fine with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function var achievers = Students.find(function (Student) { return Student.prizesWon == 4;}); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function with arrow functionsvar achievers = Students.find( (Student) => Student.prizesWon == 4); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:filter() Function: The filter() function works on an array and returns an array for filtered items implying the length of the array is reduced. It also receives the similar arguments as map but the difference lies in the callback as it needs to return either true or false. If the value returned is true then the element remains in the array otherwise the element is filtered out.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function var achievers = Students.filter(function (Student) { return Student.prizesWon == 4;}); // Display Students who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function with arrow functionsvar achievers = Students.filter( (Student) => Student.prizesWon == 4); // Display Students who won four prizesconsole.log(achievers);</script>Output:
map() Function: It works on a given array like changing/transforming the whole array and then simply return it. It does not break the flow for few conditions. The map() function takes two arguments. The first is callback which gives the current value of the iteration, index of iteration, original array from which the map was called. The other argument is not mandatory which is the value to use as this in the callback. One drawback of using the map() function is that its performance is good only with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() functionvar StudentRollNo = Students.map(function (Student) { return Student.rollNo}); // Display rollNo dataconsole.log(StudentRollNo);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() function with arrow functionsconst StudentRollNo = Students.map(Student => Student.rollNo); // Display Roll no dataconsole.log(StudentRollNo);</script>Output:Note: For more information refer to: Maps in JavaScript
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() functionvar StudentRollNo = Students.map(function (Student) { return Student.rollNo}); // Display rollNo dataconsole.log(StudentRollNo);</script>
Output:
The implementation of above code using arrow functions.
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() function with arrow functionsconst StudentRollNo = Students.map(Student => Student.rollNo); // Display Roll no dataconsole.log(StudentRollNo);</script>
Output:
Note: For more information refer to: Maps in JavaScript
reduce() Function: It is similar to map() function in terms of callback for every element of array. But the difference is that it reduce passes the result of this callback from original array to another. The result is termed as accumulator which can be of anything integer, character, string, object, map etc and should be passed while invoking. The callback now gets the accumulator, current value, index of iteration, whole array.In simple words, the accumulator accumulates all the return values. Its value is the collection of previously returned accumulations.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() functionvar totalPrizes = Students.reduce(function (accumulator, Student) { return accumulator + Student.prizesWon;}, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() function with arrow functionsconst totalPrizes = Students.reduce( (accumulator, Student) => accumulator + Student.prizesWon, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() functionvar totalPrizes = Students.reduce(function (accumulator, Student) { return accumulator + Student.prizesWon;}, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>
Output:
5
The implementation of above code using arrow functions.
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() function with arrow functionsconst totalPrizes = Students.reduce( (accumulator, Student) => accumulator + Student.prizesWon, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>
Output:
5
find() Function: It also works on an array and returns the first array element which satisfies the condition given in the function. It is similar to map() function. Its performance is not much efficient in case of large data sets although it works fine with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function var achievers = Students.find(function (Student) { return Student.prizesWon == 4;}); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function with arrow functionsvar achievers = Students.find( (Student) => Student.prizesWon == 4); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function var achievers = Students.find(function (Student) { return Student.prizesWon == 4;}); // Display only first Student who won four prizesconsole.log(achievers);</script>
Output:
The implementation of above code using arrow functions.
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function with arrow functionsvar achievers = Students.find( (Student) => Student.prizesWon == 4); // Display only first Student who won four prizesconsole.log(achievers);</script>
Output:
filter() Function: The filter() function works on an array and returns an array for filtered items implying the length of the array is reduced. It also receives the similar arguments as map but the difference lies in the callback as it needs to return either true or false. If the value returned is true then the element remains in the array otherwise the element is filtered out.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function var achievers = Students.filter(function (Student) { return Student.prizesWon == 4;}); // Display Students who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function with arrow functionsvar achievers = Students.filter( (Student) => Student.prizesWon == 4); // Display Students who won four prizesconsole.log(achievers);</script>Output:
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function var achievers = Students.filter(function (Student) { return Student.prizesWon == 4;}); // Display Students who won four prizesconsole.log(achievers);</script>
Output:
The implementation of above code using arrow functions.
<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function with arrow functionsvar achievers = Students.filter( (Student) => Student.prizesWon == 4); // Display Students who won four prizesconsole.log(achievers);</script>
Output:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24806,
"s": 24778,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 24836,
"s": 24806,
"text": "Prerequisite: Arrow Functions"
},
{
"code": null,
"e": 25054,
"s": 24836,
"text": "A Higher-Order function is a function that receives a function as an argument otherwise returns function as output. Higher-Order Arrow function implies using arrow functions (in ES6) along with Higher-Order functions."
},
{
"code": null,
"e": 25092,
"s": 25054,
"text": "Needs of Higher Order Arrow Function:"
},
{
"code": null,
"e": 25253,
"s": 25092,
"text": "In general way, the programmer instructs on how to perform the function rather than what is needed which increases the length of code and making it error prone."
},
{
"code": null,
"e": 25433,
"s": 25253,
"text": "Whereas in the Higher Order Arrow Functions implementation, the code is much short, concise, succinct, easy to debug and focuses on what is required rather than how to achieve it."
},
{
"code": null,
"e": 25540,
"s": 25433,
"text": "We can directly work with current value instead of accessing it individually using its index (i.e arr[0])."
},
{
"code": null,
"e": 25611,
"s": 25540,
"text": "There is no need to create predefined array and push back the changes."
},
{
"code": null,
"e": 25695,
"s": 25611,
"text": "The mutation of objects can be avoided and maintenance of for loop is not required."
},
{
"code": null,
"e": 25867,
"s": 25695,
"text": "Why to avoid forEach() ?The forEach() function does not return any value so results need to be pushed in a predefined array whereas this is not the case in map() function."
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use forEach() functionvar StudentRollNo = []; Students.forEach(function (Student) { StudentRollNo.push(Student.rollNo);}); // Display rollNo dataconsole.log(StudentRollNo);</script>",
"e": 26275,
"s": 25867,
"text": null
},
{
"code": null,
"e": 26283,
"s": 26275,
"text": "Output:"
},
{
"code": null,
"e": 26315,
"s": 26283,
"text": "The Higher-Order functions are:"
},
{
"code": null,
"e": 32114,
"s": 26315,
"text": "map() Function: It works on a given array like changing/transforming the whole array and then simply return it. It does not break the flow for few conditions. The map() function takes two arguments. The first is callback which gives the current value of the iteration, index of iteration, original array from which the map was called. The other argument is not mandatory which is the value to use as this in the callback. One drawback of using the map() function is that its performance is good only with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() functionvar StudentRollNo = Students.map(function (Student) { return Student.rollNo}); // Display rollNo dataconsole.log(StudentRollNo);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() function with arrow functionsconst StudentRollNo = Students.map(Student => Student.rollNo); // Display Roll no dataconsole.log(StudentRollNo);</script>Output:Note: For more information refer to: Maps in JavaScriptreduce() Function: It is similar to map() function in terms of callback for every element of array. But the difference is that it reduce passes the result of this callback from original array to another. The result is termed as accumulator which can be of anything integer, character, string, object, map etc and should be passed while invoking. The callback now gets the accumulator, current value, index of iteration, whole array.In simple words, the accumulator accumulates all the return values. Its value is the collection of previously returned accumulations.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() functionvar totalPrizes = Students.reduce(function (accumulator, Student) { return accumulator + Student.prizesWon;}, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() function with arrow functionsconst totalPrizes = Students.reduce( (accumulator, Student) => accumulator + Student.prizesWon, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5find() Function: It also works on an array and returns the first array element which satisfies the condition given in the function. It is similar to map() function. Its performance is not much efficient in case of large data sets although it works fine with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function var achievers = Students.find(function (Student) { return Student.prizesWon == 4;}); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function with arrow functionsvar achievers = Students.find( (Student) => Student.prizesWon == 4); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:filter() Function: The filter() function works on an array and returns an array for filtered items implying the length of the array is reduced. It also receives the similar arguments as map but the difference lies in the callback as it needs to return either true or false. If the value returned is true then the element remains in the array otherwise the element is filtered out.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function var achievers = Students.filter(function (Student) { return Student.prizesWon == 4;}); // Display Students who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function with arrow functionsvar achievers = Students.filter( (Student) => Student.prizesWon == 4); // Display Students who won four prizesconsole.log(achievers);</script>Output:"
},
{
"code": null,
"e": 33528,
"s": 32114,
"text": "map() Function: It works on a given array like changing/transforming the whole array and then simply return it. It does not break the flow for few conditions. The map() function takes two arguments. The first is callback which gives the current value of the iteration, index of iteration, original array from which the map was called. The other argument is not mandatory which is the value to use as this in the callback. One drawback of using the map() function is that its performance is good only with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() functionvar StudentRollNo = Students.map(function (Student) { return Student.rollNo}); // Display rollNo dataconsole.log(StudentRollNo);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() function with arrow functionsconst StudentRollNo = Students.map(Student => Student.rollNo); // Display Roll no dataconsole.log(StudentRollNo);</script>Output:Note: For more information refer to: Maps in JavaScript"
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() functionvar StudentRollNo = Students.map(function (Student) { return Student.rollNo}); // Display rollNo dataconsole.log(StudentRollNo);</script>",
"e": 33909,
"s": 33528,
"text": null
},
{
"code": null,
"e": 33917,
"s": 33909,
"text": "Output:"
},
{
"code": null,
"e": 33973,
"s": 33917,
"text": "The implementation of above code using arrow functions."
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha' }, { rollNo: 22, name: 'Beta' }, { rollNo: 23, name: 'Gamma' }, { rollNo: 24, name: 'Delta' }, { rollNo: 25, name: 'Omega'}]; // Use map() function with arrow functionsconst StudentRollNo = Students.map(Student => Student.rollNo); // Display Roll no dataconsole.log(StudentRollNo);</script>",
"e": 34362,
"s": 33973,
"text": null
},
{
"code": null,
"e": 34370,
"s": 34362,
"text": "Output:"
},
{
"code": null,
"e": 34426,
"s": 34370,
"text": "Note: For more information refer to: Maps in JavaScript"
},
{
"code": null,
"e": 36090,
"s": 34426,
"text": "reduce() Function: It is similar to map() function in terms of callback for every element of array. But the difference is that it reduce passes the result of this callback from original array to another. The result is termed as accumulator which can be of anything integer, character, string, object, map etc and should be passed while invoking. The callback now gets the accumulator, current value, index of iteration, whole array.In simple words, the accumulator accumulates all the return values. Its value is the collection of previously returned accumulations.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() functionvar totalPrizes = Students.reduce(function (accumulator, Student) { return accumulator + Student.prizesWon;}, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() function with arrow functionsconst totalPrizes = Students.reduce( (accumulator, Student) => accumulator + Student.prizesWon, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>Output:5"
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() functionvar totalPrizes = Students.reduce(function (accumulator, Student) { return accumulator + Student.prizesWon;}, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>",
"e": 36601,
"s": 36090,
"text": null
},
{
"code": null,
"e": 36609,
"s": 36601,
"text": "Output:"
},
{
"code": null,
"e": 36611,
"s": 36609,
"text": "5"
},
{
"code": null,
"e": 36667,
"s": 36611,
"text": "The implementation of above code using arrow functions."
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 1 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 0 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using reduce() function with arrow functionsconst totalPrizes = Students.reduce( (accumulator, Student) => accumulator + Student.prizesWon, 0); // Display total number of prizes won by allconsole.log(totalPrizes);</script>",
"e": 37185,
"s": 36667,
"text": null
},
{
"code": null,
"e": 37193,
"s": 37185,
"text": "Output:"
},
{
"code": null,
"e": 37195,
"s": 37193,
"text": "5"
},
{
"code": null,
"e": 38509,
"s": 37195,
"text": "find() Function: It also works on an array and returns the first array element which satisfies the condition given in the function. It is similar to map() function. Its performance is not much efficient in case of large data sets although it works fine with small data sets.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function var achievers = Students.find(function (Student) { return Student.prizesWon == 4;}); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function with arrow functionsvar achievers = Students.find( (Student) => Student.prizesWon == 4); // Display only first Student who won four prizesconsole.log(achievers);</script>Output:"
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function var achievers = Students.find(function (Student) { return Student.prizesWon == 4;}); // Display only first Student who won four prizesconsole.log(achievers);</script>",
"e": 38993,
"s": 38509,
"text": null
},
{
"code": null,
"e": 39001,
"s": 38993,
"text": "Output:"
},
{
"code": null,
"e": 39057,
"s": 39001,
"text": "The implementation of above code using arrow functions."
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using find() function with arrow functionsvar achievers = Students.find( (Student) => Student.prizesWon == 4); // Display only first Student who won four prizesconsole.log(achievers);</script>",
"e": 39545,
"s": 39057,
"text": null
},
{
"code": null,
"e": 39553,
"s": 39545,
"text": "Output:"
},
{
"code": null,
"e": 40963,
"s": 39553,
"text": "filter() Function: The filter() function works on an array and returns an array for filtered items implying the length of the array is reduced. It also receives the similar arguments as map but the difference lies in the callback as it needs to return either true or false. If the value returned is true then the element remains in the array otherwise the element is filtered out.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function var achievers = Students.filter(function (Student) { return Student.prizesWon == 4;}); // Display Students who won four prizesconsole.log(achievers);</script>Output:The implementation of above code using arrow functions.<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function with arrow functionsvar achievers = Students.filter( (Student) => Student.prizesWon == 4); // Display Students who won four prizesconsole.log(achievers);</script>Output:"
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function var achievers = Students.filter(function (Student) { return Student.prizesWon == 4;}); // Display Students who won four prizesconsole.log(achievers);</script>",
"e": 41441,
"s": 40963,
"text": null
},
{
"code": null,
"e": 41449,
"s": 41441,
"text": "Output:"
},
{
"code": null,
"e": 41505,
"s": 41449,
"text": "The implementation of above code using arrow functions."
},
{
"code": "<script>// Data set of studentsvar Students = [ { rollNo: 21, name: 'Alpha', prizesWon: 4 }, { rollNo: 22, name: 'Beta', prizesWon: 3 }, { rollNo: 23, name: 'Gamma', prizesWon: 0 }, { rollNo: 24, name: 'Delta', prizesWon: 4 }, { rollNo: 25, name: 'Omega', prizesWon: 1}]; // Using filter() function with arrow functionsvar achievers = Students.filter( (Student) => Student.prizesWon == 4); // Display Students who won four prizesconsole.log(achievers);</script>",
"e": 41989,
"s": 41505,
"text": null
},
{
"code": null,
"e": 41997,
"s": 41989,
"text": "Output:"
},
{
"code": null,
"e": 42013,
"s": 41997,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 42024,
"s": 42013,
"text": "JavaScript"
},
{
"code": null,
"e": 42041,
"s": 42024,
"text": "Web Technologies"
},
{
"code": null,
"e": 42068,
"s": 42041,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 42166,
"s": 42068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42211,
"s": 42166,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42272,
"s": 42211,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42344,
"s": 42272,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42396,
"s": 42344,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 42442,
"s": 42396,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 42484,
"s": 42442,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 42517,
"s": 42484,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42560,
"s": 42517,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 42622,
"s": 42560,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to remove a column from an R data frame?
|
This can be easily done by using subset function.
> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df
x y z a
1 1 6 11 16
2 2 7 12 17
3 3 8 13 18
4 4 9 14 19
5 5 10 15 20
To remove only one column
> df <- subset (df, select = -x)
> df
y z a
1 6 11 16
2 7 12 17
3 8 13 18
4 9 14 19
5 10 15 20
To remove two columns
> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df <- subset (df, select = -c(x,y))
> df
z a
1 11 16
2 12 17
3 13 18
4 14 19
5 15 20
To remove a range of columns
> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df <- subset (df, select = -c(x:z))
> df
a
1 16
2 17
3 18
4 19
5 20
To remove separate columns
> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)
> df <- subset (df, select = -c(x,z:a))
> df
y
1 6
2 7
3 8
4 9
5 10
|
[
{
"code": null,
"e": 1112,
"s": 1062,
"text": "This can be easily done by using subset function."
},
{
"code": null,
"e": 1241,
"s": 1112,
"text": "> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)\n> df\nx y z a\n1 1 6 11 16\n2 2 7 12 17\n3 3 8 13 18\n4 4 9 14 19\n5 5 10 15 20"
},
{
"code": null,
"e": 1267,
"s": 1241,
"text": "To remove only one column"
},
{
"code": null,
"e": 1362,
"s": 1267,
"text": "> df <- subset (df, select = -x)\n> df\ny z a\n1 6 11 16\n2 7 12 17\n3 8 13 18\n4 9 14 19\n5 10 15 20"
},
{
"code": null,
"e": 1384,
"s": 1362,
"text": "To remove two columns"
},
{
"code": null,
"e": 1523,
"s": 1384,
"text": "> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)\n> df <- subset (df, select = -c(x,y))\n> df\nz a\n1 11 16\n2 12 17\n3 13 18\n4 14 19\n5 15 20"
},
{
"code": null,
"e": 1552,
"s": 1523,
"text": "To remove a range of columns"
},
{
"code": null,
"e": 1674,
"s": 1552,
"text": "> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)\n> df <- subset (df, select = -c(x:z))\n> df\na\n1 16\n2 17\n3 18\n4 19\n5 20"
},
{
"code": null,
"e": 1701,
"s": 1674,
"text": "To remove separate columns"
},
{
"code": null,
"e": 1821,
"s": 1701,
"text": "> df <- data.frame(x=1:5, y=6:10, z=11:15, a=16:20)\n> df <- subset (df, select = -c(x,z:a))\n> df\ny\n1 6\n2 7\n3 8\n4 9\n5 10"
}
] |
Java AWS - How to Send Messages to SQS Queues - onlinetutorialspoint
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how to send messages to SQS Queues using AWS Java SDK.
We can send messages to SQS in 2 different ways that are sending a single message and sending a bunch of messages at a time.
Make sure you have an AWS account and valid credentials to access the resources.
Better you install the AWS CLI on your machine for troubleshooting.
Configure AWS credentials on your local machine.
Java 14
AWS SDK 2.16.29
As part of this example, we are going to send messages to the SQS queue, messages can be sent to the SQS queue in two ways; single message and sending a bulk of messages at a time.
In this previous tutorial, we discussed that there were 2 different queries in AWS SQS that are Standard and FIFO queues and these two have significant differences, hence there also be differences while sending the messages to Standard and FIFO queues.
Add software.amazon.awssdk dependency into your pom.xml.
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>sqs</artifactId>
</dependency>
The Amazon AWS SDK for Java is used to interact with AWS resources from a Java application.
Run the maven clean install command to download the dependencies.
% mvn clean install
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------< AWS_EXample:java-aws-examples >--------------------
[INFO] Building java-aws-examples 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
...
..
Make sure you have an AWS account and valid credentials to access the resources.
Better you install the AWS CLI on your machine for troubleshooting.
Configure AWS credentials on your local machine.
I created a standard queue with a name called My-Sample-Standard-Queue if you haven’t yet created see here.
package com.otp;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;
public class SQS_Example {
public static void main(String[] args) {
String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-Sample-Standard-Queue";
SqsClient sqsClient = SqsClient.builder()
.region(Region.US_WEST_2)
.build();
sendSingleMessage(sqsClient, queue);
sqsClient.close();
}
public static void sendSingleMessage(SqsClient sqsClient, String queueUrl) {
try {
sqsClient.sendMessage(SendMessageRequest.builder()
.queueUrl(queueUrl)
.messageBody("Hello world from Java!")
.delaySeconds(10)
.build());
System.out.println("Message has been sent successfully");
} catch (SqsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
Output:
Message has been sent successfully
Sending batch messages to SQS queue.
package com.otp;
import java.util.*;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;
public class SQS_Example {
public static void main(String[] args) {
SqsClient sqsClient = SqsClient.builder()
.region(Region.US_WEST_2)
.build();
String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-Sample-Standard-Queue"
sendBatchMessages(sqsClient, queue);
sqsClient.close();
}
public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) {
try {
Collection<SendMessageBatchRequestEntry> messages = Arrays.asList(
SendMessageBatchRequestEntry.builder().id("id-1").messageBody("Hello 1").build(),
SendMessageBatchRequestEntry.builder().id("id-2").messageBody("Hello 2").build(),
SendMessageBatchRequestEntry.builder().id("id-3").messageBody("Hello 3").build()
);
SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
.queueUrl(queueUrl)
.entries(messages)
.build();
sqsClient.sendMessageBatch(sendMessageBatchRequest);
System.out.println("Messages has been sent successfully as a batch");
} catch (SqsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
}
}
}
Output:
Messages has been sent successfully as a batch
Now send messages to the FIFO queue, it is as simple as a standard queue but here we need to pass some extra parameters with respect to the FIFO queue properties like message_ group_id and message_duplication_id.
package com.otp;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;
public class SQS_Example {
public static void main(String[] args) {
SqsClient sqsClient = SqsClient.builder()
.region(Region.US_WEST_2)
.build();
String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-FIFO-Queue.fifo";
sendSingleFifoMessage(sqsClient, queue);
sqsClient.close();
}
public static void sendSingleFifoMessage(SqsClient sqsClient, String queueUrl) {
try {
sqsClient.sendMessage(SendMessageRequest.builder()
.queueUrl(queueUrl)
.messageBody("Hello world from Java!")
.messageGroupId("12345")
.messageDeduplicationId("123")
.build());
System.out.println("Message has been sent successfully");
} catch (SqsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
Output:
Message has been sent successfully
package com.otp;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.*;
import java.util.Arrays;
import java.util.Collection;
public class SQS_Example {
public static void main(String[] args) {
SqsClient sqsClient = SqsClient.builder()
.region(Region.US_WEST_2)
.build();
String queue = "https://sqs.us-west-2.amazonaws.com/123456/My-FIFO-Queue.fifo";
sendBatchFIFOMessages(sqsClient, queue);
sqsClient.close();
}
public static void sendBatchFIFOMessages(SqsClient sqsClient, String queueUrl) {
try {
Collection<SendMessageBatchRequestEntry> messages = Arrays.asList(
SendMessageBatchRequestEntry.builder().id("id-1").messageBody("Hello 1")
.messageGroupId("12345").messageDeduplicationId("123").build(),
SendMessageBatchRequestEntry.builder().id("id-2").messageBody("Hello 2")
.messageGroupId("12345").messageDeduplicationId("123").build(),
SendMessageBatchRequestEntry.builder().id("id-3").messageBody("Hello 3").
messageGroupId("12345").messageDeduplicationId("123").build()
);
SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
.queueUrl(queueUrl)
.entries(messages)
.build();
sqsClient.sendMessageBatch(sendMessageBatchRequest);
System.out.println("Messages has been sent successfully as a batch");
} catch (SqsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
}
}
}
Output:
Messages has been sent successfully as a batch
Create SQS Queues
Install/setup AWS
AWS sqs developer guide
Happy Learning 🙂
Java AWS – How to read messages from SQS
Java AWS – How to Create SQS Standard and FIFO Queues
How to install AWS CLI on Windows 10
Python – AWS SAM Lambda Example
How to Copy Local Files to AWS EC2 instance Manually ?
Javascript – How to listObjects from AWS S3
How set AWS Access Keys in Windows or Mac Environment
How to connect AWS EC2 Instance using PuTTY
[Fixed] – Malformed Lambda proxy response – status 502
Spring Boot RabbitMQ Consumer Messages Example
How add files to S3 Bucket using Shell Script
[Fixed] – Error: No changes to deploy. Stack is up to date
Spring Boot Kafka Consume JSON Messages Example
How to push docker image to docker hub ?
How to Send Mail Spring Boot Example
Java AWS – How to read messages from SQS
Java AWS – How to Create SQS Standard and FIFO Queues
How to install AWS CLI on Windows 10
Python – AWS SAM Lambda Example
How to Copy Local Files to AWS EC2 instance Manually ?
Javascript – How to listObjects from AWS S3
How set AWS Access Keys in Windows or Mac Environment
How to connect AWS EC2 Instance using PuTTY
[Fixed] – Malformed Lambda proxy response – status 502
Spring Boot RabbitMQ Consumer Messages Example
How add files to S3 Bucket using Shell Script
[Fixed] – Error: No changes to deploy. Stack is up to date
Spring Boot Kafka Consume JSON Messages Example
How to push docker image to docker hub ?
How to Send Mail Spring Boot Example
Δ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 483,
"s": 398,
"text": "In this tutorial, we will see how to send messages to SQS Queues using AWS Java SDK."
},
{
"code": null,
"e": 608,
"s": 483,
"text": "We can send messages to SQS in 2 different ways that are sending a single message and sending a bunch of messages at a time."
},
{
"code": null,
"e": 689,
"s": 608,
"text": "Make sure you have an AWS account and valid credentials to access the resources."
},
{
"code": null,
"e": 757,
"s": 689,
"text": "Better you install the AWS CLI on your machine for troubleshooting."
},
{
"code": null,
"e": 806,
"s": 757,
"text": "Configure AWS credentials on your local machine."
},
{
"code": null,
"e": 814,
"s": 806,
"text": "Java 14"
},
{
"code": null,
"e": 830,
"s": 814,
"text": "AWS SDK 2.16.29"
},
{
"code": null,
"e": 1011,
"s": 830,
"text": "As part of this example, we are going to send messages to the SQS queue, messages can be sent to the SQS queue in two ways; single message and sending a bulk of messages at a time."
},
{
"code": null,
"e": 1264,
"s": 1011,
"text": "In this previous tutorial, we discussed that there were 2 different queries in AWS SQS that are Standard and FIFO queues and these two have significant differences, hence there also be differences while sending the messages to Standard and FIFO queues."
},
{
"code": null,
"e": 1321,
"s": 1264,
"text": "Add software.amazon.awssdk dependency into your pom.xml."
},
{
"code": null,
"e": 1427,
"s": 1321,
"text": "<dependency>\n <groupId>software.amazon.awssdk</groupId>\n <artifactId>sqs</artifactId>\n</dependency>"
},
{
"code": null,
"e": 1519,
"s": 1427,
"text": "The Amazon AWS SDK for Java is used to interact with AWS resources from a Java application."
},
{
"code": null,
"e": 1585,
"s": 1519,
"text": "Run the maven clean install command to download the dependencies."
},
{
"code": null,
"e": 1868,
"s": 1585,
"text": " % mvn clean install\n[INFO] Scanning for projects...\n[INFO] \n[INFO] -------------------< AWS_EXample:java-aws-examples >--------------------\n[INFO] Building java-aws-examples 1.0-SNAPSHOT\n[INFO] --------------------------------[ jar ]---------------------------------\n[INFO] \n...\n.."
},
{
"code": null,
"e": 1949,
"s": 1868,
"text": "Make sure you have an AWS account and valid credentials to access the resources."
},
{
"code": null,
"e": 2017,
"s": 1949,
"text": "Better you install the AWS CLI on your machine for troubleshooting."
},
{
"code": null,
"e": 2066,
"s": 2017,
"text": "Configure AWS credentials on your local machine."
},
{
"code": null,
"e": 2174,
"s": 2066,
"text": "I created a standard queue with a name called My-Sample-Standard-Queue if you haven’t yet created see here."
},
{
"code": null,
"e": 3255,
"s": 2174,
"text": "package com.otp;\n\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\n\npublic class SQS_Example {\n\n public static void main(String[] args) {\n String queue = \"https://sqs.us-west-2.amazonaws.com/123456/My-Sample-Standard-Queue\";\n SqsClient sqsClient = SqsClient.builder()\n .region(Region.US_WEST_2)\n .build();\n sendSingleMessage(sqsClient, queue);\n sqsClient.close();\n }\n\n public static void sendSingleMessage(SqsClient sqsClient, String queueUrl) {\n try {\n sqsClient.sendMessage(SendMessageRequest.builder()\n .queueUrl(queueUrl)\n .messageBody(\"Hello world from Java!\")\n .delaySeconds(10)\n .build());\n System.out.println(\"Message has been sent successfully\");\n } catch (SqsException e) {\n System.err.println(e.awsErrorDetails().errorMessage());\n System.exit(1);\n }\n }\n}\n"
},
{
"code": null,
"e": 3263,
"s": 3255,
"text": "Output:"
},
{
"code": null,
"e": 3298,
"s": 3263,
"text": "Message has been sent successfully"
},
{
"code": null,
"e": 3335,
"s": 3298,
"text": "Sending batch messages to SQS queue."
},
{
"code": null,
"e": 4858,
"s": 3335,
"text": "package com.otp;\nimport java.util.*;\n\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\n\npublic class SQS_Example {\n\n public static void main(String[] args) {\n SqsClient sqsClient = SqsClient.builder()\n .region(Region.US_WEST_2)\n .build();\n String queue = \"https://sqs.us-west-2.amazonaws.com/123456/My-Sample-Standard-Queue\"\n sendBatchMessages(sqsClient, queue);\n sqsClient.close();\n }\n\n public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) {\n\n try {\n Collection<SendMessageBatchRequestEntry> messages = Arrays.asList(\n SendMessageBatchRequestEntry.builder().id(\"id-1\").messageBody(\"Hello 1\").build(),\n SendMessageBatchRequestEntry.builder().id(\"id-2\").messageBody(\"Hello 2\").build(),\n SendMessageBatchRequestEntry.builder().id(\"id-3\").messageBody(\"Hello 3\").build()\n );\n SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()\n .queueUrl(queueUrl)\n .entries(messages)\n .build();\n sqsClient.sendMessageBatch(sendMessageBatchRequest);\n System.out.println(\"Messages has been sent successfully as a batch\");\n } catch (SqsException e) {\n System.err.println(e.awsErrorDetails().errorMessage());\n }\n }\n}\n"
},
{
"code": null,
"e": 4866,
"s": 4858,
"text": "Output:"
},
{
"code": null,
"e": 4913,
"s": 4866,
"text": "Messages has been sent successfully as a batch"
},
{
"code": null,
"e": 5126,
"s": 4913,
"text": "Now send messages to the FIFO queue, it is as simple as a standard queue but here we need to pass some extra parameters with respect to the FIFO queue properties like message_ group_id and message_duplication_id."
},
{
"code": null,
"e": 6267,
"s": 5126,
"text": "package com.otp;\n\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\n\npublic class SQS_Example {\n\n public static void main(String[] args) {\n SqsClient sqsClient = SqsClient.builder()\n .region(Region.US_WEST_2)\n .build();\n String queue = \"https://sqs.us-west-2.amazonaws.com/123456/My-FIFO-Queue.fifo\";\n sendSingleFifoMessage(sqsClient, queue);\n sqsClient.close();\n }\n\n public static void sendSingleFifoMessage(SqsClient sqsClient, String queueUrl) {\n try {\n sqsClient.sendMessage(SendMessageRequest.builder()\n .queueUrl(queueUrl)\n .messageBody(\"Hello world from Java!\")\n .messageGroupId(\"12345\")\n .messageDeduplicationId(\"123\")\n .build());\n System.out.println(\"Message has been sent successfully\");\n } catch (SqsException e) {\n System.err.println(e.awsErrorDetails().errorMessage());\n System.exit(1);\n }\n }\n}\n"
},
{
"code": null,
"e": 6275,
"s": 6267,
"text": "Output:"
},
{
"code": null,
"e": 6311,
"s": 6275,
"text": "Message has been sent successfully\n"
},
{
"code": null,
"e": 8121,
"s": 6311,
"text": "package com.otp;\n\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.sqs.SqsClient;\nimport software.amazon.awssdk.services.sqs.model.*;\n\nimport java.util.Arrays;\nimport java.util.Collection;\n\npublic class SQS_Example {\n\n public static void main(String[] args) {\n SqsClient sqsClient = SqsClient.builder()\n .region(Region.US_WEST_2)\n .build();\n String queue = \"https://sqs.us-west-2.amazonaws.com/123456/My-FIFO-Queue.fifo\";\n sendBatchFIFOMessages(sqsClient, queue);\n sqsClient.close();\n }\n\n public static void sendBatchFIFOMessages(SqsClient sqsClient, String queueUrl) {\n\n try {\n Collection<SendMessageBatchRequestEntry> messages = Arrays.asList(\n SendMessageBatchRequestEntry.builder().id(\"id-1\").messageBody(\"Hello 1\")\n .messageGroupId(\"12345\").messageDeduplicationId(\"123\").build(),\n SendMessageBatchRequestEntry.builder().id(\"id-2\").messageBody(\"Hello 2\")\n .messageGroupId(\"12345\").messageDeduplicationId(\"123\").build(),\n SendMessageBatchRequestEntry.builder().id(\"id-3\").messageBody(\"Hello 3\").\n messageGroupId(\"12345\").messageDeduplicationId(\"123\").build()\n );\n SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()\n .queueUrl(queueUrl)\n .entries(messages)\n .build();\n sqsClient.sendMessageBatch(sendMessageBatchRequest);\n System.out.println(\"Messages has been sent successfully as a batch\");\n } catch (SqsException e) {\n System.err.println(e.awsErrorDetails().errorMessage());\n }\n }\n}\n"
},
{
"code": null,
"e": 8129,
"s": 8121,
"text": "Output:"
},
{
"code": null,
"e": 8176,
"s": 8129,
"text": "Messages has been sent successfully as a batch"
},
{
"code": null,
"e": 8194,
"s": 8176,
"text": "Create SQS Queues"
},
{
"code": null,
"e": 8212,
"s": 8194,
"text": "Install/setup AWS"
},
{
"code": null,
"e": 8236,
"s": 8212,
"text": "AWS sqs developer guide"
},
{
"code": null,
"e": 8253,
"s": 8236,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 8950,
"s": 8253,
"text": "\nJava AWS – How to read messages from SQS\nJava AWS – How to Create SQS Standard and FIFO Queues\nHow to install AWS CLI on Windows 10\nPython – AWS SAM Lambda Example\nHow to Copy Local Files to AWS EC2 instance Manually ?\nJavascript – How to listObjects from AWS S3\nHow set AWS Access Keys in Windows or Mac Environment\nHow to connect AWS EC2 Instance using PuTTY\n[Fixed] – Malformed Lambda proxy response – status 502\nSpring Boot RabbitMQ Consumer Messages Example\nHow add files to S3 Bucket using Shell Script\n[Fixed] – Error: No changes to deploy. Stack is up to date\nSpring Boot Kafka Consume JSON Messages Example\nHow to push docker image to docker hub ?\nHow to Send Mail Spring Boot Example\n"
},
{
"code": null,
"e": 8991,
"s": 8950,
"text": "Java AWS – How to read messages from SQS"
},
{
"code": null,
"e": 9045,
"s": 8991,
"text": "Java AWS – How to Create SQS Standard and FIFO Queues"
},
{
"code": null,
"e": 9082,
"s": 9045,
"text": "How to install AWS CLI on Windows 10"
},
{
"code": null,
"e": 9114,
"s": 9082,
"text": "Python – AWS SAM Lambda Example"
},
{
"code": null,
"e": 9169,
"s": 9114,
"text": "How to Copy Local Files to AWS EC2 instance Manually ?"
},
{
"code": null,
"e": 9213,
"s": 9169,
"text": "Javascript – How to listObjects from AWS S3"
},
{
"code": null,
"e": 9267,
"s": 9213,
"text": "How set AWS Access Keys in Windows or Mac Environment"
},
{
"code": null,
"e": 9311,
"s": 9267,
"text": "How to connect AWS EC2 Instance using PuTTY"
},
{
"code": null,
"e": 9367,
"s": 9311,
"text": "[Fixed] – Malformed Lambda proxy response – status 502"
},
{
"code": null,
"e": 9414,
"s": 9367,
"text": "Spring Boot RabbitMQ Consumer Messages Example"
},
{
"code": null,
"e": 9460,
"s": 9414,
"text": "How add files to S3 Bucket using Shell Script"
},
{
"code": null,
"e": 9519,
"s": 9460,
"text": "[Fixed] – Error: No changes to deploy. Stack is up to date"
},
{
"code": null,
"e": 9567,
"s": 9519,
"text": "Spring Boot Kafka Consume JSON Messages Example"
},
{
"code": null,
"e": 9608,
"s": 9567,
"text": "How to push docker image to docker hub ?"
},
{
"code": null,
"e": 9645,
"s": 9608,
"text": "How to Send Mail Spring Boot Example"
},
{
"code": null,
"e": 9651,
"s": 9649,
"text": "Δ"
},
{
"code": null,
"e": 9675,
"s": 9651,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 9703,
"s": 9675,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 9732,
"s": 9703,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 9767,
"s": 9732,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 9794,
"s": 9767,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 9821,
"s": 9794,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 9850,
"s": 9821,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 9876,
"s": 9850,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 9902,
"s": 9876,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 9938,
"s": 9902,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 9972,
"s": 9938,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 9998,
"s": 9972,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 10023,
"s": 9998,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 10057,
"s": 10023,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 10092,
"s": 10057,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 10116,
"s": 10092,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 10145,
"s": 10116,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 10177,
"s": 10145,
"text": " Install Apache Kafka on Ubuntu"
}
] |
Factorial | Practice | GeeksforGeeks
|
Given a positive integer, N. Find the factorial of N.
Example 1:
Input:
N = 5
Output:
120
Explanation:
5*4*3*2*1 = 120
Example 2:
Input:
N = 4
Output:
24
Explanation:
4*3*2*1 = 24
Your Task:
You don't need to read input or print anything. Your task is to complete the function factorial() which takes an integer N as input parameters and returns an integer, the factorial of N.
Expected Time Complexity: O(N)
Expected Space Complexity: O(1)
Constraints:
0 <= N <= 18
0
mayank180919991 week ago
long long int factorial(int N){
//code here
long long int fact=1;
for(int i=1;i<=N;i++){
fact=fact*i;
}
return fact;
}
0
purnimasharma13051 month ago
public: long long int factorial(int N){ if(N == 0) return 1; return N*factorial(N-1); }
0
abhishekkr50082 months ago
//In 0.1 Try with StreamsAPI
static long factorial(int N){ java.util.stream.LongStream list=java.util.stream.LongStream.range(1,N+1); Long sum = list.reduce(1, (a, b) -> a*b); return sum; }
0
aakasshuit2 months ago
//Java Solution
long fact=1;
for(int i=N;i>0;i--){
fact*=i;
}
return fact;
+1
mrunmai51152 months ago
long long int factorial(int N){
//code here
unsigned long long int product = 1;
for(int i = 1; i <= N; i++){
product *= i;
}
return product;
}
0
manishamali2 months ago
CPP Solution Total Time Taken 0.0
long long int factorial(int N){ long long fact=1; while(N>0){ fact*=N; N=N-1; } return fact;}
0
barotlove202 months ago
long long int factorial(int N){
long long int ans = 1;
for(int i=N;i>0;--i)
{
ans *= i;
}
return ans;
}
0
nishabhatt093362 months ago
C(gcc 5.4)
long long int factorial(int N){ long long f=1,i,facto;for(i=N;i>=1;i--) {f=f*i;} facto=f;return facto;}
+1
darshitagupta2 months ago
simple c++ soln
long long int factorial(int N){ //code here if(N==1 || N==0)return 1; else return N*factorial(N-1);}
0
alokaryan513 months ago
class Solution{ static long factorial(int N){ // code here if (N == 0 || N ==1){ return 1; } long ans = 1; for(int i = 1; i <= N; i++){ ans = ans * i; } return ans; }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 294,
"s": 238,
"text": "Given a positive integer, N. Find the factorial of N.\n "
},
{
"code": null,
"e": 305,
"s": 294,
"text": "Example 1:"
},
{
"code": null,
"e": 359,
"s": 305,
"text": "Input:\nN = 5\nOutput:\n120\nExplanation:\n5*4*3*2*1 = 120"
},
{
"code": null,
"e": 370,
"s": 359,
"text": "Example 2:"
},
{
"code": null,
"e": 421,
"s": 370,
"text": "Input:\nN = 4\nOutput:\n24\nExplanation:\n4*3*2*1 = 24\n"
},
{
"code": null,
"e": 622,
"s": 421,
"text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function factorial() which takes an integer N as input parameters and returns an integer, the factorial of N.\n "
},
{
"code": null,
"e": 687,
"s": 622,
"text": "Expected Time Complexity: O(N)\nExpected Space Complexity: O(1)\n "
},
{
"code": null,
"e": 713,
"s": 687,
"text": "Constraints:\n0 <= N <= 18"
},
{
"code": null,
"e": 715,
"s": 713,
"text": "0"
},
{
"code": null,
"e": 740,
"s": 715,
"text": "mayank180919991 week ago"
},
{
"code": null,
"e": 901,
"s": 740,
"text": "long long int factorial(int N){\n //code here\n long long int fact=1;\n for(int i=1;i<=N;i++){\n fact=fact*i;\n }\n return fact;\n}"
},
{
"code": null,
"e": 903,
"s": 901,
"text": "0"
},
{
"code": null,
"e": 932,
"s": 903,
"text": "purnimasharma13051 month ago"
},
{
"code": null,
"e": 1053,
"s": 932,
"text": "public: long long int factorial(int N){ if(N == 0) return 1; return N*factorial(N-1); }"
},
{
"code": null,
"e": 1055,
"s": 1053,
"text": "0"
},
{
"code": null,
"e": 1082,
"s": 1055,
"text": "abhishekkr50082 months ago"
},
{
"code": null,
"e": 1112,
"s": 1082,
"text": " //In 0.1 Try with StreamsAPI"
},
{
"code": null,
"e": 1296,
"s": 1112,
"text": "static long factorial(int N){ java.util.stream.LongStream list=java.util.stream.LongStream.range(1,N+1); Long sum = list.reduce(1, (a, b) -> a*b); return sum; }"
},
{
"code": null,
"e": 1298,
"s": 1296,
"text": "0"
},
{
"code": null,
"e": 1321,
"s": 1298,
"text": "aakasshuit2 months ago"
},
{
"code": null,
"e": 1441,
"s": 1321,
"text": "//Java Solution\n\n long fact=1;\n for(int i=N;i>0;i--){\n fact*=i;\n }\n return fact;"
},
{
"code": null,
"e": 1444,
"s": 1441,
"text": "+1"
},
{
"code": null,
"e": 1468,
"s": 1444,
"text": "mrunmai51152 months ago"
},
{
"code": null,
"e": 1657,
"s": 1468,
"text": "long long int factorial(int N){\n //code here\n unsigned long long int product = 1;\n for(int i = 1; i <= N; i++){\n product *= i;\n }\n return product;\n}"
},
{
"code": null,
"e": 1659,
"s": 1657,
"text": "0"
},
{
"code": null,
"e": 1683,
"s": 1659,
"text": "manishamali2 months ago"
},
{
"code": null,
"e": 1717,
"s": 1683,
"text": "CPP Solution Total Time Taken 0.0"
},
{
"code": null,
"e": 1850,
"s": 1717,
"text": "long long int factorial(int N){ long long fact=1; while(N>0){ fact*=N; N=N-1; } return fact;} "
},
{
"code": null,
"e": 1852,
"s": 1850,
"text": "0"
},
{
"code": null,
"e": 1876,
"s": 1852,
"text": "barotlove202 months ago"
},
{
"code": null,
"e": 2027,
"s": 1876,
"text": "long long int factorial(int N){\n long long int ans = 1;\n for(int i=N;i>0;--i)\n {\n ans *= i;\n }\n return ans;\n}\n"
},
{
"code": null,
"e": 2029,
"s": 2027,
"text": "0"
},
{
"code": null,
"e": 2057,
"s": 2029,
"text": "nishabhatt093362 months ago"
},
{
"code": null,
"e": 2068,
"s": 2057,
"text": "C(gcc 5.4)"
},
{
"code": null,
"e": 2180,
"s": 2068,
"text": "long long int factorial(int N){ long long f=1,i,facto;for(i=N;i>=1;i--) {f=f*i;} facto=f;return facto;}"
},
{
"code": null,
"e": 2183,
"s": 2180,
"text": "+1"
},
{
"code": null,
"e": 2209,
"s": 2183,
"text": "darshitagupta2 months ago"
},
{
"code": null,
"e": 2225,
"s": 2209,
"text": "simple c++ soln"
},
{
"code": null,
"e": 2346,
"s": 2225,
"text": "long long int factorial(int N){ //code here if(N==1 || N==0)return 1; else return N*factorial(N-1);}"
},
{
"code": null,
"e": 2350,
"s": 2348,
"text": "0"
},
{
"code": null,
"e": 2374,
"s": 2350,
"text": "alokaryan513 months ago"
},
{
"code": null,
"e": 2615,
"s": 2374,
"text": "class Solution{ static long factorial(int N){ // code here if (N == 0 || N ==1){ return 1; } long ans = 1; for(int i = 1; i <= N; i++){ ans = ans * i; } return ans; }}"
},
{
"code": null,
"e": 2761,
"s": 2615,
"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": 2797,
"s": 2761,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2807,
"s": 2797,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2817,
"s": 2807,
"text": "\nContest\n"
},
{
"code": null,
"e": 2880,
"s": 2817,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3028,
"s": 2880,
"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": 3236,
"s": 3028,
"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": 3342,
"s": 3236,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
OpenCV - Morphological Operations
|
In the earlier chapters, we discussed the process of erosion and dilation. In addition to these two, OpenCV has more morphological transformations. The morphologyEx() of the method of the class Imgproc is used to perform these operations on a given image.
Following is the syntax of this method −
morphologyEx(src, dst, op, kernel)
This method accepts the following parameters −
src − An object of the class Mat representing the source (input) image.
src − An object of the class Mat representing the source (input) image.
dst − object of the class Mat representing the destination (output) image.
dst − object of the class Mat representing the destination (output) image.
op − An integer representing the type of the Morphological operation.
op − An integer representing the type of the Morphological operation.
kernel − A kernel matrix.
kernel − A kernel matrix.
The following program demonstrates how to apply the morphological operation "top-hat" on an image using OpenCV library.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class MorphologyExTest {
public static void main(String args[]) {
// Loading the OpenCV core library
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
// Reading the Image from the file and storing it in to a Matrix object
String file ="E:/OpenCV/chap12/morph_input.jpg";
Mat src = Imgcodecs.imread(file);
// Creating an empty matrix to store the result
Mat dst = new Mat();
// Creating kernel matrix
Mat kernel = Mat.ones(5,5, CvType.CV_32F);
// Applying Blur effect on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);
// Writing the image
Imgcodecs.imwrite("E:/OpenCV/chap12/morph_tophat.jpg", dst);
System.out.println("Image Processed");
}
}
Assume that following is the input image morph_input.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed
If you open the specified path, you can observe the output image as follows −
In addition to the morphological operation TOPHAT, demonstrated in the previous example, OpenCV caters various other types of morphologies. All these types are represented by predefined static fields (fixed values) of Imgproc class.
You can choose the type of the morphology you need by passing their respective predefined value to the parameter op of the morphologyEx() method.
// Applying Blur effect on the Image
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);
Following are the values representing the type of morphological operations and their respective outputs.
70 Lectures
9 hours
Abhilash Nelson
41 Lectures
4 hours
Abhilash Nelson
20 Lectures
2 hours
Spotle Learn
12 Lectures
46 mins
Srikanth Guskra
19 Lectures
2 hours
Haithem Gasmi
67 Lectures
6.5 hours
Gianluca Mottola
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3260,
"s": 3004,
"text": "In the earlier chapters, we discussed the process of erosion and dilation. In addition to these two, OpenCV has more morphological transformations. The morphologyEx() of the method of the class Imgproc is used to perform these operations on a given image."
},
{
"code": null,
"e": 3301,
"s": 3260,
"text": "Following is the syntax of this method −"
},
{
"code": null,
"e": 3337,
"s": 3301,
"text": "morphologyEx(src, dst, op, kernel)\n"
},
{
"code": null,
"e": 3384,
"s": 3337,
"text": "This method accepts the following parameters −"
},
{
"code": null,
"e": 3456,
"s": 3384,
"text": "src − An object of the class Mat representing the source (input) image."
},
{
"code": null,
"e": 3528,
"s": 3456,
"text": "src − An object of the class Mat representing the source (input) image."
},
{
"code": null,
"e": 3603,
"s": 3528,
"text": "dst − object of the class Mat representing the destination (output) image."
},
{
"code": null,
"e": 3678,
"s": 3603,
"text": "dst − object of the class Mat representing the destination (output) image."
},
{
"code": null,
"e": 3748,
"s": 3678,
"text": "op − An integer representing the type of the Morphological operation."
},
{
"code": null,
"e": 3818,
"s": 3748,
"text": "op − An integer representing the type of the Morphological operation."
},
{
"code": null,
"e": 3844,
"s": 3818,
"text": "kernel − A kernel matrix."
},
{
"code": null,
"e": 3870,
"s": 3844,
"text": "kernel − A kernel matrix."
},
{
"code": null,
"e": 3990,
"s": 3870,
"text": "The following program demonstrates how to apply the morphological operation \"top-hat\" on an image using OpenCV library."
},
{
"code": null,
"e": 4924,
"s": 3990,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.CvType;\nimport org.opencv.core.Mat;\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class MorphologyExTest {\n public static void main(String args[]) {\n // Loading the OpenCV core library\n System.loadLibrary( Core.NATIVE_LIBRARY_NAME );\n\n // Reading the Image from the file and storing it in to a Matrix object\n String file =\"E:/OpenCV/chap12/morph_input.jpg\";\n Mat src = Imgcodecs.imread(file);\n\n // Creating an empty matrix to store the result\n Mat dst = new Mat();\n\n // Creating kernel matrix\n Mat kernel = Mat.ones(5,5, CvType.CV_32F);\n\n // Applying Blur effect on the Image \n Imgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap12/morph_tophat.jpg\", dst);\n\n System.out.println(\"Image Processed\");\n } \n}"
},
{
"code": null,
"e": 5013,
"s": 4924,
"text": "Assume that following is the input image morph_input.jpg specified in the above program."
},
{
"code": null,
"e": 5075,
"s": 5013,
"text": "On executing the program, you will get the following output −"
},
{
"code": null,
"e": 5092,
"s": 5075,
"text": "Image Processed\n"
},
{
"code": null,
"e": 5170,
"s": 5092,
"text": "If you open the specified path, you can observe the output image as follows −"
},
{
"code": null,
"e": 5403,
"s": 5170,
"text": "In addition to the morphological operation TOPHAT, demonstrated in the previous example, OpenCV caters various other types of morphologies. All these types are represented by predefined static fields (fixed values) of Imgproc class."
},
{
"code": null,
"e": 5549,
"s": 5403,
"text": "You can choose the type of the morphology you need by passing their respective predefined value to the parameter op of the morphologyEx() method."
},
{
"code": null,
"e": 5649,
"s": 5549,
"text": "// Applying Blur effect on the Image\nImgproc.morphologyEx(src, dst, Imgproc.MORPH_TOPHAT, kernel);\n"
},
{
"code": null,
"e": 5754,
"s": 5649,
"text": "Following are the values representing the type of morphological operations and their respective outputs."
},
{
"code": null,
"e": 5787,
"s": 5754,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5804,
"s": 5787,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5837,
"s": 5804,
"text": "\n 41 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5854,
"s": 5837,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5887,
"s": 5854,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5901,
"s": 5887,
"text": " Spotle Learn"
},
{
"code": null,
"e": 5933,
"s": 5901,
"text": "\n 12 Lectures \n 46 mins\n"
},
{
"code": null,
"e": 5950,
"s": 5933,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 5983,
"s": 5950,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5998,
"s": 5983,
"text": " Haithem Gasmi"
},
{
"code": null,
"e": 6033,
"s": 5998,
"text": "\n 67 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6051,
"s": 6033,
"text": " Gianluca Mottola"
},
{
"code": null,
"e": 6058,
"s": 6051,
"text": " Print"
},
{
"code": null,
"e": 6069,
"s": 6058,
"text": " Add Notes"
}
] |
Metrics and Python. In a series of three articles, we will... | by Gabriel Naya | Towards Data Science
|
As a programmer I lacked on studies about mathematical and statistical concepts. Now with more experience I’ve decided to compile and share some of the metrics and concepts that I’ve faced for different problems I encountered.
In this series of articles, we will briefly review each of them, their use, their formulas, examples, and implementation in Python, so we can see them all together and have this chart on hands, if necessary.Here is part one, referring to the most used metrics for regression cases.
For this article, we have used the Kaggle dataset on housing prices, because it is a typical example of regression with which many of us are familiar.Elementary engineering features have been done to be able to present a minimum reasonable model, which serves as an example for the development of metrics.
from scipy.stats import boxcox_normmaxfrom scipy.special import boxcox1pfrom sklearn.linear_model import LinearRegressiontrain = pd.read_csv('../input/home-data-for-ml-course/train.csv')y = train.SalePrice.reset_index(drop=True)features = trainend_features = ['OverallQual','GrLivArea','GarageCars','GarageArea','TotalBsmtSF','1stFlrSF','FullBath','TotRmsAbvGrd','MSSubClass','MSZoning']features = features[end_features]features['MSSubClass'] = features['MSSubClass'].apply(str)features['MSZoning'] = features.groupby('MSSubClass')['MSZoning'].transform(lambda x: x.fillna(x.mode()[0]))objects = [col for col in features.columns if features[col].dtype == "object"]features.update(features[objects].fillna('None'))numeric_dtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']numerics = [col for col in features.columns if features[col].dtype in numeric_dtypes]features.update(features[numerics].fillna(0))for i in numerics: features[i] = boxcox1p(features[i], boxcox_normmax(features[i] + 1))X = pd.get_dummies(features).reset_index(drop=True)#----------------- The modelreg = LinearRegression().fit(X, y)y_pred = reg.predict(X)
Here is a simple table with the review of the metrics we are going to describe, the last column of the table is the result of our model.
MAE measures the average magnitude of the errors in a set of predictions, without considering their direction. It’s the average over the test sample of the absolute differences between prediction and actual observation where all individual differences have equal weight.
The mean absolute error uses the same scale as the data. This is known as a scale-dependent accuracy measure and, therefore, cannot be used to make comparisons between series using different scales.
from sklearn.metrics import mean_absolute_errorprint ('Sk MAE: ' + str(mean_absolute_error(y,y_pred)) )def MAE(predict,target): return (abs(predict-target)).mean()print ('My MAE: ' + str(MAE(y_pred,y)))
MSE is a risk function, corresponding to the expected value of the squared error loss. The fact that MSE is almost always strictly positive (and not zero) is because of randomness or because the estimator does not account for information that could produce a more accurate estimate. The MSE is a measure of the quality of an estimator — it is always non-negative, and values closer to zero are better.
“Minimizing MSE is a key criterion in selecting estimators: see minimum mean-square error. Among unbiased estimators, minimizing the MSE is equivalent to minimizing the variance, and the estimator that does this is the minimum variance unbiased estimator. However, a biased estimator may have lower MSE; see estimator bias.
In statistical modelling the MSE can represent the difference between the actual observations and the observation values predicted by the model. In this context, it is used to determine the extent to which the model fits the data as well as whether removing some explanatory variables is possible without significantly harming the model’s predictive ability.”
from sklearn.metrics import mean_squared_errorprint ('Sk MSE: ' + str(mean_squared_error(y,y_pred)) )def MSE(predict,target): return ((predict-target)**2).mean()print ('My MSE: ' + str(MSE(y_pred,y)) )
RMSE is a quadratic scoring rule that also measures the average magnitude of the error. It’s the square root of the average of squared differences between prediction and actual observation.
Comparision RMSE vs MAE
Similarities:
Express average model prediction error in same units of the variable of interest.
Can range from 0 to ∞ and are indifferent to the direction of errors.
Lower values are better.
Difference:
Taking the square root before they are averaged, RMSE gives a relatively high weight to large errors, so RMSE should be useful when large errors are undesirable.
def RMSE(predict, target): return np.sqrt(((predict - target) ** 2).mean())print ('My RMSE: ' + str(RMSE(y_pred,y)) )
Measure of prediction accuracy of a forecasting method in statistics, for example in trend estimation, also used as a loss function for regression problems in machine learning. It usually expresses accuracy as a percentage.
Although the concept of MAPE sounds very simple and convincing, it has major drawbacks in practical application [*], and there are many studies on shortcomings and misleading results from MAPE
def MAPE(predict,target): return ( abs((target - predict) / target).mean()) * 100print ('My MAPE: ' + str(MAPE(y_pred,y)) )
In case of RMSLE, you take the log of the predictions and actual values. So basically, what changes is the variance that you are measuring. I believe RMSLE is usually used when you don’t want to penalize huge differences in the predicted and the actual values when both predicted and true values are huge numbers.
RMSLE measures the ratio between actual and predicted.
log(pi+1)−log(ai+1)log(pi+1)−log(ai+1)
can be written as log((pi+1)/(ai+1))log((pi+1)/(ai+1))
It can be used when you don’t want to penalize huge differences when the values are huge numbers.
Also, this can be used when you want to penalize under estimates more than over estimates.
Lets have a look at the below example
Case a) : Pi = 600, Ai = 1000 — RMSE = 400, RMSLE = 0.5108
Case b) : Pi = 1400, Ai = 1000 — RMSE = 400, RMSLE = 0.3365
import mathdef RMSLE(predict, target): total = 0 for k in range(len(predict)): LPred= np.log1p(predict[k]+1) LTarg = np.log1p(target[k] + 1) if not (math.isnan(LPred)) and not (math.isnan(LTarg)): total = total + ((LPred-LTarg) **2) total = total / len(predict) return np.sqrt(total)print ('My RMSLE: ' + str(RMSLE(y_pred,y)) )
R2 and R-Squared help us to know how good our regression model as compared to a very simple model that just predicts the mean value of target from the train set as predictions.
def R2(predict, target): return 1 - (MAE(predict,target) / MAE(target.mean(),target))def R_SQR(predict, target): r2 = R2(predict,target) return np.sqrt(r2)print ('My R2 : ' + str(R2(y_pred,y)) )print ('My R : ' + str(R_SQR(y_pred,y)) )
A model performing equal to baseline would give R-Squared as 0. Better the model, higher the r2 value. The best model with all correct predictions would give R-Squared as 1. However, on adding new features to the model, the R-Squared value either increases or remains the same. R-Squared does not penalize for adding features that add no value to the model. So an improved version over the R-Squared is the adjusted R-Squared
def R2_ADJ(predict, target, k): r2 = R2(predict,target) n = len(target) return (1 - ( (1-r2) * ( (n-1) / (n-(k+1)) ) ) )k= len(features.columns)print ('My R2 adjusted: ' + str(R2_ADJ(y_pred,y,k)) )
Putting the main regression metrics in a single table, and programming the functions for each of them has been an excellent personal experience.Applying them on the same exercise, since it allowed me to compare their uses, understand their formulas, and while developing the article, to have a complete picture. Hopefully, the article has been useful, and any comments or corrections will be welcome.
Next week we will deliver the second part of this series, an article on classification metrics ...
|
[
{
"code": null,
"e": 274,
"s": 47,
"text": "As a programmer I lacked on studies about mathematical and statistical concepts. Now with more experience I’ve decided to compile and share some of the metrics and concepts that I’ve faced for different problems I encountered."
},
{
"code": null,
"e": 556,
"s": 274,
"text": "In this series of articles, we will briefly review each of them, their use, their formulas, examples, and implementation in Python, so we can see them all together and have this chart on hands, if necessary.Here is part one, referring to the most used metrics for regression cases."
},
{
"code": null,
"e": 862,
"s": 556,
"text": "For this article, we have used the Kaggle dataset on housing prices, because it is a typical example of regression with which many of us are familiar.Elementary engineering features have been done to be able to present a minimum reasonable model, which serves as an example for the development of metrics."
},
{
"code": null,
"e": 2009,
"s": 862,
"text": "from scipy.stats import boxcox_normmaxfrom scipy.special import boxcox1pfrom sklearn.linear_model import LinearRegressiontrain = pd.read_csv('../input/home-data-for-ml-course/train.csv')y = train.SalePrice.reset_index(drop=True)features = trainend_features = ['OverallQual','GrLivArea','GarageCars','GarageArea','TotalBsmtSF','1stFlrSF','FullBath','TotRmsAbvGrd','MSSubClass','MSZoning']features = features[end_features]features['MSSubClass'] = features['MSSubClass'].apply(str)features['MSZoning'] = features.groupby('MSSubClass')['MSZoning'].transform(lambda x: x.fillna(x.mode()[0]))objects = [col for col in features.columns if features[col].dtype == \"object\"]features.update(features[objects].fillna('None'))numeric_dtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']numerics = [col for col in features.columns if features[col].dtype in numeric_dtypes]features.update(features[numerics].fillna(0))for i in numerics: features[i] = boxcox1p(features[i], boxcox_normmax(features[i] + 1))X = pd.get_dummies(features).reset_index(drop=True)#----------------- The modelreg = LinearRegression().fit(X, y)y_pred = reg.predict(X)"
},
{
"code": null,
"e": 2146,
"s": 2009,
"text": "Here is a simple table with the review of the metrics we are going to describe, the last column of the table is the result of our model."
},
{
"code": null,
"e": 2417,
"s": 2146,
"text": "MAE measures the average magnitude of the errors in a set of predictions, without considering their direction. It’s the average over the test sample of the absolute differences between prediction and actual observation where all individual differences have equal weight."
},
{
"code": null,
"e": 2616,
"s": 2417,
"text": "The mean absolute error uses the same scale as the data. This is known as a scale-dependent accuracy measure and, therefore, cannot be used to make comparisons between series using different scales."
},
{
"code": null,
"e": 2822,
"s": 2616,
"text": "from sklearn.metrics import mean_absolute_errorprint ('Sk MAE: ' + str(mean_absolute_error(y,y_pred)) )def MAE(predict,target): return (abs(predict-target)).mean()print ('My MAE: ' + str(MAE(y_pred,y)))"
},
{
"code": null,
"e": 3224,
"s": 2822,
"text": "MSE is a risk function, corresponding to the expected value of the squared error loss. The fact that MSE is almost always strictly positive (and not zero) is because of randomness or because the estimator does not account for information that could produce a more accurate estimate. The MSE is a measure of the quality of an estimator — it is always non-negative, and values closer to zero are better."
},
{
"code": null,
"e": 3548,
"s": 3224,
"text": "“Minimizing MSE is a key criterion in selecting estimators: see minimum mean-square error. Among unbiased estimators, minimizing the MSE is equivalent to minimizing the variance, and the estimator that does this is the minimum variance unbiased estimator. However, a biased estimator may have lower MSE; see estimator bias."
},
{
"code": null,
"e": 3908,
"s": 3548,
"text": "In statistical modelling the MSE can represent the difference between the actual observations and the observation values predicted by the model. In this context, it is used to determine the extent to which the model fits the data as well as whether removing some explanatory variables is possible without significantly harming the model’s predictive ability.”"
},
{
"code": null,
"e": 4113,
"s": 3908,
"text": "from sklearn.metrics import mean_squared_errorprint ('Sk MSE: ' + str(mean_squared_error(y,y_pred)) )def MSE(predict,target): return ((predict-target)**2).mean()print ('My MSE: ' + str(MSE(y_pred,y)) )"
},
{
"code": null,
"e": 4303,
"s": 4113,
"text": "RMSE is a quadratic scoring rule that also measures the average magnitude of the error. It’s the square root of the average of squared differences between prediction and actual observation."
},
{
"code": null,
"e": 4327,
"s": 4303,
"text": "Comparision RMSE vs MAE"
},
{
"code": null,
"e": 4341,
"s": 4327,
"text": "Similarities:"
},
{
"code": null,
"e": 4423,
"s": 4341,
"text": "Express average model prediction error in same units of the variable of interest."
},
{
"code": null,
"e": 4493,
"s": 4423,
"text": "Can range from 0 to ∞ and are indifferent to the direction of errors."
},
{
"code": null,
"e": 4518,
"s": 4493,
"text": "Lower values are better."
},
{
"code": null,
"e": 4530,
"s": 4518,
"text": "Difference:"
},
{
"code": null,
"e": 4692,
"s": 4530,
"text": "Taking the square root before they are averaged, RMSE gives a relatively high weight to large errors, so RMSE should be useful when large errors are undesirable."
},
{
"code": null,
"e": 4813,
"s": 4692,
"text": "def RMSE(predict, target): return np.sqrt(((predict - target) ** 2).mean())print ('My RMSE: ' + str(RMSE(y_pred,y)) )"
},
{
"code": null,
"e": 5037,
"s": 4813,
"text": "Measure of prediction accuracy of a forecasting method in statistics, for example in trend estimation, also used as a loss function for regression problems in machine learning. It usually expresses accuracy as a percentage."
},
{
"code": null,
"e": 5230,
"s": 5037,
"text": "Although the concept of MAPE sounds very simple and convincing, it has major drawbacks in practical application [*], and there are many studies on shortcomings and misleading results from MAPE"
},
{
"code": null,
"e": 5357,
"s": 5230,
"text": "def MAPE(predict,target): return ( abs((target - predict) / target).mean()) * 100print ('My MAPE: ' + str(MAPE(y_pred,y)) )"
},
{
"code": null,
"e": 5671,
"s": 5357,
"text": "In case of RMSLE, you take the log of the predictions and actual values. So basically, what changes is the variance that you are measuring. I believe RMSLE is usually used when you don’t want to penalize huge differences in the predicted and the actual values when both predicted and true values are huge numbers."
},
{
"code": null,
"e": 5726,
"s": 5671,
"text": "RMSLE measures the ratio between actual and predicted."
},
{
"code": null,
"e": 5765,
"s": 5726,
"text": "log(pi+1)−log(ai+1)log(pi+1)−log(ai+1)"
},
{
"code": null,
"e": 5820,
"s": 5765,
"text": "can be written as log((pi+1)/(ai+1))log((pi+1)/(ai+1))"
},
{
"code": null,
"e": 5918,
"s": 5820,
"text": "It can be used when you don’t want to penalize huge differences when the values are huge numbers."
},
{
"code": null,
"e": 6009,
"s": 5918,
"text": "Also, this can be used when you want to penalize under estimates more than over estimates."
},
{
"code": null,
"e": 6047,
"s": 6009,
"text": "Lets have a look at the below example"
},
{
"code": null,
"e": 6106,
"s": 6047,
"text": "Case a) : Pi = 600, Ai = 1000 — RMSE = 400, RMSLE = 0.5108"
},
{
"code": null,
"e": 6166,
"s": 6106,
"text": "Case b) : Pi = 1400, Ai = 1000 — RMSE = 400, RMSLE = 0.3365"
},
{
"code": null,
"e": 6557,
"s": 6166,
"text": "import mathdef RMSLE(predict, target): total = 0 for k in range(len(predict)): LPred= np.log1p(predict[k]+1) LTarg = np.log1p(target[k] + 1) if not (math.isnan(LPred)) and not (math.isnan(LTarg)): total = total + ((LPred-LTarg) **2) total = total / len(predict) return np.sqrt(total)print ('My RMSLE: ' + str(RMSLE(y_pred,y)) )"
},
{
"code": null,
"e": 6734,
"s": 6557,
"text": "R2 and R-Squared help us to know how good our regression model as compared to a very simple model that just predicts the mean value of target from the train set as predictions."
},
{
"code": null,
"e": 6996,
"s": 6734,
"text": "def R2(predict, target): return 1 - (MAE(predict,target) / MAE(target.mean(),target))def R_SQR(predict, target): r2 = R2(predict,target) return np.sqrt(r2)print ('My R2 : ' + str(R2(y_pred,y)) )print ('My R : ' + str(R_SQR(y_pred,y)) )"
},
{
"code": null,
"e": 7422,
"s": 6996,
"text": "A model performing equal to baseline would give R-Squared as 0. Better the model, higher the r2 value. The best model with all correct predictions would give R-Squared as 1. However, on adding new features to the model, the R-Squared value either increases or remains the same. R-Squared does not penalize for adding features that add no value to the model. So an improved version over the R-Squared is the adjusted R-Squared"
},
{
"code": null,
"e": 7631,
"s": 7422,
"text": "def R2_ADJ(predict, target, k): r2 = R2(predict,target) n = len(target) return (1 - ( (1-r2) * ( (n-1) / (n-(k+1)) ) ) )k= len(features.columns)print ('My R2 adjusted: ' + str(R2_ADJ(y_pred,y,k)) )"
},
{
"code": null,
"e": 8032,
"s": 7631,
"text": "Putting the main regression metrics in a single table, and programming the functions for each of them has been an excellent personal experience.Applying them on the same exercise, since it allowed me to compare their uses, understand their formulas, and while developing the article, to have a complete picture. Hopefully, the article has been useful, and any comments or corrections will be welcome."
}
] |
DALL·E by OpenAI: Creating
Images from Text | by Merzmensch | Towards Data Science
|
It’s the 5th of January 2021, and OpenAI reports back already with another AI breakthrough. 2020 they impacted the AI world at least with two Milestones: GPT-3, a powerful Natural Language Processing model, and a music generator JukeBox.
Driven by Transformer, these two approaches in various media created coherent and convincing outputs — as texts and as music. OpenAI also experimented with visual media — e.g., within ImageGPT.
Now a new star arises on the horizon of a generative AI approach: DALL-E. Called after surrealist Salvador Dalí and the SciFi animation “Wall-E”, this transformer language model represents a multimodal neural network —
AI systems that learn about concepts in several modalities, primarily the textual and visual domains, in order to better understand the world. (OpenAI)
I suppose this is a good way to avoid AGI claims. Even OpenAI is aware, that the way to AGI is long (as these stated after they experienced the hype around GPT-3):
Indeed, AGI needs an omnipotent and multimedia approach. But DALL·E is a huge step towards this.
DALL·E does what it is described to do: creating images from text prompts. It’s a 12-billion parameter of GPT-3 and can generate images from texts using text-image pairs.
Transformer-driven Neural Networks are already an overwhelming phenomenon. Even if we can discuss “comprehension”, the “understanding” of concepts is unbelievably vital. Remind the GPT-3 written “love letter by a toaster”:
In this case, GPT-3 understood:
The essence of love letters
Functionality and features of a toaster
combination of both concepts into one “Gesamtkunstwerk”
With your Prompts, you don’t just “program” transformer driven model. You transmit your request, like to a design agency — and the results may amuse, attract, or annoy you (it’s a matter of the taste).
DALL·E fulfills its job perfectly — when we may apply the adjective “perfect” to the creative approach.
In the Blog presenting DALL·E you can see the model in action — with pre-rendered images of various contexts. You can in an interactive mode even chose between some predefined parameters.
Here is, for example, a Prompts:
A [store front] that has the word [openai] written on it
Changing the second parameter (word) to “Skynet” we get another set of images:
Or: CLIP
You see, how well the task is received and realized — in various styles and visuals, based on the pre-trained model.
There were indeed another approaches for Text2Img, but DALL·E wins in every comparison:
Experimenting with objects, shapes, and colors demonstrates the capability of this Neural Network.
Using Prompts
an [armchair] in the [shape] of [avocado/pikachu/japanese mapple]
you get photorealistic imagery with an astonishing style coherence, and variety within one topic.
Interestingly, DALL·E works perfectly with zero-shot visual reasoning without additional training.
Here is a more sophisticated prompt using text and image:
You see the same cat, the postage stamp, and a variety of colors and designs.
Apropos design, the system can recognize styles and emotional sentiment of image characterization.
For example, let’s take an owl as an emoji.
Here is a confused owl:
A depressed owl:
A happy owl:
A sleepy owl:
DALL·E has also pre-training based knowledge of temporal styles, for example, a visual representation of a device from various epochs:
Even geographical and cultural knowledge is present here. For example, the system can generate images of landmarks — combined with an image prompt for style transfer:
Here you can see various SF MOMA hallucinations with the “night sky” image prompt.
Indeed, even if AGI is still in the future, DALL·E is undoubtedly a giant leap towards it — understanding the human requests, applying own knowledge, generating photorealistic and unique imagery, it opens new ways for various approaches in Art, Design, Storytelling.
Now I am eager to play around with it as soon as it is available. Because already knowing GPT-3 ability, I can freely say — it’s a mind-blowing experience.
|
[
{
"code": null,
"e": 409,
"s": 171,
"text": "It’s the 5th of January 2021, and OpenAI reports back already with another AI breakthrough. 2020 they impacted the AI world at least with two Milestones: GPT-3, a powerful Natural Language Processing model, and a music generator JukeBox."
},
{
"code": null,
"e": 603,
"s": 409,
"text": "Driven by Transformer, these two approaches in various media created coherent and convincing outputs — as texts and as music. OpenAI also experimented with visual media — e.g., within ImageGPT."
},
{
"code": null,
"e": 823,
"s": 603,
"text": "Now a new star arises on the horizon of a generative AI approach: DALL-E. Called after surrealist Salvador Dalí and the SciFi animation “Wall-E”, this transformer language model represents a multimodal neural network —"
},
{
"code": null,
"e": 975,
"s": 823,
"text": "AI systems that learn about concepts in several modalities, primarily the textual and visual domains, in order to better understand the world. (OpenAI)"
},
{
"code": null,
"e": 1139,
"s": 975,
"text": "I suppose this is a good way to avoid AGI claims. Even OpenAI is aware, that the way to AGI is long (as these stated after they experienced the hype around GPT-3):"
},
{
"code": null,
"e": 1236,
"s": 1139,
"text": "Indeed, AGI needs an omnipotent and multimedia approach. But DALL·E is a huge step towards this."
},
{
"code": null,
"e": 1407,
"s": 1236,
"text": "DALL·E does what it is described to do: creating images from text prompts. It’s a 12-billion parameter of GPT-3 and can generate images from texts using text-image pairs."
},
{
"code": null,
"e": 1630,
"s": 1407,
"text": "Transformer-driven Neural Networks are already an overwhelming phenomenon. Even if we can discuss “comprehension”, the “understanding” of concepts is unbelievably vital. Remind the GPT-3 written “love letter by a toaster”:"
},
{
"code": null,
"e": 1662,
"s": 1630,
"text": "In this case, GPT-3 understood:"
},
{
"code": null,
"e": 1690,
"s": 1662,
"text": "The essence of love letters"
},
{
"code": null,
"e": 1730,
"s": 1690,
"text": "Functionality and features of a toaster"
},
{
"code": null,
"e": 1786,
"s": 1730,
"text": "combination of both concepts into one “Gesamtkunstwerk”"
},
{
"code": null,
"e": 1988,
"s": 1786,
"text": "With your Prompts, you don’t just “program” transformer driven model. You transmit your request, like to a design agency — and the results may amuse, attract, or annoy you (it’s a matter of the taste)."
},
{
"code": null,
"e": 2092,
"s": 1988,
"text": "DALL·E fulfills its job perfectly — when we may apply the adjective “perfect” to the creative approach."
},
{
"code": null,
"e": 2280,
"s": 2092,
"text": "In the Blog presenting DALL·E you can see the model in action — with pre-rendered images of various contexts. You can in an interactive mode even chose between some predefined parameters."
},
{
"code": null,
"e": 2313,
"s": 2280,
"text": "Here is, for example, a Prompts:"
},
{
"code": null,
"e": 2370,
"s": 2313,
"text": "A [store front] that has the word [openai] written on it"
},
{
"code": null,
"e": 2449,
"s": 2370,
"text": "Changing the second parameter (word) to “Skynet” we get another set of images:"
},
{
"code": null,
"e": 2458,
"s": 2449,
"text": "Or: CLIP"
},
{
"code": null,
"e": 2575,
"s": 2458,
"text": "You see, how well the task is received and realized — in various styles and visuals, based on the pre-trained model."
},
{
"code": null,
"e": 2663,
"s": 2575,
"text": "There were indeed another approaches for Text2Img, but DALL·E wins in every comparison:"
},
{
"code": null,
"e": 2762,
"s": 2663,
"text": "Experimenting with objects, shapes, and colors demonstrates the capability of this Neural Network."
},
{
"code": null,
"e": 2776,
"s": 2762,
"text": "Using Prompts"
},
{
"code": null,
"e": 2842,
"s": 2776,
"text": "an [armchair] in the [shape] of [avocado/pikachu/japanese mapple]"
},
{
"code": null,
"e": 2940,
"s": 2842,
"text": "you get photorealistic imagery with an astonishing style coherence, and variety within one topic."
},
{
"code": null,
"e": 3039,
"s": 2940,
"text": "Interestingly, DALL·E works perfectly with zero-shot visual reasoning without additional training."
},
{
"code": null,
"e": 3097,
"s": 3039,
"text": "Here is a more sophisticated prompt using text and image:"
},
{
"code": null,
"e": 3175,
"s": 3097,
"text": "You see the same cat, the postage stamp, and a variety of colors and designs."
},
{
"code": null,
"e": 3274,
"s": 3175,
"text": "Apropos design, the system can recognize styles and emotional sentiment of image characterization."
},
{
"code": null,
"e": 3318,
"s": 3274,
"text": "For example, let’s take an owl as an emoji."
},
{
"code": null,
"e": 3342,
"s": 3318,
"text": "Here is a confused owl:"
},
{
"code": null,
"e": 3359,
"s": 3342,
"text": "A depressed owl:"
},
{
"code": null,
"e": 3372,
"s": 3359,
"text": "A happy owl:"
},
{
"code": null,
"e": 3386,
"s": 3372,
"text": "A sleepy owl:"
},
{
"code": null,
"e": 3521,
"s": 3386,
"text": "DALL·E has also pre-training based knowledge of temporal styles, for example, a visual representation of a device from various epochs:"
},
{
"code": null,
"e": 3688,
"s": 3521,
"text": "Even geographical and cultural knowledge is present here. For example, the system can generate images of landmarks — combined with an image prompt for style transfer:"
},
{
"code": null,
"e": 3771,
"s": 3688,
"text": "Here you can see various SF MOMA hallucinations with the “night sky” image prompt."
},
{
"code": null,
"e": 4038,
"s": 3771,
"text": "Indeed, even if AGI is still in the future, DALL·E is undoubtedly a giant leap towards it — understanding the human requests, applying own knowledge, generating photorealistic and unique imagery, it opens new ways for various approaches in Art, Design, Storytelling."
}
] |
How can we insert a new row into a MySQL table?
|
With the help of INSERT INTO command, a new row can be inserted into a table.
INSERT INTO table_name values(value1,value2,...)
Suppose we have a table named ‘Employee’ with three columns ‘Emp_id’, ‘Emp_name’ and ‘Emp_Sal’ then with the help of following query we can add new rows to the table −
mysql> INSERT INTO Employee values(110,'Aarav',50000);
Query OK, 1 row affected (0.07 sec)
mysql> INSERT INTO Employee values(200,'Raman',28000);
Query OK, 1 row affected (0.10 sec)
mysql> Select * from Employee;
+---------+-------------+-----------+
| Emp_id | Emp_name | Emp_sal |
+---------+-------------+-----------+
| 110 |Aarav | 50000 |
| 200 | Raman | 28000 |
+---------+-------------+-----------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "With the help of INSERT INTO command, a new row can be inserted into a table."
},
{
"code": null,
"e": 1189,
"s": 1140,
"text": "INSERT INTO table_name values(value1,value2,...)"
},
{
"code": null,
"e": 1357,
"s": 1189,
"text": "Suppose we have a table named ‘Employee’ with three columns ‘Emp_id’, ‘Emp_name’ and ‘Emp_Sal’ then with the help of following query we can add new rows to the table −"
},
{
"code": null,
"e": 1825,
"s": 1357,
"text": "mysql> INSERT INTO Employee values(110,'Aarav',50000);\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> INSERT INTO Employee values(200,'Raman',28000);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> Select * from Employee;\n+---------+-------------+-----------+\n| Emp_id | Emp_name | Emp_sal |\n+---------+-------------+-----------+\n| 110 |Aarav | 50000 |\n| 200 | Raman | 28000 |\n+---------+-------------+-----------+\n2 rows in set (0.00 sec)"
}
] |
Salesforce - Variables & Formulas
|
The data from the Salesforce objects can be brought into the Visualforce page using variables and expressions. Like other normal programming language, the Visualforce language has expressions, operators and literals, etc. The basic building block of this language is expressions.
The syntax of a Visualforce expression is as below.
{! expression }
Let us use the global variable $user. We can write the following code to get the username, First name and login name.
On previewing the output, we get the following details.
Similarly, we can use many other variables and manipulate them using formula as shown in the code below.
On previewing the output, we get the following details.
49 Lectures
3.5 hours
Manigandan Jagadeesan
113 Lectures
13 hours
Eduonix Learning Solutions
37 Lectures
3 hours
Manish Choudhari
22 Lectures
4.5 hours
Pranjal Srivastava
43 Lectures
7 hours
Debasis Jena
54 Lectures
8 hours
SYED CHAND SHAH
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2837,
"s": 2557,
"text": "The data from the Salesforce objects can be brought into the Visualforce page using variables and expressions. Like other normal programming language, the Visualforce language has expressions, operators and literals, etc. The basic building block of this language is expressions."
},
{
"code": null,
"e": 2889,
"s": 2837,
"text": "The syntax of a Visualforce expression is as below."
},
{
"code": null,
"e": 2906,
"s": 2889,
"text": "{! expression }\n"
},
{
"code": null,
"e": 3024,
"s": 2906,
"text": "Let us use the global variable $user. We can write the following code to get the username, First name and login name."
},
{
"code": null,
"e": 3080,
"s": 3024,
"text": "On previewing the output, we get the following details."
},
{
"code": null,
"e": 3185,
"s": 3080,
"text": "Similarly, we can use many other variables and manipulate them using formula as shown in the code below."
},
{
"code": null,
"e": 3241,
"s": 3185,
"text": "On previewing the output, we get the following details."
},
{
"code": null,
"e": 3276,
"s": 3241,
"text": "\n 49 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3299,
"s": 3276,
"text": " Manigandan Jagadeesan"
},
{
"code": null,
"e": 3334,
"s": 3299,
"text": "\n 113 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3362,
"s": 3334,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3395,
"s": 3362,
"text": "\n 37 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3413,
"s": 3395,
"text": " Manish Choudhari"
},
{
"code": null,
"e": 3448,
"s": 3413,
"text": "\n 22 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3468,
"s": 3448,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 3501,
"s": 3468,
"text": "\n 43 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3515,
"s": 3501,
"text": " Debasis Jena"
},
{
"code": null,
"e": 3548,
"s": 3515,
"text": "\n 54 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3565,
"s": 3548,
"text": " SYED CHAND SHAH"
},
{
"code": null,
"e": 3572,
"s": 3565,
"text": " Print"
},
{
"code": null,
"e": 3583,
"s": 3572,
"text": " Add Notes"
}
] |
How to wrap long lines in Python?
|
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.
Example of paranthesized line break:
list(
"Hello"
)
This will give the output:
['H', 'e','l', 'l', 'o']
Example of back-slashed line break:
print 'This s a really long line,', \
'but we can make it across multiple lines.'
This will give the output:
This is a really long line, but we can make it across multiple lines.
Both of these can be used, you may choose to use either depending on which looks more readable to you.
|
[
{
"code": null,
"e": 1461,
"s": 1062,
"text": "The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it. "
},
{
"code": null,
"e": 1499,
"s": 1461,
"text": " Example of paranthesized line break:"
},
{
"code": null,
"e": 1524,
"s": 1499,
"text": " list(\n \"Hello\"\n )"
},
{
"code": null,
"e": 1551,
"s": 1524,
"text": "This will give the output:"
},
{
"code": null,
"e": 1576,
"s": 1551,
"text": "['H', 'e','l', 'l', 'o']"
},
{
"code": null,
"e": 1613,
"s": 1576,
"text": " Example of back-slashed line break:"
},
{
"code": null,
"e": 1700,
"s": 1613,
"text": " print 'This s a really long line,', \\\n 'but we can make it across multiple lines.'"
},
{
"code": null,
"e": 1728,
"s": 1700,
"text": " This will give the output:"
},
{
"code": null,
"e": 1798,
"s": 1728,
"text": "This is a really long line, but we can make it across multiple lines."
},
{
"code": null,
"e": 1903,
"s": 1798,
"text": " Both of these can be used, you may choose to use either depending on which looks more readable to you. "
}
] |
Prolog - Towers of Hanoi Problem
|
Towers of Hanoi Problem is a famous puzzle to move N disks from the source peg/tower to the target peg/tower using the intermediate peg as an auxiliary holding peg. There are two conditions that are to be followed while solving this problem −
A larger disk cannot be placed on a smaller disk.
A larger disk cannot be placed on a smaller disk.
Only one disk can be moved at a time.
Only one disk can be moved at a time.
The following diagram depicts the starting setup for N=3 disks.
To solve this, we have to write one procedure move(N, Source, Target, auxiliary). Here N number of disks will have to be shifted from Source peg to Target peg keeping Auxiliary peg as intermediate.
For example – move(3, source, target, auxiliary).
Move top disk from source to target
Move top disk from source to target
Move top disk from source to auxiliary
Move top disk from source to auxiliary
Move top disk from target to auxiliary
Move top disk from target to auxiliary
Move top disk from source to target
Move top disk from source to target
Move top disk from auxiliary to source
Move top disk from auxiliary to source
Move top disk from auxiliary to target
Move top disk from auxiliary to target
Move top disk from source to target
Move top disk from source to target
move(1,X,Y,_) :-
write('Move top disk from '), write(X), write(' to '), write(Y), nl.
move(N,X,Y,Z) :-
N>1,
M is N-1,
move(M,X,Z,Y),
move(1,X,Y,_),
move(M,Z,Y,X).
| ?- [towersofhanoi].
compiling D:/TP Prolog/Sample_Codes/towersofhanoi.pl for byte code...
D:/TP Prolog/Sample_Codes/towersofhanoi.pl compiled, 8 lines read - 1409 bytes written, 15 ms
yes
| ?- move(4,source,target,auxiliary).
Move top disk from source to auxiliary
Move top disk from source to target
Move top disk from auxiliary to target
Move top disk from source to auxiliary
Move top disk from target to source
Move top disk from target to auxiliary
Move top disk from source to auxiliary
Move top disk from source to target
Move top disk from auxiliary to target
Move top disk from auxiliary to source
Move top disk from target to source
Move top disk from auxiliary to target
Move top disk from source to auxiliary
Move top disk from source to target
Move top disk from auxiliary to target
true ?
(31 ms) yes
65 Lectures
5 hours
Arnab Chakraborty
78 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2335,
"s": 2092,
"text": "Towers of Hanoi Problem is a famous puzzle to move N disks from the source peg/tower to the target peg/tower using the intermediate peg as an auxiliary holding peg. There are two conditions that are to be followed while solving this problem −"
},
{
"code": null,
"e": 2385,
"s": 2335,
"text": "A larger disk cannot be placed on a smaller disk."
},
{
"code": null,
"e": 2435,
"s": 2385,
"text": "A larger disk cannot be placed on a smaller disk."
},
{
"code": null,
"e": 2473,
"s": 2435,
"text": "Only one disk can be moved at a time."
},
{
"code": null,
"e": 2511,
"s": 2473,
"text": "Only one disk can be moved at a time."
},
{
"code": null,
"e": 2575,
"s": 2511,
"text": "The following diagram depicts the starting setup for N=3 disks."
},
{
"code": null,
"e": 2773,
"s": 2575,
"text": "To solve this, we have to write one procedure move(N, Source, Target, auxiliary). Here N number of disks will have to be shifted from Source peg to Target peg keeping Auxiliary peg as intermediate."
},
{
"code": null,
"e": 2823,
"s": 2773,
"text": "For example – move(3, source, target, auxiliary)."
},
{
"code": null,
"e": 2859,
"s": 2823,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 2895,
"s": 2859,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 2934,
"s": 2895,
"text": "Move top disk from source to auxiliary"
},
{
"code": null,
"e": 2973,
"s": 2934,
"text": "Move top disk from source to auxiliary"
},
{
"code": null,
"e": 3012,
"s": 2973,
"text": "Move top disk from target to auxiliary"
},
{
"code": null,
"e": 3051,
"s": 3012,
"text": "Move top disk from target to auxiliary"
},
{
"code": null,
"e": 3087,
"s": 3051,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 3123,
"s": 3087,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 3162,
"s": 3123,
"text": "Move top disk from auxiliary to source"
},
{
"code": null,
"e": 3201,
"s": 3162,
"text": "Move top disk from auxiliary to source"
},
{
"code": null,
"e": 3240,
"s": 3201,
"text": "Move top disk from auxiliary to target"
},
{
"code": null,
"e": 3279,
"s": 3240,
"text": "Move top disk from auxiliary to target"
},
{
"code": null,
"e": 3315,
"s": 3279,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 3351,
"s": 3315,
"text": "Move top disk from source to target"
},
{
"code": null,
"e": 3532,
"s": 3351,
"text": "move(1,X,Y,_) :-\n write('Move top disk from '), write(X), write(' to '), write(Y), nl.\nmove(N,X,Y,Z) :-\n N>1,\n M is N-1,\n move(M,X,Z,Y),\n move(1,X,Y,_),\n move(M,Z,Y,X)."
},
{
"code": null,
"e": 4353,
"s": 3532,
"text": "| ?- [towersofhanoi].\ncompiling D:/TP Prolog/Sample_Codes/towersofhanoi.pl for byte code...\nD:/TP Prolog/Sample_Codes/towersofhanoi.pl compiled, 8 lines read - 1409 bytes written, 15 ms\n\nyes\n| ?- move(4,source,target,auxiliary).\nMove top disk from source to auxiliary\nMove top disk from source to target\nMove top disk from auxiliary to target\nMove top disk from source to auxiliary\nMove top disk from target to source\nMove top disk from target to auxiliary\nMove top disk from source to auxiliary\nMove top disk from source to target\nMove top disk from auxiliary to target\nMove top disk from auxiliary to source\nMove top disk from target to source\nMove top disk from auxiliary to target\nMove top disk from source to auxiliary\nMove top disk from source to target\nMove top disk from auxiliary to target\n\ntrue ?\n\n(31 ms) yes\n"
},
{
"code": null,
"e": 4386,
"s": 4353,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4405,
"s": 4386,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4438,
"s": 4405,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4457,
"s": 4438,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4464,
"s": 4457,
"text": " Print"
},
{
"code": null,
"e": 4475,
"s": 4464,
"text": " Add Notes"
}
] |
Cucumber - Data Tables
|
While working on automation, we may face variety of scenarios. Each scenario carries a different meaning and needs.
Since the beginning, we have been taking an example of login functionality for a social networking site, where we just had two input parameters to be passed. Let’s think of some more possibility. How about “New user registration” functionality? Typically, what can be the input parameters while registering a new user for a social networking site? Something like the following −
User Name
Email Address
Password
Re-enter password
Birthdate
Gender
Phone number
Feature − New user registration.
Verify that the new user registration is unsuccessful after passing the incorrect inputs.
Given I am on a new user registration page.
When I enter the user name and an e-mail address as email address and password as, and re-enter password as and Birthdate as and Gender as and phone number as then the user registration should be unsuccessful.
It looks a bit messy at first glance. So, is there any better way to manage such chunk of inputs? Answer can be “Data Table”. Data table is a set of input to be provided for a single tag. This tag can be GIVEN, WHEN, or THEN.
Let’s write the above scenario with the help of data table and it will look like the following −
Given I am on a new user registration page
When I enter valid data on the page
| Fields | Values |
| First Name | Tom |
| Last Name | Kenny |
| Email Address | someone@someone.com |
| Re-enter Email Address | someone@someone.com |
| Password | Password1 |
| Birthdate | 01 |
Then the user registration should be successful.
Let’s automate an example of a data table.
Step 1 − Create a Maven Test Project named “DataTableTest”.
Go to File → New → Others → Maven → Maven Project → Next.
Go to File → New → Others → Maven → Maven Project → Next.
Provide group Id (group Id will identify your project uniquely across all projects).
Provide group Id (group Id will identify your project uniquely across all projects).
Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name which is in lowercase).
Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name which is in lowercase).
Click on Finish.
Click on Finish.
Open pom.xml −
Go to package explorer on the left hand side of Eclipse.
Expand the project CucumberTest.
Locate pom.xml file.
Right-click and select the option, Open with “Text Editor”.
Open pom.xml −
Go to package explorer on the left hand side of Eclipse.
Go to package explorer on the left hand side of Eclipse.
Expand the project CucumberTest.
Expand the project CucumberTest.
Locate pom.xml file.
Locate pom.xml file.
Right-click and select the option, Open with “Text Editor”.
Right-click and select the option, Open with “Text Editor”.
Add dependency for Selenium: This will indicate Maven, which Selenium jar files are to be downloaded from the central repository to the local repository.
Open pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag.
Inside the dependencies tag, create dependency tag. (<dependency></dependency>).
Provide the following information within the dependency tag.
Add dependency for Selenium: This will indicate Maven, which Selenium jar files are to be downloaded from the central repository to the local repository.
Open pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag.
Open pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag.
Inside the dependencies tag, create dependency tag. (<dependency></dependency>).
Inside the dependencies tag, create dependency tag. (<dependency></dependency>).
Provide the following information within the dependency tag.
Provide the following information within the dependency tag.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.47.1</version>
</dependency>
Add dependency for Cucumber-Java − This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository.
Create one more dependency tag.
Provide the following information within the dependency tag.
Add dependency for Cucumber-Java − This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository.
Create one more dependency tag.
Create one more dependency tag.
Provide the following information within the dependency tag.
Provide the following information within the dependency tag.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for Cucumber-JUnit − This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository.
Create one more dependency tag.
Provide the following information within the dependency tag.
Add dependency for Cucumber-JUnit − This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository.
Create one more dependency tag.
Create one more dependency tag.
Provide the following information within the dependency tag.
Provide the following information within the dependency tag.
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.0.2</version>
<scope>test</scope>
</dependency>
Add dependency for JUnit − This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository.
Create one more dependency tag.
Provide the following information within the dependency tag
Add dependency for JUnit − This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository.
Create one more dependency tag.
Create one more dependency tag.
Provide the following information within the dependency tag
Provide the following information within the dependency tag
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
Verify binaries.
Once pom.xml is edited successfully, save it.
Go to Project → Clean − It will take a few minutes.
Verify binaries.
Once pom.xml is edited successfully, save it.
Once pom.xml is edited successfully, save it.
Go to Project → Clean − It will take a few minutes.
Go to Project → Clean − It will take a few minutes.
Step 2 − Create a package named dataTable under src/test/java
Step 3 − Create a Feature file.
Create a feature file, named as dataTable.feature inside the package dataTable (see section scenario outline for more detailed steps).
Create a feature file, named as dataTable.feature inside the package dataTable (see section scenario outline for more detailed steps).
Write the following text.
Feature − Data table
Verify that the new user registration is unsuccessful after passing incorrect inputs.
Scenario:
Given I am on the new user registration page
When I enter invalid data on the page
Write the following text.
Feature − Data table
Verify that the new user registration is unsuccessful after passing incorrect inputs.
Scenario:
Given I am on the new user registration page
When I enter invalid data on the page
| Fields | Values |
| First Name | Tom |
| Last Name | Kenny |
| Email Address | someone@someone.com |
| Re-enter Email Address | someone@someone.com |
| Password | Password1 |
| Birthdate | 01 |
Then the user registration should be unsuccessful
Save the file.
Save the file.
Step 4 − Create step definition file.
Create the step definition file named as ‘dataTable.java’ inside the package dataTable (see section scenario outline for more detailed steps).
Create the step definition file named as ‘dataTable.java’ inside the package dataTable (see section scenario outline for more detailed steps).
Write the following code.
Write the following code.
package dataTable;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.table.DataTable;
public class stepdefinition {
WebDriver driver = null;
@Given("^I am on new user registration page$")
public void goToFacebook() {
//Intiate web browser instance. driver = new FirefoxDriver();
driver.navigate().to("https://www.facebook.com/");
}
@When("^I enter invalid data on the page$")
public void enterData(DataTable table){
//Initialize data table
List<list> data = table.raw();
System.out.println(data.get(1).get(1));
//Enter data
driver.findElement(By.name("firstname")).sendKeys(data.get(1).get(1));
driver.findElement(By.name("lastname")).sendKeys(data.get(2).get(1));
driver.findElement(By.name("reg_email__")).sendKeys(data.get(3).get(1));
driver.findElement(By.name("reg_email_confirmation__")).
sendKeys(data.get(4).get(1));
driver.findElement(By.name("reg_passwd__")).sendKeys(data.get(5).get(1));
Select dropdownB = new Select(driver.findElement(By.name("birthday_day")));
dropdownB.selectByValue("15");
Select dropdownM = new Select(driver.findElement(By.name("birthday_month")));
dropdownM.selectByValue("6");
Select dropdownY = new Select(driver.findElement(By.name("birthday_year")));
dropdownY.selectByValue("1990");
driver.findElement(By.className("_58mt")).click();
// Click submit button driver.findElement(By.name("websubmit")).click();
}
@Then("^User registration should be unsuccessful$")
public void User_registration_should_be_unsuccessful() {
if(driver.getCurrentUrl().equalsIgnoreCase("https://www.facebook.com/")){
System.out.println("Test Pass");
} else {
System.out.println("Test Failed");
}
driver.close();
}
}
Save the file.
Save the file.
Step 5 − Create a runner class file.
Create runner class named as runTest.java inside the package.
Create runner class named as runTest.java inside the package.
Write the following code.
Write the following code.
package dataTable;
import org.junit.runner.RunWith;
import cucumber.junit.Cucumber;
@RunWith(Cucumber.class)
@Cucumber.Options(format = {"pretty", "html:target/cucumber"})
public class runTest { }
Save the file.
Save the file.
Run the test using the option
Select runTest.java file from the package explorer.
Right-click and select the option, Run as.
Select JUnit test.
Run the test using the option
Select runTest.java file from the package explorer.
Select runTest.java file from the package explorer.
Right-click and select the option, Run as.
Right-click and select the option, Run as.
Select JUnit test.
Select JUnit test.
You may observe the following things upon successful execution.
Facebook website gets loaded.
Facebook website gets loaded.
Data will be entered on the registration page.
Data will be entered on the registration page.
Submit button will be clicked.
Submit button will be clicked.
We will see that home page will not displayed and “Test Pass” will be written on the console.
We will see that home page will not displayed and “Test Pass” will be written on the console.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2078,
"s": 1962,
"text": "While working on automation, we may face variety of scenarios. Each scenario carries a different meaning and needs."
},
{
"code": null,
"e": 2457,
"s": 2078,
"text": "Since the beginning, we have been taking an example of login functionality for a social networking site, where we just had two input parameters to be passed. Let’s think of some more possibility. How about “New user registration” functionality? Typically, what can be the input parameters while registering a new user for a social networking site? Something like the following −"
},
{
"code": null,
"e": 2467,
"s": 2457,
"text": "User Name"
},
{
"code": null,
"e": 2481,
"s": 2467,
"text": "Email Address"
},
{
"code": null,
"e": 2490,
"s": 2481,
"text": "Password"
},
{
"code": null,
"e": 2508,
"s": 2490,
"text": "Re-enter password"
},
{
"code": null,
"e": 2518,
"s": 2508,
"text": "Birthdate"
},
{
"code": null,
"e": 2525,
"s": 2518,
"text": "Gender"
},
{
"code": null,
"e": 2538,
"s": 2525,
"text": "Phone number"
},
{
"code": null,
"e": 2571,
"s": 2538,
"text": "Feature − New user registration."
},
{
"code": null,
"e": 2661,
"s": 2571,
"text": "Verify that the new user registration is unsuccessful after passing the incorrect inputs."
},
{
"code": null,
"e": 2705,
"s": 2661,
"text": "Given I am on a new user registration page."
},
{
"code": null,
"e": 2915,
"s": 2705,
"text": "When I enter the user name and an e-mail address as email address and password as, and re-enter password as and Birthdate as and Gender as and phone number as then the user registration should be unsuccessful."
},
{
"code": null,
"e": 3141,
"s": 2915,
"text": "It looks a bit messy at first glance. So, is there any better way to manage such chunk of inputs? Answer can be “Data Table”. Data table is a set of input to be provided for a single tag. This tag can be GIVEN, WHEN, or THEN."
},
{
"code": null,
"e": 3238,
"s": 3141,
"text": "Let’s write the above scenario with the help of data table and it will look like the following −"
},
{
"code": null,
"e": 3281,
"s": 3238,
"text": "Given I am on a new user registration page"
},
{
"code": null,
"e": 3317,
"s": 3281,
"text": "When I enter valid data on the page"
},
{
"code": null,
"e": 3661,
"s": 3317,
"text": "| Fields | Values |\n| First Name | Tom |\n| Last Name | Kenny |\n| Email Address | someone@someone.com |\n| Re-enter Email Address | someone@someone.com |\n| Password | Password1 |\n| Birthdate | 01 |\n"
},
{
"code": null,
"e": 3710,
"s": 3661,
"text": "Then the user registration should be successful."
},
{
"code": null,
"e": 3753,
"s": 3710,
"text": "Let’s automate an example of a data table."
},
{
"code": null,
"e": 3813,
"s": 3753,
"text": "Step 1 − Create a Maven Test Project named “DataTableTest”."
},
{
"code": null,
"e": 3871,
"s": 3813,
"text": "Go to File → New → Others → Maven → Maven Project → Next."
},
{
"code": null,
"e": 3929,
"s": 3871,
"text": "Go to File → New → Others → Maven → Maven Project → Next."
},
{
"code": null,
"e": 4014,
"s": 3929,
"text": "Provide group Id (group Id will identify your project uniquely across all projects)."
},
{
"code": null,
"e": 4099,
"s": 4014,
"text": "Provide group Id (group Id will identify your project uniquely across all projects)."
},
{
"code": null,
"e": 4220,
"s": 4099,
"text": "Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name which is in lowercase)."
},
{
"code": null,
"e": 4341,
"s": 4220,
"text": "Provide artifact Id (artifact Id is the name of the jar without version. You can choose any name which is in lowercase)."
},
{
"code": null,
"e": 4358,
"s": 4341,
"text": "Click on Finish."
},
{
"code": null,
"e": 4375,
"s": 4358,
"text": "Click on Finish."
},
{
"code": null,
"e": 4563,
"s": 4375,
"text": "Open pom.xml −\n\nGo to package explorer on the left hand side of Eclipse.\nExpand the project CucumberTest.\nLocate pom.xml file.\nRight-click and select the option, Open with “Text Editor”.\n"
},
{
"code": null,
"e": 4578,
"s": 4563,
"text": "Open pom.xml −"
},
{
"code": null,
"e": 4635,
"s": 4578,
"text": "Go to package explorer on the left hand side of Eclipse."
},
{
"code": null,
"e": 4692,
"s": 4635,
"text": "Go to package explorer on the left hand side of Eclipse."
},
{
"code": null,
"e": 4725,
"s": 4692,
"text": "Expand the project CucumberTest."
},
{
"code": null,
"e": 4758,
"s": 4725,
"text": "Expand the project CucumberTest."
},
{
"code": null,
"e": 4779,
"s": 4758,
"text": "Locate pom.xml file."
},
{
"code": null,
"e": 4800,
"s": 4779,
"text": "Locate pom.xml file."
},
{
"code": null,
"e": 4860,
"s": 4800,
"text": "Right-click and select the option, Open with “Text Editor”."
},
{
"code": null,
"e": 4920,
"s": 4860,
"text": "Right-click and select the option, Open with “Text Editor”."
},
{
"code": null,
"e": 5328,
"s": 4920,
"text": "Add dependency for Selenium: This will indicate Maven, which Selenium jar files are to be downloaded from the central repository to the local repository.\n\nOpen pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag.\nInside the dependencies tag, create dependency tag. (<dependency></dependency>).\nProvide the following information within the dependency tag."
},
{
"code": null,
"e": 5482,
"s": 5328,
"text": "Add dependency for Selenium: This will indicate Maven, which Selenium jar files are to be downloaded from the central repository to the local repository."
},
{
"code": null,
"e": 5593,
"s": 5482,
"text": "Open pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag."
},
{
"code": null,
"e": 5704,
"s": 5593,
"text": "Open pom.xml is in edit mode, create dependencies tag (<dependencies></dependencies>), inside the project tag."
},
{
"code": null,
"e": 5785,
"s": 5704,
"text": "Inside the dependencies tag, create dependency tag. (<dependency></dependency>)."
},
{
"code": null,
"e": 5866,
"s": 5785,
"text": "Inside the dependencies tag, create dependency tag. (<dependency></dependency>)."
},
{
"code": null,
"e": 5927,
"s": 5866,
"text": "Provide the following information within the dependency tag."
},
{
"code": null,
"e": 5988,
"s": 5927,
"text": "Provide the following information within the dependency tag."
},
{
"code": null,
"e": 6136,
"s": 5988,
"text": "<dependency> \n <groupId>org.seleniumhq.selenium</groupId> \n <artifactId>selenium-java</artifactId> \n <version>2.47.1</version> \n</dependency>"
},
{
"code": null,
"e": 6387,
"s": 6136,
"text": "Add dependency for Cucumber-Java − This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository.\n\nCreate one more dependency tag.\nProvide the following information within the dependency tag.\n"
},
{
"code": null,
"e": 6543,
"s": 6387,
"text": "Add dependency for Cucumber-Java − This will indicate Maven, which Cucumber files are to be downloaded from the central repository to the local repository."
},
{
"code": null,
"e": 6575,
"s": 6543,
"text": "Create one more dependency tag."
},
{
"code": null,
"e": 6607,
"s": 6575,
"text": "Create one more dependency tag."
},
{
"code": null,
"e": 6668,
"s": 6607,
"text": "Provide the following information within the dependency tag."
},
{
"code": null,
"e": 6729,
"s": 6668,
"text": "Provide the following information within the dependency tag."
},
{
"code": null,
"e": 6887,
"s": 6729,
"text": "<dependency> \n <groupId>info.cukes</groupId> \n <artifactId>cucumber-java</artifactId> \n <version>1.0.2</version> \n <scope>test</scope> \n</dependency>"
},
{
"code": null,
"e": 7145,
"s": 6887,
"text": "Add dependency for Cucumber-JUnit − This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository.\n\nCreate one more dependency tag.\nProvide the following information within the dependency tag.\n"
},
{
"code": null,
"e": 7308,
"s": 7145,
"text": "Add dependency for Cucumber-JUnit − This will indicate Maven, which Cucumber JUnit files are to be downloaded from the central repository to the local repository."
},
{
"code": null,
"e": 7340,
"s": 7308,
"text": "Create one more dependency tag."
},
{
"code": null,
"e": 7372,
"s": 7340,
"text": "Create one more dependency tag."
},
{
"code": null,
"e": 7433,
"s": 7372,
"text": "Provide the following information within the dependency tag."
},
{
"code": null,
"e": 7494,
"s": 7433,
"text": "Provide the following information within the dependency tag."
},
{
"code": null,
"e": 7653,
"s": 7494,
"text": "<dependency> \n <groupId>info.cukes</groupId> \n <artifactId>cucumber-junit</artifactId> \n <version>1.0.2</version> \n <scope>test</scope> \n</dependency>"
},
{
"code": null,
"e": 7892,
"s": 7653,
"text": "Add dependency for JUnit − This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository.\n\nCreate one more dependency tag.\nProvide the following information within the dependency tag\n"
},
{
"code": null,
"e": 8037,
"s": 7892,
"text": "Add dependency for JUnit − This will indicate Maven, which JUnit files are to be downloaded from the central repository to the local repository."
},
{
"code": null,
"e": 8069,
"s": 8037,
"text": "Create one more dependency tag."
},
{
"code": null,
"e": 8101,
"s": 8069,
"text": "Create one more dependency tag."
},
{
"code": null,
"e": 8161,
"s": 8101,
"text": "Provide the following information within the dependency tag"
},
{
"code": null,
"e": 8221,
"s": 8161,
"text": "Provide the following information within the dependency tag"
},
{
"code": null,
"e": 8365,
"s": 8221,
"text": "<dependency> \n <groupId>junit</groupId> \n <artifactId>junit</artifactId> \n <version>4.10</version> \n <scope>test</scope> \n</dependency>"
},
{
"code": null,
"e": 8482,
"s": 8365,
"text": "Verify binaries.\n\nOnce pom.xml is edited successfully, save it.\nGo to Project → Clean − It will take a few minutes.\n"
},
{
"code": null,
"e": 8499,
"s": 8482,
"text": "Verify binaries."
},
{
"code": null,
"e": 8545,
"s": 8499,
"text": "Once pom.xml is edited successfully, save it."
},
{
"code": null,
"e": 8591,
"s": 8545,
"text": "Once pom.xml is edited successfully, save it."
},
{
"code": null,
"e": 8643,
"s": 8591,
"text": "Go to Project → Clean − It will take a few minutes."
},
{
"code": null,
"e": 8695,
"s": 8643,
"text": "Go to Project → Clean − It will take a few minutes."
},
{
"code": null,
"e": 8757,
"s": 8695,
"text": "Step 2 − Create a package named dataTable under src/test/java"
},
{
"code": null,
"e": 8789,
"s": 8757,
"text": "Step 3 − Create a Feature file."
},
{
"code": null,
"e": 8924,
"s": 8789,
"text": "Create a feature file, named as dataTable.feature inside the package dataTable (see section scenario outline for more detailed steps)."
},
{
"code": null,
"e": 9059,
"s": 8924,
"text": "Create a feature file, named as dataTable.feature inside the package dataTable (see section scenario outline for more detailed steps)."
},
{
"code": null,
"e": 9286,
"s": 9059,
"text": "Write the following text.\nFeature − Data table\nVerify that the new user registration is unsuccessful after passing incorrect inputs.\nScenario:\nGiven I am on the new user registration page\nWhen I enter invalid data on the page\n"
},
{
"code": null,
"e": 9312,
"s": 9286,
"text": "Write the following text."
},
{
"code": null,
"e": 9333,
"s": 9312,
"text": "Feature − Data table"
},
{
"code": null,
"e": 9419,
"s": 9333,
"text": "Verify that the new user registration is unsuccessful after passing incorrect inputs."
},
{
"code": null,
"e": 9429,
"s": 9419,
"text": "Scenario:"
},
{
"code": null,
"e": 9474,
"s": 9429,
"text": "Given I am on the new user registration page"
},
{
"code": null,
"e": 9512,
"s": 9474,
"text": "When I enter invalid data on the page"
},
{
"code": null,
"e": 9856,
"s": 9512,
"text": "| Fields | Values |\n| First Name | Tom |\n| Last Name | Kenny |\n| Email Address | someone@someone.com |\n| Re-enter Email Address | someone@someone.com |\n| Password | Password1 |\n| Birthdate | 01 |\n"
},
{
"code": null,
"e": 9906,
"s": 9856,
"text": "Then the user registration should be unsuccessful"
},
{
"code": null,
"e": 9921,
"s": 9906,
"text": "Save the file."
},
{
"code": null,
"e": 9936,
"s": 9921,
"text": "Save the file."
},
{
"code": null,
"e": 9974,
"s": 9936,
"text": "Step 4 − Create step definition file."
},
{
"code": null,
"e": 10117,
"s": 9974,
"text": "Create the step definition file named as ‘dataTable.java’ inside the package dataTable (see section scenario outline for more detailed steps)."
},
{
"code": null,
"e": 10260,
"s": 10117,
"text": "Create the step definition file named as ‘dataTable.java’ inside the package dataTable (see section scenario outline for more detailed steps)."
},
{
"code": null,
"e": 10286,
"s": 10260,
"text": "Write the following code."
},
{
"code": null,
"e": 10312,
"s": 10286,
"text": "Write the following code."
},
{
"code": null,
"e": 12514,
"s": 10312,
"text": "package dataTable; \n\nimport java.util.List; \n\nimport org.openqa.selenium.By; \nimport org.openqa.selenium.WebDriver; \nimport org.openqa.selenium.WebElement; \nimport org.openqa.selenium.firefox.FirefoxDriver; \nimport org.openqa.selenium.support.ui.Select;\n\nimport cucumber.annotation.en.Given; \nimport cucumber.annotation.en.Then; \nimport cucumber.annotation.en.When; \nimport cucumber.table.DataTable; \n\npublic class stepdefinition { \n WebDriver driver = null;\n\t\n @Given(\"^I am on new user registration page$\") \n public void goToFacebook() { \n //Intiate web browser instance. driver = new FirefoxDriver();\n driver.navigate().to(\"https://www.facebook.com/\"); \n } \n\t\n @When(\"^I enter invalid data on the page$\") \n public void enterData(DataTable table){ \n //Initialize data table \n List<list> data = table.raw();\n System.out.println(data.get(1).get(1)); \n \n //Enter data\n driver.findElement(By.name(\"firstname\")).sendKeys(data.get(1).get(1));\n driver.findElement(By.name(\"lastname\")).sendKeys(data.get(2).get(1));\n driver.findElement(By.name(\"reg_email__\")).sendKeys(data.get(3).get(1)); \n driver.findElement(By.name(\"reg_email_confirmation__\")).\n sendKeys(data.get(4).get(1)); \n driver.findElement(By.name(\"reg_passwd__\")).sendKeys(data.get(5).get(1)); \n \n Select dropdownB = new Select(driver.findElement(By.name(\"birthday_day\"))); \n dropdownB.selectByValue(\"15\"); \n\t\t\n Select dropdownM = new Select(driver.findElement(By.name(\"birthday_month\")));\n dropdownM.selectByValue(\"6\"); \n\t\t\n Select dropdownY = new Select(driver.findElement(By.name(\"birthday_year\")));\n dropdownY.selectByValue(\"1990\"); \n\t\t\n driver.findElement(By.className(\"_58mt\")).click(); \n // Click submit button driver.findElement(By.name(\"websubmit\")).click(); \n } \n\t\n @Then(\"^User registration should be unsuccessful$\") \n public void User_registration_should_be_unsuccessful() {\n if(driver.getCurrentUrl().equalsIgnoreCase(\"https://www.facebook.com/\")){\n System.out.println(\"Test Pass\"); \n } else { \n System.out.println(\"Test Failed\"); \n } \n driver.close(); \n } \n}"
},
{
"code": null,
"e": 12529,
"s": 12514,
"text": "Save the file."
},
{
"code": null,
"e": 12544,
"s": 12529,
"text": "Save the file."
},
{
"code": null,
"e": 12581,
"s": 12544,
"text": "Step 5 − Create a runner class file."
},
{
"code": null,
"e": 12643,
"s": 12581,
"text": "Create runner class named as runTest.java inside the package."
},
{
"code": null,
"e": 12705,
"s": 12643,
"text": "Create runner class named as runTest.java inside the package."
},
{
"code": null,
"e": 12731,
"s": 12705,
"text": "Write the following code."
},
{
"code": null,
"e": 12757,
"s": 12731,
"text": "Write the following code."
},
{
"code": null,
"e": 12962,
"s": 12757,
"text": "package dataTable; \n\nimport org.junit.runner.RunWith; \nimport cucumber.junit.Cucumber; \n\n@RunWith(Cucumber.class) \n@Cucumber.Options(format = {\"pretty\", \"html:target/cucumber\"})\n \npublic class runTest { }"
},
{
"code": null,
"e": 12977,
"s": 12962,
"text": "Save the file."
},
{
"code": null,
"e": 12992,
"s": 12977,
"text": "Save the file."
},
{
"code": null,
"e": 13138,
"s": 12992,
"text": "Run the test using the option\n\nSelect runTest.java file from the package explorer.\nRight-click and select the option, Run as.\nSelect JUnit test.\n"
},
{
"code": null,
"e": 13168,
"s": 13138,
"text": "Run the test using the option"
},
{
"code": null,
"e": 13220,
"s": 13168,
"text": "Select runTest.java file from the package explorer."
},
{
"code": null,
"e": 13272,
"s": 13220,
"text": "Select runTest.java file from the package explorer."
},
{
"code": null,
"e": 13315,
"s": 13272,
"text": "Right-click and select the option, Run as."
},
{
"code": null,
"e": 13358,
"s": 13315,
"text": "Right-click and select the option, Run as."
},
{
"code": null,
"e": 13377,
"s": 13358,
"text": "Select JUnit test."
},
{
"code": null,
"e": 13396,
"s": 13377,
"text": "Select JUnit test."
},
{
"code": null,
"e": 13460,
"s": 13396,
"text": "You may observe the following things upon successful execution."
},
{
"code": null,
"e": 13490,
"s": 13460,
"text": "Facebook website gets loaded."
},
{
"code": null,
"e": 13520,
"s": 13490,
"text": "Facebook website gets loaded."
},
{
"code": null,
"e": 13567,
"s": 13520,
"text": "Data will be entered on the registration page."
},
{
"code": null,
"e": 13614,
"s": 13567,
"text": "Data will be entered on the registration page."
},
{
"code": null,
"e": 13645,
"s": 13614,
"text": "Submit button will be clicked."
},
{
"code": null,
"e": 13676,
"s": 13645,
"text": "Submit button will be clicked."
},
{
"code": null,
"e": 13770,
"s": 13676,
"text": "We will see that home page will not displayed and “Test Pass” will be written on the console."
},
{
"code": null,
"e": 13864,
"s": 13770,
"text": "We will see that home page will not displayed and “Test Pass” will be written on the console."
},
{
"code": null,
"e": 13871,
"s": 13864,
"text": " Print"
},
{
"code": null,
"e": 13882,
"s": 13871,
"text": " Add Notes"
}
] |
How animate(), hide and show elements using jQuery?
|
Use the hide() and show() method with animate() to hide and show elements.
You can try to run the following code to learn how to work with animate() method to hide and show elements:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("#box").animate({height: "300px"}, 500, function() {
$(this).hide();
});
});
$("#btn2").click(function(){
$("#box").animate({height: "300px"}, 500, function() {
$(this).show();
});
});
});
</script>
</head>
<body>
<button id="btn1">Hide</button>
<button id="btn2">Show</button>
<div id="box" style="background:#000000;height:300px;width:100px;margin:10px;"></div>
</body>
</html>
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "Use the hide() and show() method with animate() to hide and show elements."
},
{
"code": null,
"e": 1245,
"s": 1137,
"text": "You can try to run the following code to learn how to work with animate() method to hide and show elements:"
},
{
"code": null,
"e": 1255,
"s": 1245,
"text": "Live Demo"
},
{
"code": null,
"e": 1896,
"s": 1255,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"#btn1\").click(function(){\n $(\"#box\").animate({height: \"300px\"}, 500, function() {\n $(this).hide();\n });\n });\n $(\"#btn2\").click(function(){\n $(\"#box\").animate({height: \"300px\"}, 500, function() {\n $(this).show();\n });\n });\n});\n</script>\n</head>\n<body>\n\n<button id=\"btn1\">Hide</button>\n<button id=\"btn2\">Show</button>\n\n<div id=\"box\" style=\"background:#000000;height:300px;width:100px;margin:10px;\"></div>\n\n</body>\n</html>"
}
] |
Split the array into equal sum parts according to given conditions in C++
|
Here we will see one problem. Suppose one array arr is given. We have to check whether the array can be split into two parts, such that −
Sub of both sub-arrays will be the same
All elements, which are multiple of 5, will be in the same group
All elements which are multiple of 3, but not multiple of 5, will be in the same group
All other elements will be in other groups.
Suppose the array elements are {1, 4, 3}, then this can be split, because the sum of {1, 3} is the same as the sum of {4}, and the groups are also correct for the given condition.
isSplitArray(arr, n, start, left_sum, right_sum) −
Begin
if start = n, then return true when left_sum = right_sum, otherwise false
if arr[start] is divisible by 5, then add arr[start] with the left_sum
else if arr[start] is divisible by 3, then add arr[start] with the right_sum
else
return isSplitArray(arr, n, start + 1, left_sum + arr[start], right_sum) OR isSplitArray(arr, n, start + 1, left_sum, right_sum + arr[start])
isSplitArray(arr, n, start + 1, left_sum, right_sum)
End
Live Demo
#include <iostream>
using namespace std;
bool isSplitArray(int* arr, int n, int start, int left_sum, int right_sum) {
if (start == n) //when it reaches at the end
return left_sum == right_sum;
if (arr[start] % 5 == 0) //when the element is divisible by 5, add to left sum
left_sum += arr[start];
else if (arr[start] % 3 == 0) //when the element is divisible by 3 but not 5, add to right sum
right_sum += arr[start];
else // otherwise it can be added to any of the sub-arrays
return isSplitArray(arr, n, start + 1, left_sum + arr[start], right_sum) || isSplitArray(arr, n, start + 1, left_sum, right_sum + arr[start]);
// For cases when element is multiple of 3 or 5.
return isSplitArray(arr, n, start + 1, left_sum, right_sum);
}
int main() {
int arr[] = {1, 4, 3};
int n = sizeof(arr)/sizeof(arr[0]);
if(isSplitArray(arr, n, 0, 0, 0)){
cout <<"Can be split";
} else {
cout <<"Can not be split";
}
}
Can be split
|
[
{
"code": null,
"e": 1200,
"s": 1062,
"text": "Here we will see one problem. Suppose one array arr is given. We have to check whether the array can be split into two parts, such that −"
},
{
"code": null,
"e": 1240,
"s": 1200,
"text": "Sub of both sub-arrays will be the same"
},
{
"code": null,
"e": 1305,
"s": 1240,
"text": "All elements, which are multiple of 5, will be in the same group"
},
{
"code": null,
"e": 1392,
"s": 1305,
"text": "All elements which are multiple of 3, but not multiple of 5, will be in the same group"
},
{
"code": null,
"e": 1436,
"s": 1392,
"text": "All other elements will be in other groups."
},
{
"code": null,
"e": 1616,
"s": 1436,
"text": "Suppose the array elements are {1, 4, 3}, then this can be split, because the sum of {1, 3} is the same as the sum of {4}, and the groups are also correct for the given condition."
},
{
"code": null,
"e": 1667,
"s": 1616,
"text": "isSplitArray(arr, n, start, left_sum, right_sum) −"
},
{
"code": null,
"e": 2120,
"s": 1667,
"text": "Begin\n if start = n, then return true when left_sum = right_sum, otherwise false\n if arr[start] is divisible by 5, then add arr[start] with the left_sum\n else if arr[start] is divisible by 3, then add arr[start] with the right_sum\n else\n return isSplitArray(arr, n, start + 1, left_sum + arr[start], right_sum) OR isSplitArray(arr, n, start + 1, left_sum, right_sum + arr[start])\n isSplitArray(arr, n, start + 1, left_sum, right_sum)\nEnd"
},
{
"code": null,
"e": 2131,
"s": 2120,
"text": " Live Demo"
},
{
"code": null,
"e": 3106,
"s": 2131,
"text": "#include <iostream>\nusing namespace std;\nbool isSplitArray(int* arr, int n, int start, int left_sum, int right_sum) {\n if (start == n) //when it reaches at the end\n return left_sum == right_sum;\n if (arr[start] % 5 == 0) //when the element is divisible by 5, add to left sum\n left_sum += arr[start];\n else if (arr[start] % 3 == 0) //when the element is divisible by 3 but not 5, add to right sum\n right_sum += arr[start];\n else // otherwise it can be added to any of the sub-arrays\n return isSplitArray(arr, n, start + 1, left_sum + arr[start], right_sum) || isSplitArray(arr, n, start + 1, left_sum, right_sum + arr[start]);\n // For cases when element is multiple of 3 or 5.\n return isSplitArray(arr, n, start + 1, left_sum, right_sum);\n}\nint main() {\n int arr[] = {1, 4, 3};\n int n = sizeof(arr)/sizeof(arr[0]);\n if(isSplitArray(arr, n, 0, 0, 0)){\n cout <<\"Can be split\";\n } else {\n cout <<\"Can not be split\";\n }\n}"
},
{
"code": null,
"e": 3119,
"s": 3106,
"text": "Can be split"
}
] |
Program to find maximum in generated array in Python
|
Suppose we have a number n. We have to generate an array A of length n + 1 in the following way −
A[0] = 0
A[0] = 0
A[1] = 1
A[1] = 1
A[2 * i] = A[i] if 2 <= 2 * i <= n
A[2 * i] = A[i] if 2 <= 2 * i <= n
A[2 * i + 1] = A[i] + A[i + 1] if 2 <= 2 * i + 1 <= n
A[2 * i + 1] = A[i] + A[i + 1] if 2 <= 2 * i + 1 <= n
Finally we have to find the maximum number in the array nums.
So, if the input is like n = 5, then the output will be 3 because
A[0] = 0
A[0] = 0
A[1] = 1
A[1] = 1
A[2] = A[1] = 1
A[2] = A[1] = 1
A[3] = A[1] + A[2] = 1 + 1 = 2
A[3] = A[1] + A[2] = 1 + 1 = 2
A[4] = A[2]= 1
A[4] = A[2]= 1
A[5] = A[2] + A[3] = 1 + 2 = 3
A[5] = A[2] + A[3] = 1 + 2 = 3
A[6] = A[3] = 2
A[6] = A[3] = 2
So the maximum is 3
To solve this, we will follow these steps −
A := a new list from 0 to n
A := a new list from 0 to n
for each element i in A, doif i is same as 0 or i is same as 1, thengo to next iterationotherwise when i is even, thenA[i] := A[integer of i/2]otherwise,A[i] := A[integer of i/2] + A[(integer of i/2) + 1]
for each element i in A, do
if i is same as 0 or i is same as 1, thengo to next iteration
if i is same as 0 or i is same as 1, then
go to next iteration
go to next iteration
otherwise when i is even, thenA[i] := A[integer of i/2]
otherwise when i is even, then
A[i] := A[integer of i/2]
A[i] := A[integer of i/2]
otherwise,A[i] := A[integer of i/2] + A[(integer of i/2) + 1]
otherwise,
A[i] := A[integer of i/2] + A[(integer of i/2) + 1]
A[i] := A[integer of i/2] + A[(integer of i/2) + 1]
return maximum element of A
return maximum element of A
Let us see the following implementation to get better understanding −
Live Demo
def solve(n):
A = list(range(0,n+1))
for i in A:
if i == 0 or i == 1:
continue
elif i%2 == 0:
A[i] = A[i//2]
else:
A[i] = A[i//2] + A[(i//2) + 1]
return max(A)
n = 5
print(solve(n))
5
3
|
[
{
"code": null,
"e": 1160,
"s": 1062,
"text": "Suppose we have a number n. We have to generate an array A of length n + 1 in the following way −"
},
{
"code": null,
"e": 1169,
"s": 1160,
"text": "A[0] = 0"
},
{
"code": null,
"e": 1178,
"s": 1169,
"text": "A[0] = 0"
},
{
"code": null,
"e": 1187,
"s": 1178,
"text": "A[1] = 1"
},
{
"code": null,
"e": 1196,
"s": 1187,
"text": "A[1] = 1"
},
{
"code": null,
"e": 1231,
"s": 1196,
"text": "A[2 * i] = A[i] if 2 <= 2 * i <= n"
},
{
"code": null,
"e": 1266,
"s": 1231,
"text": "A[2 * i] = A[i] if 2 <= 2 * i <= n"
},
{
"code": null,
"e": 1320,
"s": 1266,
"text": "A[2 * i + 1] = A[i] + A[i + 1] if 2 <= 2 * i + 1 <= n"
},
{
"code": null,
"e": 1374,
"s": 1320,
"text": "A[2 * i + 1] = A[i] + A[i + 1] if 2 <= 2 * i + 1 <= n"
},
{
"code": null,
"e": 1436,
"s": 1374,
"text": "Finally we have to find the maximum number in the array nums."
},
{
"code": null,
"e": 1502,
"s": 1436,
"text": "So, if the input is like n = 5, then the output will be 3 because"
},
{
"code": null,
"e": 1511,
"s": 1502,
"text": "A[0] = 0"
},
{
"code": null,
"e": 1520,
"s": 1511,
"text": "A[0] = 0"
},
{
"code": null,
"e": 1529,
"s": 1520,
"text": "A[1] = 1"
},
{
"code": null,
"e": 1538,
"s": 1529,
"text": "A[1] = 1"
},
{
"code": null,
"e": 1554,
"s": 1538,
"text": "A[2] = A[1] = 1"
},
{
"code": null,
"e": 1570,
"s": 1554,
"text": "A[2] = A[1] = 1"
},
{
"code": null,
"e": 1601,
"s": 1570,
"text": "A[3] = A[1] + A[2] = 1 + 1 = 2"
},
{
"code": null,
"e": 1632,
"s": 1601,
"text": "A[3] = A[1] + A[2] = 1 + 1 = 2"
},
{
"code": null,
"e": 1647,
"s": 1632,
"text": "A[4] = A[2]= 1"
},
{
"code": null,
"e": 1662,
"s": 1647,
"text": "A[4] = A[2]= 1"
},
{
"code": null,
"e": 1693,
"s": 1662,
"text": "A[5] = A[2] + A[3] = 1 + 2 = 3"
},
{
"code": null,
"e": 1724,
"s": 1693,
"text": "A[5] = A[2] + A[3] = 1 + 2 = 3"
},
{
"code": null,
"e": 1740,
"s": 1724,
"text": "A[6] = A[3] = 2"
},
{
"code": null,
"e": 1756,
"s": 1740,
"text": "A[6] = A[3] = 2"
},
{
"code": null,
"e": 1776,
"s": 1756,
"text": "So the maximum is 3"
},
{
"code": null,
"e": 1820,
"s": 1776,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1848,
"s": 1820,
"text": "A := a new list from 0 to n"
},
{
"code": null,
"e": 1876,
"s": 1848,
"text": "A := a new list from 0 to n"
},
{
"code": null,
"e": 2081,
"s": 1876,
"text": "for each element i in A, doif i is same as 0 or i is same as 1, thengo to next iterationotherwise when i is even, thenA[i] := A[integer of i/2]otherwise,A[i] := A[integer of i/2] + A[(integer of i/2) + 1]"
},
{
"code": null,
"e": 2109,
"s": 2081,
"text": "for each element i in A, do"
},
{
"code": null,
"e": 2171,
"s": 2109,
"text": "if i is same as 0 or i is same as 1, thengo to next iteration"
},
{
"code": null,
"e": 2213,
"s": 2171,
"text": "if i is same as 0 or i is same as 1, then"
},
{
"code": null,
"e": 2234,
"s": 2213,
"text": "go to next iteration"
},
{
"code": null,
"e": 2255,
"s": 2234,
"text": "go to next iteration"
},
{
"code": null,
"e": 2311,
"s": 2255,
"text": "otherwise when i is even, thenA[i] := A[integer of i/2]"
},
{
"code": null,
"e": 2342,
"s": 2311,
"text": "otherwise when i is even, then"
},
{
"code": null,
"e": 2368,
"s": 2342,
"text": "A[i] := A[integer of i/2]"
},
{
"code": null,
"e": 2394,
"s": 2368,
"text": "A[i] := A[integer of i/2]"
},
{
"code": null,
"e": 2456,
"s": 2394,
"text": "otherwise,A[i] := A[integer of i/2] + A[(integer of i/2) + 1]"
},
{
"code": null,
"e": 2467,
"s": 2456,
"text": "otherwise,"
},
{
"code": null,
"e": 2519,
"s": 2467,
"text": "A[i] := A[integer of i/2] + A[(integer of i/2) + 1]"
},
{
"code": null,
"e": 2571,
"s": 2519,
"text": "A[i] := A[integer of i/2] + A[(integer of i/2) + 1]"
},
{
"code": null,
"e": 2599,
"s": 2571,
"text": "return maximum element of A"
},
{
"code": null,
"e": 2627,
"s": 2599,
"text": "return maximum element of A"
},
{
"code": null,
"e": 2697,
"s": 2627,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": " Live Demo"
},
{
"code": null,
"e": 2945,
"s": 2708,
"text": "def solve(n):\n A = list(range(0,n+1))\n for i in A:\n if i == 0 or i == 1:\n continue\n elif i%2 == 0:\n A[i] = A[i//2]\n else:\n A[i] = A[i//2] + A[(i//2) + 1]\n return max(A)\n\nn = 5\nprint(solve(n))"
},
{
"code": null,
"e": 2947,
"s": 2945,
"text": "5"
},
{
"code": null,
"e": 2949,
"s": 2947,
"text": "3"
}
] |
SQL Query to Display Last 50% Records from Employee Table - GeeksforGeeks
|
13 Apr, 2021
Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server’s databases.
For the purpose of demonstration, we will be creating an Employee table in a database called “geeks“.
Use the below SQL statement to create a database called geeks:
CREATE DATABASE geeks;
USE geeks;
We have the following Employee table in our geeks database :
CREATE TABLE Employee(
ID INT IDENTITY(1,1) KEY, --IDENTITY(1,1) tells start ID from 1 and increment
-- it by 1 with each row inserted.
NAME VARCHAR(30) NOT NULL,
PHONE INT NOT NULL UNIQUE,
EMAIL VARCHAR(30) NOT NULL UNIQUE,
DATE_OF_JOINING DATE);
NOTE: We should use VARCHAR or BIGINT as the data type for the PHONE column to avoid integer overflow.
You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS Employee;
Use the below statement to add data to the Employee table:
INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)
VALUES
('Yogesh Vaishnav', 0000000001, 'yogesh@mail.com', '2019-10-03'),
('Vishal Vishwakarma', 0000000002, 'chicha@mail.com', '2019-11-07'),
('Ajit Yadav', 0000000003, 'ppa@mail.com', '2019-12-12'),
('Ashish Yadav', 0000000004, 'baba@mail.com', '2019-12-25'),
('Tanvi Thakur', 0000000005, 'tanvi@mail.com', '2020-01-20'),
('Sam', 0000000006, 'sam@mail.com', '2020-03-03'),
('Ron', 0000000007, 'ron@mail.com', '2020-05-16'),
('Sara', 0000000008, 'sara@mail.com', '2020-07-01'),
('Zara', 0000000009, 'zara@mail.com', '2020-08-20'),
('Yoji', 0000000010, 'yoji@mail.com', '2020-03-10'),
('Rekha Vaishnav', 12, 'rekha@mail.com', '2021-03-25');
To verify the contents of the table use the below statement:
SELECT * FROM Employee;
Now let’s retrieve the last 50% of the records from the Employee Table.
In MS SQL we can directly retrieve the last 50% of the records with the help of top and percent and order by clauses. A simple syntax for the same is given below:
Syntax :
select * from
/*Gives the top N percent records from bottom of a database table*/
(select top N percent * from <table_name> order by <column_name> desc)<identifier>
order by <column_name>;
Example :
SELECT * FROM
(SELECT top 50 percent * FROM Employee ORDER BY ID DESC)
ORDER BY ID;
Output :
Picked
SQL-Query
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Composite Key in SQL
SQL using Python
SQL | DROP, TRUNCATE
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
|
[
{
"code": null,
"e": 23949,
"s": 23918,
"text": " \n13 Apr, 2021\n"
},
{
"code": null,
"e": 24077,
"s": 23949,
"text": "Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server’s databases."
},
{
"code": null,
"e": 24179,
"s": 24077,
"text": "For the purpose of demonstration, we will be creating an Employee table in a database called “geeks“."
},
{
"code": null,
"e": 24242,
"s": 24179,
"text": "Use the below SQL statement to create a database called geeks:"
},
{
"code": null,
"e": 24265,
"s": 24242,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 24276,
"s": 24265,
"text": "USE geeks;"
},
{
"code": null,
"e": 24337,
"s": 24276,
"text": "We have the following Employee table in our geeks database :"
},
{
"code": null,
"e": 24617,
"s": 24337,
"text": "CREATE TABLE Employee(\nID INT IDENTITY(1,1) KEY, --IDENTITY(1,1) tells start ID from 1 and increment\n -- it by 1 with each row inserted.\nNAME VARCHAR(30) NOT NULL,\nPHONE INT NOT NULL UNIQUE,\nEMAIL VARCHAR(30) NOT NULL UNIQUE,\nDATE_OF_JOINING DATE);"
},
{
"code": null,
"e": 24720,
"s": 24617,
"text": "NOTE: We should use VARCHAR or BIGINT as the data type for the PHONE column to avoid integer overflow."
},
{
"code": null,
"e": 24799,
"s": 24720,
"text": "You can use the below statement to query the description of the created table:"
},
{
"code": null,
"e": 24825,
"s": 24799,
"text": "EXEC SP_COLUMNS Employee;"
},
{
"code": null,
"e": 24884,
"s": 24825,
"text": "Use the below statement to add data to the Employee table:"
},
{
"code": null,
"e": 25583,
"s": 24884,
"text": "INSERT INTO Employee (NAME, PHONE, EMAIL, DATE_OF_JOINING)\nVALUES\n('Yogesh Vaishnav', 0000000001, 'yogesh@mail.com', '2019-10-03'),\n('Vishal Vishwakarma', 0000000002, 'chicha@mail.com', '2019-11-07'),\n('Ajit Yadav', 0000000003, 'ppa@mail.com', '2019-12-12'),\n('Ashish Yadav', 0000000004, 'baba@mail.com', '2019-12-25'),\n('Tanvi Thakur', 0000000005, 'tanvi@mail.com', '2020-01-20'),\n('Sam', 0000000006, 'sam@mail.com', '2020-03-03'),\n('Ron', 0000000007, 'ron@mail.com', '2020-05-16'),\n('Sara', 0000000008, 'sara@mail.com', '2020-07-01'),\n('Zara', 0000000009, 'zara@mail.com', '2020-08-20'),\n('Yoji', 0000000010, 'yoji@mail.com', '2020-03-10'),\n('Rekha Vaishnav', 12, 'rekha@mail.com', '2021-03-25');"
},
{
"code": null,
"e": 25644,
"s": 25583,
"text": "To verify the contents of the table use the below statement:"
},
{
"code": null,
"e": 25668,
"s": 25644,
"text": "SELECT * FROM Employee;"
},
{
"code": null,
"e": 25740,
"s": 25668,
"text": "Now let’s retrieve the last 50% of the records from the Employee Table."
},
{
"code": null,
"e": 25903,
"s": 25740,
"text": "In MS SQL we can directly retrieve the last 50% of the records with the help of top and percent and order by clauses. A simple syntax for the same is given below:"
},
{
"code": null,
"e": 25912,
"s": 25903,
"text": "Syntax :"
},
{
"code": null,
"e": 25927,
"s": 25912,
"text": "select * from "
},
{
"code": null,
"e": 25997,
"s": 25927,
"text": " /*Gives the top N percent records from bottom of a database table*/"
},
{
"code": null,
"e": 26080,
"s": 25997,
"text": "(select top N percent * from <table_name> order by <column_name> desc)<identifier>"
},
{
"code": null,
"e": 26104,
"s": 26080,
"text": "order by <column_name>;"
},
{
"code": null,
"e": 26114,
"s": 26104,
"text": "Example :"
},
{
"code": null,
"e": 26198,
"s": 26114,
"text": "SELECT * FROM\n(SELECT top 50 percent * FROM Employee ORDER BY ID DESC)\nORDER BY ID;"
},
{
"code": null,
"e": 26207,
"s": 26198,
"text": "Output :"
},
{
"code": null,
"e": 26216,
"s": 26207,
"text": "\nPicked\n"
},
{
"code": null,
"e": 26228,
"s": 26216,
"text": "\nSQL-Query\n"
},
{
"code": null,
"e": 26234,
"s": 26228,
"text": "\nSQL\n"
},
{
"code": null,
"e": 26439,
"s": 26234,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 26505,
"s": 26439,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26583,
"s": 26505,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 26604,
"s": 26583,
"text": "Composite Key in SQL"
},
{
"code": null,
"e": 26621,
"s": 26604,
"text": "SQL using Python"
},
{
"code": null,
"e": 26642,
"s": 26621,
"text": "SQL | DROP, TRUNCATE"
},
{
"code": null,
"e": 26654,
"s": 26642,
"text": "SQL indexes"
},
{
"code": null,
"e": 26675,
"s": 26654,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 26707,
"s": 26675,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 26731,
"s": 26707,
"text": "Window functions in SQL"
}
] |
Check if a string can be formed from another string by at most X circular clockwise shifts - GeeksforGeeks
|
02 Jun, 2021
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times.
Input: S1 = “abcd”, S2 = “dddd”, X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character “a” – Shift 3 times – “d” Character “b” – Shift 2 times – “d” Character “c” – Shift 1 times – “d” Character “d” – Shift 0 times – “d”
Input: S1 = “you”, S2 = “ara”, X = 6 Output: Yes Explanation: Given string S1 can be converted to string S2 as – Character “y” – Circular Shift 2 times – “a” Character “o” – Shift 3 times – “r” Character “u” – Circular Shift 6 times – “a”
Approach: The idea is to traverse the string and for each index and find the difference between the ASCII values of the character at the respective indices of the two strings. If the difference is less than 0, then for a circular shift, add 26 to get the actual difference. If for any index, the difference exceeds X, then S2 can’t be formed from S1, otherwise possible. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X times #include <bits/stdc++.h>using namespace std; // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesvoid isConversionPossible(string s1, string s2, int x){ int diff, n; n = s1.length(); // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for (int i = 0; i < n; i++) { // If both the characters // are same if (s1[i] == s2[i]) continue; // Calculate the difference // between the ASCII values // of the characters diff = (int(s2[i] - s1[i]) + 26) % 26; // If difference exceeds X if (diff > x) { cout << "NO" << endl; return; } } cout << "YES" << endl;} // Driver Codeint main(){ string s1 = "you"; string s2 = "ara"; int x = 6; // Function call isConversionPossible(s1, s2, x); return 0;}
// Java implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X timesimport java.io.*;import java.util.*; class GFG{ // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesstatic void isConversionPossible(String s1, String s2, int x){ int diff = 0, n; n = s1.length(); // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for(int i = 0; i < n; i++) { // If both the characters // are same if (s1.charAt(i) == s2.charAt(i)) continue; // Calculate the difference // between the ASCII values // of the characters diff = ((int)(s2.charAt(i) - s1.charAt(i)) + 26) % 26; // If difference exceeds X if (diff > x) { System.out.println("NO"); return; } } System.out.println("YES");} // Driver Codepublic static void main (String[] args){ String s1 = "you"; String s2 = "ara"; int x = 6; // Function call isConversionPossible(s1, s2, x);}} // This code is contributed by Ganeshchowdharysadanala
# Python3 implementation to check# that the given string can be# converted to another string# by circular clockwise shift # Function to check that the# string s1 can be converted# to s2 by clockwise circular# shift of all characters of# str1 atmost X timesdef isConversionPossible(s1, s2, x): n = len(s1) s1 = list(s1) s2 = list(s2) for i in range(n): # Difference between the # ASCII numbers of characters diff = ord(s2[i]) - ord(s1[i]) # If both characters # are the same if diff == 0: continue # Condition to check if the # difference less than 0 then # find the circular shift by # adding 26 to it if diff < 0: diff = diff + 26 # If difference between # their ASCII values # exceeds X if diff > x: return False return True # Driver Codeif __name__ == "__main__": s1 = "you" s2 = "ara" x = 6 # Function Call result = isConversionPossible(s1, s2, x) if result: print("YES") else: print("NO")
// C# implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X timesusing System; class GFG{ // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesstatic void isConversionPossible(String s1, String s2, int x){ int diff = 0, n; n = s1.Length; // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for(int i = 0; i < n; i++) { // If both the characters // are same if (s1[i] == s2[i]) continue; // Calculate the difference // between the ASCII values // of the characters diff = ((int)(s2[i] - s1[i]) + 26) % 26; // If difference exceeds X if (diff > x) { Console.Write("NO"); return; } } Console.Write("YES");} // Driver Codepublic static void Main (){ String s1 = "you"; String s2 = "ara"; int x = 6; // Function call isConversionPossible(s1, s2, x);}} // This code is contributed by chitranayal
<script>// Javascript implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X times // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesfunction isConversionPossible(s1,s2,x){ let diff = 0, n; n = s1.length; // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for(let i = 0; i < n; i++) { // If both the characters // are same if (s1[i] == s2[i]) continue; // Calculate the difference // between the ASCII values // of the characters diff = ((s2[i].charCodeAt(0) - s1[i].charCodeAt(0)) + 26) % 26; // If difference exceeds X if (diff > x) { document.write("NO<br>"); return; } } document.write("YES<br>");} // Driver Codelet s1 = "you";let s2 = "ara";let x = 6; // Function callisConversionPossible(s1, s2, x); // This code is contributed by avanitrachhadiya2155</script>
YES
Time Complexity:O(N),N=Length(S1)
Auxiliary Space:O(1)
Ganeshchowdharysadanala
ukasp
aditya7409
avanitrachhadiya2155
ASCII
rotation
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Reverse words in a given string
Caesar Cipher in Cryptography
Length of the longest substring without repeating characters
|
[
{
"code": null,
"e": 25113,
"s": 25085,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 25287,
"s": 25113,
"text": "Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times."
},
{
"code": null,
"e": 25545,
"s": 25287,
"text": "Input: S1 = “abcd”, S2 = “dddd”, X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character “a” – Shift 3 times – “d” Character “b” – Shift 2 times – “d” Character “c” – Shift 1 times – “d” Character “d” – Shift 0 times – “d”"
},
{
"code": null,
"e": 25786,
"s": 25545,
"text": "Input: S1 = “you”, S2 = “ara”, X = 6 Output: Yes Explanation: Given string S1 can be converted to string S2 as – Character “y” – Circular Shift 2 times – “a” Character “o” – Shift 3 times – “r” Character “u” – Circular Shift 6 times – “a” "
},
{
"code": null,
"e": 26209,
"s": 25786,
"text": "Approach: The idea is to traverse the string and for each index and find the difference between the ASCII values of the character at the respective indices of the two strings. If the difference is less than 0, then for a circular shift, add 26 to get the actual difference. If for any index, the difference exceeds X, then S2 can’t be formed from S1, otherwise possible. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26213,
"s": 26209,
"text": "C++"
},
{
"code": null,
"e": 26218,
"s": 26213,
"text": "Java"
},
{
"code": null,
"e": 26226,
"s": 26218,
"text": "Python3"
},
{
"code": null,
"e": 26229,
"s": 26226,
"text": "C#"
},
{
"code": null,
"e": 26240,
"s": 26229,
"text": "Javascript"
},
{
"code": "// C++ implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X times #include <bits/stdc++.h>using namespace std; // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesvoid isConversionPossible(string s1, string s2, int x){ int diff, n; n = s1.length(); // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for (int i = 0; i < n; i++) { // If both the characters // are same if (s1[i] == s2[i]) continue; // Calculate the difference // between the ASCII values // of the characters diff = (int(s2[i] - s1[i]) + 26) % 26; // If difference exceeds X if (diff > x) { cout << \"NO\" << endl; return; } } cout << \"YES\" << endl;} // Driver Codeint main(){ string s1 = \"you\"; string s2 = \"ara\"; int x = 6; // Function call isConversionPossible(s1, s2, x); return 0;}",
"e": 27440,
"s": 26240,
"text": null
},
{
"code": "// Java implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X timesimport java.io.*;import java.util.*; class GFG{ // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesstatic void isConversionPossible(String s1, String s2, int x){ int diff = 0, n; n = s1.length(); // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for(int i = 0; i < n; i++) { // If both the characters // are same if (s1.charAt(i) == s2.charAt(i)) continue; // Calculate the difference // between the ASCII values // of the characters diff = ((int)(s2.charAt(i) - s1.charAt(i)) + 26) % 26; // If difference exceeds X if (diff > x) { System.out.println(\"NO\"); return; } } System.out.println(\"YES\");} // Driver Codepublic static void main (String[] args){ String s1 = \"you\"; String s2 = \"ara\"; int x = 6; // Function call isConversionPossible(s1, s2, x);}} // This code is contributed by Ganeshchowdharysadanala",
"e": 28821,
"s": 27440,
"text": null
},
{
"code": "# Python3 implementation to check# that the given string can be# converted to another string# by circular clockwise shift # Function to check that the# string s1 can be converted# to s2 by clockwise circular# shift of all characters of# str1 atmost X timesdef isConversionPossible(s1, s2, x): n = len(s1) s1 = list(s1) s2 = list(s2) for i in range(n): # Difference between the # ASCII numbers of characters diff = ord(s2[i]) - ord(s1[i]) # If both characters # are the same if diff == 0: continue # Condition to check if the # difference less than 0 then # find the circular shift by # adding 26 to it if diff < 0: diff = diff + 26 # If difference between # their ASCII values # exceeds X if diff > x: return False return True # Driver Codeif __name__ == \"__main__\": s1 = \"you\" s2 = \"ara\" x = 6 # Function Call result = isConversionPossible(s1, s2, x) if result: print(\"YES\") else: print(\"NO\")",
"e": 29955,
"s": 28821,
"text": null
},
{
"code": "// C# implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X timesusing System; class GFG{ // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesstatic void isConversionPossible(String s1, String s2, int x){ int diff = 0, n; n = s1.Length; // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for(int i = 0; i < n; i++) { // If both the characters // are same if (s1[i] == s2[i]) continue; // Calculate the difference // between the ASCII values // of the characters diff = ((int)(s2[i] - s1[i]) + 26) % 26; // If difference exceeds X if (diff > x) { Console.Write(\"NO\"); return; } } Console.Write(\"YES\");} // Driver Codepublic static void Main (){ String s1 = \"you\"; String s2 = \"ara\"; int x = 6; // Function call isConversionPossible(s1, s2, x);}} // This code is contributed by chitranayal",
"e": 31271,
"s": 29955,
"text": null
},
{
"code": "<script>// Javascript implementation to check// that a given string can be// converted to another string// by circular clockwise shift// of each character by atmost// X times // Function to check that all// characters of s1 can be// converted to s2 by circular// clockwise shift atmost X timesfunction isConversionPossible(s1,s2,x){ let diff = 0, n; n = s1.length; // Check for all characters of // the strings whether the // difference between their // ascii values is less than // X or not for(let i = 0; i < n; i++) { // If both the characters // are same if (s1[i] == s2[i]) continue; // Calculate the difference // between the ASCII values // of the characters diff = ((s2[i].charCodeAt(0) - s1[i].charCodeAt(0)) + 26) % 26; // If difference exceeds X if (diff > x) { document.write(\"NO<br>\"); return; } } document.write(\"YES<br>\");} // Driver Codelet s1 = \"you\";let s2 = \"ara\";let x = 6; // Function callisConversionPossible(s1, s2, x); // This code is contributed by avanitrachhadiya2155</script>",
"e": 32459,
"s": 31271,
"text": null
},
{
"code": null,
"e": 32463,
"s": 32459,
"text": "YES"
},
{
"code": null,
"e": 32499,
"s": 32465,
"text": "Time Complexity:O(N),N=Length(S1)"
},
{
"code": null,
"e": 32520,
"s": 32499,
"text": "Auxiliary Space:O(1)"
},
{
"code": null,
"e": 32544,
"s": 32520,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 32550,
"s": 32544,
"text": "ukasp"
},
{
"code": null,
"e": 32561,
"s": 32550,
"text": "aditya7409"
},
{
"code": null,
"e": 32582,
"s": 32561,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 32588,
"s": 32582,
"text": "ASCII"
},
{
"code": null,
"e": 32597,
"s": 32588,
"text": "rotation"
},
{
"code": null,
"e": 32605,
"s": 32597,
"text": "Strings"
},
{
"code": null,
"e": 32613,
"s": 32605,
"text": "Strings"
},
{
"code": null,
"e": 32711,
"s": 32613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32720,
"s": 32711,
"text": "Comments"
},
{
"code": null,
"e": 32733,
"s": 32720,
"text": "Old Comments"
},
{
"code": null,
"e": 32790,
"s": 32733,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 32865,
"s": 32790,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 32901,
"s": 32865,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32948,
"s": 32901,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 32984,
"s": 32948,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 33037,
"s": 32984,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 33075,
"s": 33037,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 33107,
"s": 33075,
"text": "Reverse words in a given string"
},
{
"code": null,
"e": 33137,
"s": 33107,
"text": "Caesar Cipher in Cryptography"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.