title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
JavaFX | Arc with examples - GeeksforGeeks | 13 May, 2019
Arc class is a part of JavaxFX. Arc class creates an arc on some given values specified, such as center of the arc, the start angle, the extent of arc(length), and radius. Arc class extends Shape class.Constructor for the class are
Arc(): creates an empty instance of arc classArc(double centerX, double centerY, double radiusX, double radiusY, double startAngle, double length): creates an arc with given coordinates and values
Arc(): creates an empty instance of arc class
Arc(double centerX, double centerY, double radiusX, double radiusY, double startAngle, double length): creates an arc with given coordinates and values
commonly used methods
The following programs will illustrate the use of the Arc classJava program to create a arcThis program creates a Arc indicated by the name arc( center, radius, start angle and arc length is passed as arguments). The arc will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the arc is attached.The group is attached to the scene. Finally, the show() method is called to display the final results.
// Java program to create a arcimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Arc;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group;public class arc_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating arc"); // create a arc Arc arc = new Arc(100.0f, 100.0f, 100.0f, 100.0f, 0.0f, 100.0f); // create a Group Group group = new Group(arc); // translate the arc to a position arc.setTranslateX(100); arc.setTranslateY(100); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java program to create a arc and set fill for the arc
This program creates a Arc indicated by the name arc( center, radius, start angle and arc length are set using setCenterX(), setCenterY(), setRadiusX(), setRadiusY(), setLength()). The arc will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the arc is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. The function setFill() is used to set fill for the arc.
// Java program to create a arc// and set fill for the arcimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Arc;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group;import javafx.scene.shape.ArcType;import javafx.scene.paint.Color;public class arc_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating arc"); // create a arc Arc arc = new Arc(); // set center arc.setCenterX(100.0f); arc.setCenterY(100.0f); // set radius arc.setRadiusX(100.0f); arc.setRadiusY(100.0f); // set start angle and length arc.setStartAngle(0.0f); arc.setLength(270.0f); // create a Group Group group = new Group(arc); // translate the arc to a position arc.setTranslateX(100); arc.setTranslateY(100); // set fill for the arc arc.setFill(Color.BLUE); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:Java Program to create a arc and specify its fill and arc typeThis program creates a Arc indicated by the name arc( center, radius, start angle and arc length are set using setCenterX(), setCenterY(), setRadiusX(), setRadiusY(), setLength()). The arc will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the arc is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. The function setFill() is used to set fill for the arc and function setArcType() is used to set ArcType of the arc.
// Java Program to create a arc and specify its fill and arc typeimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Arc;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group;import javafx.scene.shape.ArcType;import javafx.scene.paint.Color;public class arc_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating arc"); // create a arc Arc arc = new Arc(); // set center arc.setCenterX(100.0f); arc.setCenterY(100.0f); // set radius arc.setRadiusX(100.0f); arc.setRadiusY(100.0f); // set start angle and length arc.setStartAngle(0.0f); arc.setLength(270.0f); // create a Group Group group = new Group(arc); // translate the arc to a position arc.setTranslateX(100); arc.setTranslateY(100); // set fill for the arc arc.setFill(Color.BLUE); // set Type of Arc arc.setType(ArcType.ROUND); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}
Output:Note :The above program might not run in an online IDE please use an offline compilerReferencehttps://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Arc.html
Akanksha_Rai
JavaFX
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
Iterate through List in Java
Factory method design pattern in Java
Java program to count the occurrence of each character in a string using Hashmap
Java Program to Remove Duplicate Elements From the Array
Traverse Through a HashMap in Java
Min Heap in Java
Iterate Over the Characters of a String in Java
Remove first and last character of a string in Java | [
{
"code": null,
"e": 25277,
"s": 25249,
"text": "\n13 May, 2019"
},
{
"code": null,
"e": 25509,
"s": 25277,
"text": "Arc class is a part of JavaxFX. Arc class creates an arc on some given values specified, such as center of the arc, the start angle, the extent of arc(length), and radius. Arc class extends Shape class.Constructor for the class are"
},
{
"code": null,
"e": 25706,
"s": 25509,
"text": "Arc(): creates an empty instance of arc classArc(double centerX, double centerY, double radiusX, double radiusY, double startAngle, double length): creates an arc with given coordinates and values"
},
{
"code": null,
"e": 25752,
"s": 25706,
"text": "Arc(): creates an empty instance of arc class"
},
{
"code": null,
"e": 25904,
"s": 25752,
"text": "Arc(double centerX, double centerY, double radiusX, double radiusY, double startAngle, double length): creates an arc with given coordinates and values"
},
{
"code": null,
"e": 25926,
"s": 25904,
"text": "commonly used methods"
},
{
"code": null,
"e": 26439,
"s": 25926,
"text": "The following programs will illustrate the use of the Arc classJava program to create a arcThis program creates a Arc indicated by the name arc( center, radius, start angle and arc length is passed as arguments). The arc will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the arc is attached.The group is attached to the scene. Finally, the show() method is called to display the final results."
},
{
"code": "// Java program to create a arcimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Arc;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group;public class arc_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating arc\"); // create a arc Arc arc = new Arc(100.0f, 100.0f, 100.0f, 100.0f, 0.0f, 100.0f); // create a Group Group group = new Group(arc); // translate the arc to a position arc.setTranslateX(100); arc.setTranslateY(100); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 27462,
"s": 26439,
"text": null
},
{
"code": null,
"e": 27470,
"s": 27462,
"text": "Output:"
},
{
"code": null,
"e": 27524,
"s": 27470,
"text": "Java program to create a arc and set fill for the arc"
},
{
"code": null,
"e": 28061,
"s": 27524,
"text": "This program creates a Arc indicated by the name arc( center, radius, start angle and arc length are set using setCenterX(), setCenterY(), setRadiusX(), setRadiusY(), setLength()). The arc will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the arc is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. The function setFill() is used to set fill for the arc."
},
{
"code": "// Java program to create a arc// and set fill for the arcimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Arc;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group;import javafx.scene.shape.ArcType;import javafx.scene.paint.Color;public class arc_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating arc\"); // create a arc Arc arc = new Arc(); // set center arc.setCenterX(100.0f); arc.setCenterY(100.0f); // set radius arc.setRadiusX(100.0f); arc.setRadiusY(100.0f); // set start angle and length arc.setStartAngle(0.0f); arc.setLength(270.0f); // create a Group Group group = new Group(arc); // translate the arc to a position arc.setTranslateX(100); arc.setTranslateY(100); // set fill for the arc arc.setFill(Color.BLUE); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 29469,
"s": 28061,
"text": null
},
{
"code": null,
"e": 30135,
"s": 29469,
"text": "Output:Java Program to create a arc and specify its fill and arc typeThis program creates a Arc indicated by the name arc( center, radius, start angle and arc length are set using setCenterX(), setCenterY(), setRadiusX(), setRadiusY(), setLength()). The arc will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the arc is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. The function setFill() is used to set fill for the arc and function setArcType() is used to set ArcType of the arc."
},
{
"code": "// Java Program to create a arc and specify its fill and arc typeimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Arc;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group;import javafx.scene.shape.ArcType;import javafx.scene.paint.Color;public class arc_2 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating arc\"); // create a arc Arc arc = new Arc(); // set center arc.setCenterX(100.0f); arc.setCenterY(100.0f); // set radius arc.setRadiusX(100.0f); arc.setRadiusY(100.0f); // set start angle and length arc.setStartAngle(0.0f); arc.setLength(270.0f); // create a Group Group group = new Group(arc); // translate the arc to a position arc.setTranslateX(100); arc.setTranslateY(100); // set fill for the arc arc.setFill(Color.BLUE); // set Type of Arc arc.setType(ArcType.ROUND); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}",
"e": 31613,
"s": 30135,
"text": null
},
{
"code": null,
"e": 31786,
"s": 31613,
"text": "Output:Note :The above program might not run in an online IDE please use an offline compilerReferencehttps://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Arc.html"
},
{
"code": null,
"e": 31799,
"s": 31786,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31806,
"s": 31799,
"text": "JavaFX"
},
{
"code": null,
"e": 31820,
"s": 31806,
"text": "Java Programs"
},
{
"code": null,
"e": 31918,
"s": 31820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31950,
"s": 31918,
"text": "How to Iterate HashMap in Java?"
},
{
"code": null,
"e": 31994,
"s": 31950,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 32023,
"s": 31994,
"text": "Iterate through List in Java"
},
{
"code": null,
"e": 32061,
"s": 32023,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 32142,
"s": 32061,
"text": "Java program to count the occurrence of each character in a string using Hashmap"
},
{
"code": null,
"e": 32199,
"s": 32142,
"text": "Java Program to Remove Duplicate Elements From the Array"
},
{
"code": null,
"e": 32234,
"s": 32199,
"text": "Traverse Through a HashMap in Java"
},
{
"code": null,
"e": 32251,
"s": 32234,
"text": "Min Heap in Java"
},
{
"code": null,
"e": 32299,
"s": 32251,
"text": "Iterate Over the Characters of a String in Java"
}
]
|
StringBuffer append() Method in Java with Examples - GeeksforGeeks | 15 Dec, 2021
Pre-requisite: StringBuffer class in JavaThe java.lang.StringBuffer.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the append() method can be used:
StringBuffer append(boolean a) :The java.lang.StringBuffer.append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence.Syntax :public StringBuffer append(boolean a)Parameter : This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.Return Value : The method returns a reference to this object.Examples:Input:
string_buffer = "I love my Country"
boolean a = true
Output: I love my Country true
Below program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// StringBuffer append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("We are geeks and its really "); System.out.println("Input: " + sbf1); // Appending the boolean value sbf1.append(true); System.out.println("Output: " + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer("We are lost - "); System.out.println("Input: " + sbf2); // Appending the boolean value sbf2.append(false); System.out.println("Output: " + sbf2); }}Output:Input: We are geeks and its really
Output: We are geeks and its really true
Input: We are lost -
Output: We are lost - false
java.lang.StringBuffer.append(char a) : This is an inbuilt method that appends the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuffer sequence.Syntax :public StringBuffer append(char a)Parameter : The method accepts a single parameter a which is the Char value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
char a = A
Output: I love my Country ABelow programs illustrate the java.lang.StringBuffer.append(char a) method.// Java program to illustrate the// java.lang.StringBuffer.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its"); /* Here it appends the char argument as string to the string buffer */ sbf.append('M'); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); /* Here it appends the char argument as string to the string buffer */ sbf.append('&'); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and itsM
We are lost -
Result after appending = We are lost -&
StringBuffer append(char[] astr): The java.lang.StringBuffer.append(char[] astr) is the inbuilt method which appends the string representation of the char array argument to this StringBuffer sequence.Syntax :public StringBuffer append(char[] astr)Parameter : The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples:Input :
StringBuffer = I love my Country
char[] astr = 'I', 'N', 'D', 'I', 'A'
Output: I love my Country INDIABelow program illustrates the java.lang.StringBuffer.append(char[] astr) method:// Java program to illustrate the// java.lang.StringBuffer.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Here it appends string representation of char array argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Here it appends string representation of char array argument to argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its GEEkS
We are lost -
Result after appending = We are lost -abcd
StringBuffer append(char[] cstr, int iset, int ilength) : This method appends the string representation of a subarray of the char array argument to this sequence. The Characters of the char array cstr, starting at index iset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of ilength.Syntax :public StringBuffer append(char[] cstr, int iset, int ilenght)Parameter : This method accepts three parameters:cstr – This refers to the Char sequence.iset – This refers to the index of the first char to append.ilenght – This refers to the number of chars to append.Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuffer.append(char[] cstr, int iset, int ilength) method.// Java program to illustrate the// java.lang.StringBuffer append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Geeks"); System.out.println(" String buffer before = " + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', 'b', 'e', 'a', 'g', 'e', 'e', 'k' }; /* appends the string representation of char array argument to this string buffer with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the string buffer after appending System.out.println("After appending string buffer = " + sb); }}Output:String buffer before = Geeks
After appending string buffer = GeeksforGeeks
StringBuffer append(double a) : This method simply appends the string representation of the double argument to this StringBuffer sequence.Syntax :public StringBuffer append(double a)Parameter: The method accepts a single parameter a which refers to the decimal value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
Double a = 54.82
Output: I love my Country 54.82Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); // char array Double astr = new Double(636.47); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Double(827.38); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 636.47
We are lost -
Result after appending = We are lost -827.38
StringBuffer append(float f) : This method appends the string representation of the float argument to this sequence.Syntax :public StringBuffer append(float a)Parameter: The method accepts a single parameter a which is the float value whose string representation is to be appended.Return Value: StringBuffer.append(float a) method returns a reference the string object after the operation is performed.Examples :Input :
StringBuffer = I love my Country
float a = 5.2
Output: I love my Country 5.2Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this string buffer sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 6.47
We are lost -
Result after appending = We are lost -27.38
StringBuffer append(int i :) This method simply appends the string representation of the int argument to this StringBuffer sequence.Syntax :public StringBuffer append(int a)Parameter: The method accepts a single parameter a which is the int value.Return Value: The method returns a reference to this object.Examples :Input :
StringBuffer = I love my Country
int a = 55
Output: I love my Country 55Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Integer astr = new Integer(827); /*Here it appends string representation of Integer argument to argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this string buffer sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 827
We are lost -
Result after appending = We are lost -515
StringBuffer append(Long l) : This method simply appends the string representation of the long argument to this StringBuffer sequence.Syntax :public StringBuffer append(Long a)Parameter : The method accepts a single parameter a which is the long value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
Long a = 591995
Output: I love my Country 591995Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Long astr = new Long(827); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Long(515); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 827
We are lost -
Result after appending = We are lost -515
StringBuffer append(CharSequence a) : This method is used to append the specified CharSequence to this sequence.Syntax :public StringBuffer append(CharSequence a)Parameter: The method accepts a single parameter a which is the CharSequence value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
CharSequence a = abcd
Output : I love my Countryabcd
Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println(" string buffer = " + sbf); CharSequence chSeq = "geeks"; // Appends the CharSequence sbf.append(chSeq); // Print the string buffer after appending System.out.println("After append = " + sbf); }}Output:string buffer = Geeksfor
After append = Geeksforgeeks
StringBuffer append(CharSequence chseq, int start, int end) : This method is used to append a subsequence of the specified CharSequence to this StringBuffer.Syntax :StringBuffer append(CharSequence chseq, int start, int end)Parameter : The method accepts a three parameter:chseq(CharSequence): This refers to the CharSequence value.start(Integer): This refers to the starting index of the subsequence to be appended..end(Integer): This refers to the end index of the subsequence to be appended.Return Value : The method returns the string after the append operation is performed.Examples :Input :
StringBuffer = Geeksforgeeks
CharSequence chseq = abcd1234
int start = 2
int end = 7
Output :Geeksforgeekscd123
Below program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("we are the "); System.out.println(" string buffer = " + sbf); CharSequence chSeq = "wegeekss"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println("After append string buffer = " + sbf); }}Output:string buffer = we are the
After append string buffer = we are the geeks
StringBuffer append(Object obj) : This method is used to append the string representation of the Object argument to the StringBuffer.Syntax :StringBuffer append(Object obj)Parameter : The method accepts a single parameter obj which refers to the object needed to be appended.Return Value : The method returns the string after performing the append operation.Below programs illustrate the java.lang.StringBuffer.append() method.Program :// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println("string buffer = " + sbf); Object objectvalue = "geeks"; // Here it appends the Object value sbf.append(objectvalue); System.out.println("After appending result is = " + sbf); }}Output:string buffer = Geeksfor
After appending result is = Geeksforgeeks
StringBuffer append(String istr) : This method is used to append the specified string to this StringBuffer.Syntax :StringBuffer append(String istr)Parameter : The method accepts a single parameter istr of String type which refer to the value to be appended.Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println("string buffer = " + sbf); String strvalue = "geeks"; // Here it appends the Object value sbf.append(strvalue); System.out.println("After appending result is = " + sbf); }}Output:string buffer = Geeksfor
After appending result is = Geeksforgeeks
StringBuffer append(StringBuffer sbf) : This method is used to append the specified StringBuffer to this sequence or StringBuffer.Syntax :public StringBuffer append(StringBuffer sbf)Parameter : The method accepts a single parameter sbf refers to the StringBuffer to append.Return Value : The method returns StringBuffer to this sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("Geeks"); System.out.println("String buffer 1 = " + sbf1); StringBuffer sbf2 = new StringBuffer("forgeeks "); System.out.println("String buffer 2 = " + sbf2); // Here it appends stringbuffer2 to stringbuffer1 sbf1.append(sbf2); System.out.println("After appending the result is = " + sbf1); }}Output:String buffer 1 = Geeks
String buffer 2 = forgeeks
After appending the result is = Geeksforgeeks
StringBuffer append(boolean a) :The java.lang.StringBuffer.append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence.Syntax :public StringBuffer append(boolean a)Parameter : This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.Return Value : The method returns a reference to this object.Examples:Input:
string_buffer = "I love my Country"
boolean a = true
Output: I love my Country true
Below program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// StringBuffer append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("We are geeks and its really "); System.out.println("Input: " + sbf1); // Appending the boolean value sbf1.append(true); System.out.println("Output: " + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer("We are lost - "); System.out.println("Input: " + sbf2); // Appending the boolean value sbf2.append(false); System.out.println("Output: " + sbf2); }}Output:Input: We are geeks and its really
Output: We are geeks and its really true
Input: We are lost -
Output: We are lost - false
Syntax :
public StringBuffer append(boolean a)
Parameter : This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.
Return Value : The method returns a reference to this object.
Examples:
Input:
string_buffer = "I love my Country"
boolean a = true
Output: I love my Country true
Below program illustrates the java.lang.StringBuffer.append() method:
// Java program to illustrate the// StringBuffer append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("We are geeks and its really "); System.out.println("Input: " + sbf1); // Appending the boolean value sbf1.append(true); System.out.println("Output: " + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer("We are lost - "); System.out.println("Input: " + sbf2); // Appending the boolean value sbf2.append(false); System.out.println("Output: " + sbf2); }}
Input: We are geeks and its really
Output: We are geeks and its really true
Input: We are lost -
Output: We are lost - false
java.lang.StringBuffer.append(char a) : This is an inbuilt method that appends the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuffer sequence.Syntax :public StringBuffer append(char a)Parameter : The method accepts a single parameter a which is the Char value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
char a = A
Output: I love my Country ABelow programs illustrate the java.lang.StringBuffer.append(char a) method.// Java program to illustrate the// java.lang.StringBuffer.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its"); /* Here it appends the char argument as string to the string buffer */ sbf.append('M'); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); /* Here it appends the char argument as string to the string buffer */ sbf.append('&'); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and itsM
We are lost -
Result after appending = We are lost -&
Syntax :
public StringBuffer append(char a)
Parameter : The method accepts a single parameter a which is the Char value whose string representation is to be appended.
Return Value: The method returns a string object after the append operation is performed.Examples :
Input :
StringBuffer = I love my Country
char a = A
Output: I love my Country A
Below programs illustrate the java.lang.StringBuffer.append(char a) method.
// Java program to illustrate the// java.lang.StringBuffer.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its"); /* Here it appends the char argument as string to the string buffer */ sbf.append('M'); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); /* Here it appends the char argument as string to the string buffer */ sbf.append('&'); System.out.println("Result after appending = " + sbf); }}
We are geeks and its really
Result after appending = We are geeks and itsM
We are lost -
Result after appending = We are lost -&
StringBuffer append(char[] astr): The java.lang.StringBuffer.append(char[] astr) is the inbuilt method which appends the string representation of the char array argument to this StringBuffer sequence.Syntax :public StringBuffer append(char[] astr)Parameter : The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples:Input :
StringBuffer = I love my Country
char[] astr = 'I', 'N', 'D', 'I', 'A'
Output: I love my Country INDIABelow program illustrates the java.lang.StringBuffer.append(char[] astr) method:// Java program to illustrate the// java.lang.StringBuffer.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Here it appends string representation of char array argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Here it appends string representation of char array argument to argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its GEEkS
We are lost -
Result after appending = We are lost -abcd
Syntax :
public StringBuffer append(char[] astr)
Parameter : The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.
Return Value: The method returns a string object after the append operation is performed.Examples:
Input :
StringBuffer = I love my Country
char[] astr = 'I', 'N', 'D', 'I', 'A'
Output: I love my Country INDIA
Below program illustrates the java.lang.StringBuffer.append(char[] astr) method:
// Java program to illustrate the// java.lang.StringBuffer.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Here it appends string representation of char array argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Here it appends string representation of char array argument to argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}
We are geeks and its really
Result after appending = We are geeks and its GEEkS
We are lost -
Result after appending = We are lost -abcd
StringBuffer append(char[] cstr, int iset, int ilength) : This method appends the string representation of a subarray of the char array argument to this sequence. The Characters of the char array cstr, starting at index iset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of ilength.Syntax :public StringBuffer append(char[] cstr, int iset, int ilenght)Parameter : This method accepts three parameters:cstr – This refers to the Char sequence.iset – This refers to the index of the first char to append.ilenght – This refers to the number of chars to append.Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuffer.append(char[] cstr, int iset, int ilength) method.// Java program to illustrate the// java.lang.StringBuffer append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Geeks"); System.out.println(" String buffer before = " + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', 'b', 'e', 'a', 'g', 'e', 'e', 'k' }; /* appends the string representation of char array argument to this string buffer with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the string buffer after appending System.out.println("After appending string buffer = " + sb); }}Output:String buffer before = Geeks
After appending string buffer = GeeksforGeeks
Syntax :
public StringBuffer append(char[] cstr, int iset, int ilenght)
Parameter : This method accepts three parameters:
cstr – This refers to the Char sequence.
iset – This refers to the index of the first char to append.
ilenght – This refers to the number of chars to append.
Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuffer.append(char[] cstr, int iset, int ilength) method.
// Java program to illustrate the// java.lang.StringBuffer append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Geeks"); System.out.println(" String buffer before = " + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', 'b', 'e', 'a', 'g', 'e', 'e', 'k' }; /* appends the string representation of char array argument to this string buffer with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the string buffer after appending System.out.println("After appending string buffer = " + sb); }}
String buffer before = Geeks
After appending string buffer = GeeksforGeeks
StringBuffer append(double a) : This method simply appends the string representation of the double argument to this StringBuffer sequence.Syntax :public StringBuffer append(double a)Parameter: The method accepts a single parameter a which refers to the decimal value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
Double a = 54.82
Output: I love my Country 54.82Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); // char array Double astr = new Double(636.47); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Double(827.38); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 636.47
We are lost -
Result after appending = We are lost -827.38
Syntax :
public StringBuffer append(double a)
Parameter: The method accepts a single parameter a which refers to the decimal value whose string representation is to be appended.
Return Value: The method returns a string object after the append operation is performed.Examples :
Input :
StringBuffer = I love my Country
Double a = 54.82
Output: I love my Country 54.82
Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); // char array Double astr = new Double(636.47); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Double(827.38); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}
We are geeks and its really
Result after appending = We are geeks and its 636.47
We are lost -
Result after appending = We are lost -827.38
StringBuffer append(float f) : This method appends the string representation of the float argument to this sequence.Syntax :public StringBuffer append(float a)Parameter: The method accepts a single parameter a which is the float value whose string representation is to be appended.Return Value: StringBuffer.append(float a) method returns a reference the string object after the operation is performed.Examples :Input :
StringBuffer = I love my Country
float a = 5.2
Output: I love my Country 5.2Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this string buffer sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 6.47
We are lost -
Result after appending = We are lost -27.38
Syntax :
public StringBuffer append(float a)
Parameter: The method accepts a single parameter a which is the float value whose string representation is to be appended.
Return Value: StringBuffer.append(float a) method returns a reference the string object after the operation is performed.
Examples :
Input :
StringBuffer = I love my Country
float a = 5.2
Output: I love my Country 5.2
Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this string buffer */ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this string buffer sbf.append(astr); System.out.println("Result after appending = " + sbf); }}
We are geeks and its really
Result after appending = We are geeks and its 6.47
We are lost -
Result after appending = We are lost -27.38
StringBuffer append(int i :) This method simply appends the string representation of the int argument to this StringBuffer sequence.Syntax :public StringBuffer append(int a)Parameter: The method accepts a single parameter a which is the int value.Return Value: The method returns a reference to this object.Examples :Input :
StringBuffer = I love my Country
int a = 55
Output: I love my Country 55Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Integer astr = new Integer(827); /*Here it appends string representation of Integer argument to argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this string buffer sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 827
We are lost -
Result after appending = We are lost -515
public StringBuffer append(int a)
Parameter: The method accepts a single parameter a which is the int value.
Return Value: The method returns a reference to this object.
Examples :
Input :
StringBuffer = I love my Country
int a = 55
Output: I love my Country 55
Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Integer astr = new Integer(827); /*Here it appends string representation of Integer argument to argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this string buffer sbf.append(astr); System.out.println("Result after appending = " + sbf); }}
We are geeks and its really
Result after appending = We are geeks and its 827
We are lost -
Result after appending = We are lost -515
StringBuffer append(Long l) : This method simply appends the string representation of the long argument to this StringBuffer sequence.Syntax :public StringBuffer append(Long a)Parameter : The method accepts a single parameter a which is the long value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
Long a = 591995
Output: I love my Country 591995Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Long astr = new Long(827); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Long(515); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}Output:We are geeks and its really
Result after appending = We are geeks and its 827
We are lost -
Result after appending = We are lost -515
Syntax :
public StringBuffer append(Long a)
Parameter : The method accepts a single parameter a which is the long value.
Return Value: The method returns a string object after the append operation is performed.Examples :
Input :
StringBuffer = I love my Country
Long a = 591995
Output: I love my Country 591995
Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println("We are geeks and its really "); StringBuffer sbf = new StringBuffer("We are geeks and its "); Long astr = new Long(827); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); System.out.println("We are lost -"); sbf = new StringBuffer("We are lost -"); astr = new Long(515); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println("Result after appending = " + sbf); }}
We are geeks and its really
Result after appending = We are geeks and its 827
We are lost -
Result after appending = We are lost -515
StringBuffer append(CharSequence a) : This method is used to append the specified CharSequence to this sequence.Syntax :public StringBuffer append(CharSequence a)Parameter: The method accepts a single parameter a which is the CharSequence value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :
StringBuffer = I love my Country
CharSequence a = abcd
Output : I love my Countryabcd
Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println(" string buffer = " + sbf); CharSequence chSeq = "geeks"; // Appends the CharSequence sbf.append(chSeq); // Print the string buffer after appending System.out.println("After append = " + sbf); }}Output:string buffer = Geeksfor
After append = Geeksforgeeks
Syntax :
public StringBuffer append(CharSequence a)
Parameter: The method accepts a single parameter a which is the CharSequence value.
Return Value: The method returns a string object after the append operation is performed.
Examples :
Input :
StringBuffer = I love my Country
CharSequence a = abcd
Output : I love my Countryabcd
Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println(" string buffer = " + sbf); CharSequence chSeq = "geeks"; // Appends the CharSequence sbf.append(chSeq); // Print the string buffer after appending System.out.println("After append = " + sbf); }}
string buffer = Geeksfor
After append = Geeksforgeeks
StringBuffer append(CharSequence chseq, int start, int end) : This method is used to append a subsequence of the specified CharSequence to this StringBuffer.Syntax :StringBuffer append(CharSequence chseq, int start, int end)Parameter : The method accepts a three parameter:chseq(CharSequence): This refers to the CharSequence value.start(Integer): This refers to the starting index of the subsequence to be appended..end(Integer): This refers to the end index of the subsequence to be appended.Return Value : The method returns the string after the append operation is performed.Examples :Input :
StringBuffer = Geeksforgeeks
CharSequence chseq = abcd1234
int start = 2
int end = 7
Output :Geeksforgeekscd123
Below program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("we are the "); System.out.println(" string buffer = " + sbf); CharSequence chSeq = "wegeekss"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println("After append string buffer = " + sbf); }}Output:string buffer = we are the
After append string buffer = we are the geeks
Syntax :
StringBuffer append(CharSequence chseq, int start, int end)
Parameter : The method accepts a three parameter:
chseq(CharSequence): This refers to the CharSequence value.
start(Integer): This refers to the starting index of the subsequence to be appended..
end(Integer): This refers to the end index of the subsequence to be appended.
Return Value : The method returns the string after the append operation is performed.
Examples :
Input :
StringBuffer = Geeksforgeeks
CharSequence chseq = abcd1234
int start = 2
int end = 7
Output :Geeksforgeekscd123
Below program illustrates the java.lang.StringBuffer.append() method:
// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("we are the "); System.out.println(" string buffer = " + sbf); CharSequence chSeq = "wegeekss"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println("After append string buffer = " + sbf); }}
string buffer = we are the
After append string buffer = we are the geeks
StringBuffer append(Object obj) : This method is used to append the string representation of the Object argument to the StringBuffer.Syntax :StringBuffer append(Object obj)Parameter : The method accepts a single parameter obj which refers to the object needed to be appended.Return Value : The method returns the string after performing the append operation.Below programs illustrate the java.lang.StringBuffer.append() method.Program :// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println("string buffer = " + sbf); Object objectvalue = "geeks"; // Here it appends the Object value sbf.append(objectvalue); System.out.println("After appending result is = " + sbf); }}Output:string buffer = Geeksfor
After appending result is = Geeksforgeeks
Syntax :
StringBuffer append(Object obj)
Parameter : The method accepts a single parameter obj which refers to the object needed to be appended.
Return Value : The method returns the string after performing the append operation.
Below programs illustrate the java.lang.StringBuffer.append() method.
Program :
// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println("string buffer = " + sbf); Object objectvalue = "geeks"; // Here it appends the Object value sbf.append(objectvalue); System.out.println("After appending result is = " + sbf); }}
string buffer = Geeksfor
After appending result is = Geeksforgeeks
StringBuffer append(String istr) : This method is used to append the specified string to this StringBuffer.Syntax :StringBuffer append(String istr)Parameter : The method accepts a single parameter istr of String type which refer to the value to be appended.Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println("string buffer = " + sbf); String strvalue = "geeks"; // Here it appends the Object value sbf.append(strvalue); System.out.println("After appending result is = " + sbf); }}Output:string buffer = Geeksfor
After appending result is = Geeksforgeeks
StringBuffer append(String istr)
Parameter : The method accepts a single parameter istr of String type which refer to the value to be appended.
Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer("Geeksfor"); System.out.println("string buffer = " + sbf); String strvalue = "geeks"; // Here it appends the Object value sbf.append(strvalue); System.out.println("After appending result is = " + sbf); }}
string buffer = Geeksfor
After appending result is = Geeksforgeeks
StringBuffer append(StringBuffer sbf) : This method is used to append the specified StringBuffer to this sequence or StringBuffer.Syntax :public StringBuffer append(StringBuffer sbf)Parameter : The method accepts a single parameter sbf refers to the StringBuffer to append.Return Value : The method returns StringBuffer to this sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("Geeks"); System.out.println("String buffer 1 = " + sbf1); StringBuffer sbf2 = new StringBuffer("forgeeks "); System.out.println("String buffer 2 = " + sbf2); // Here it appends stringbuffer2 to stringbuffer1 sbf1.append(sbf2); System.out.println("After appending the result is = " + sbf1); }}Output:String buffer 1 = Geeks
String buffer 2 = forgeeks
After appending the result is = Geeksforgeeks
Syntax :
public StringBuffer append(StringBuffer sbf)
Parameter : The method accepts a single parameter sbf refers to the StringBuffer to append.
Return Value : The method returns StringBuffer to this sequence.Below program illustrates the java.lang.StringBuffer.append() method.
// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("Geeks"); System.out.println("String buffer 1 = " + sbf1); StringBuffer sbf2 = new StringBuffer("forgeeks "); System.out.println("String buffer 2 = " + sbf2); // Here it appends stringbuffer2 to stringbuffer1 sbf1.append(sbf2); System.out.println("After appending the result is = " + sbf1); }}
String buffer 1 = Geeks
String buffer 2 = forgeeks
After appending the result is = Geeksforgeeks
anikaseth98
Java-Functions
Java-lang package
java-StringBuffer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 26238,
"s": 26210,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 26466,
"s": 26238,
"text": "Pre-requisite: StringBuffer class in JavaThe java.lang.StringBuffer.append() method is used to append the string representation of some argument to the sequence. There are 13 ways/forms in which the append() method can be used:"
},
{
"code": null,
"e": 44260,
"s": 26466,
"text": "StringBuffer append(boolean a) :The java.lang.StringBuffer.append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence.Syntax :public StringBuffer append(boolean a)Parameter : This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.Return Value : The method returns a reference to this object.Examples:Input: \nstring_buffer = \"I love my Country\" \nboolean a = true\n\nOutput: I love my Country true\nBelow program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// StringBuffer append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer(\"We are geeks and its really \"); System.out.println(\"Input: \" + sbf1); // Appending the boolean value sbf1.append(true); System.out.println(\"Output: \" + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer(\"We are lost - \"); System.out.println(\"Input: \" + sbf2); // Appending the boolean value sbf2.append(false); System.out.println(\"Output: \" + sbf2); }}Output:Input: We are geeks and its really \nOutput: We are geeks and its really true\n\nInput: We are lost - \nOutput: We are lost - false\njava.lang.StringBuffer.append(char a) : This is an inbuilt method that appends the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuffer sequence.Syntax :public StringBuffer append(char a)Parameter : The method accepts a single parameter a which is the Char value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country \nchar a = A\n\nOutput: I love my Country ABelow programs illustrate the java.lang.StringBuffer.append(char a) method.// Java program to illustrate the// java.lang.StringBuffer.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its\"); /* Here it appends the char argument as string to the string buffer */ sbf.append('M'); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); /* Here it appends the char argument as string to the string buffer */ sbf.append('&'); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and itsM\nWe are lost -\nResult after appending = We are lost -&\nStringBuffer append(char[] astr): The java.lang.StringBuffer.append(char[] astr) is the inbuilt method which appends the string representation of the char array argument to this StringBuffer sequence.Syntax :public StringBuffer append(char[] astr)Parameter : The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples:Input :\nStringBuffer = I love my Country \nchar[] astr = 'I', 'N', 'D', 'I', 'A'\n\nOutput: I love my Country INDIABelow program illustrates the java.lang.StringBuffer.append(char[] astr) method:// Java program to illustrate the// java.lang.StringBuffer.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Here it appends string representation of char array argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Here it appends string representation of char array argument to argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its GEEkS\nWe are lost -\nResult after appending = We are lost -abcd\nStringBuffer append(char[] cstr, int iset, int ilength) : This method appends the string representation of a subarray of the char array argument to this sequence. The Characters of the char array cstr, starting at index iset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of ilength.Syntax :public StringBuffer append(char[] cstr, int iset, int ilenght)Parameter : This method accepts three parameters:cstr – This refers to the Char sequence.iset – This refers to the index of the first char to append.ilenght – This refers to the number of chars to append.Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuffer.append(char[] cstr, int iset, int ilength) method.// Java program to illustrate the// java.lang.StringBuffer append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sb = new StringBuffer(\"Geeks\"); System.out.println(\" String buffer before = \" + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', 'b', 'e', 'a', 'g', 'e', 'e', 'k' }; /* appends the string representation of char array argument to this string buffer with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the string buffer after appending System.out.println(\"After appending string buffer = \" + sb); }}Output:String buffer before = Geeks\nAfter appending string buffer = GeeksforGeeks\nStringBuffer append(double a) : This method simply appends the string representation of the double argument to this StringBuffer sequence.Syntax :public StringBuffer append(double a)Parameter: The method accepts a single parameter a which refers to the decimal value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country\nDouble a = 54.82\nOutput: I love my Country 54.82Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); // char array Double astr = new Double(636.47); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Double(827.38); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 636.47\nWe are lost -\nResult after appending = We are lost -827.38\nStringBuffer append(float f) : This method appends the string representation of the float argument to this sequence.Syntax :public StringBuffer append(float a)Parameter: The method accepts a single parameter a which is the float value whose string representation is to be appended.Return Value: StringBuffer.append(float a) method returns a reference the string object after the operation is performed.Examples :Input : \n StringBuffer = I love my Country \nfloat a = 5.2\n \nOutput: I love my Country 5.2Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this string buffer sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 6.47\nWe are lost -\nResult after appending = We are lost -27.38\nStringBuffer append(int i :) This method simply appends the string representation of the int argument to this StringBuffer sequence.Syntax :public StringBuffer append(int a)Parameter: The method accepts a single parameter a which is the int value.Return Value: The method returns a reference to this object.Examples :Input :\nStringBuffer = I love my Country \nint a = 55\n\nOutput: I love my Country 55Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Integer astr = new Integer(827); /*Here it appends string representation of Integer argument to argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this string buffer sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 827\nWe are lost -\nResult after appending = We are lost -515\nStringBuffer append(Long l) : This method simply appends the string representation of the long argument to this StringBuffer sequence.Syntax :public StringBuffer append(Long a)Parameter : The method accepts a single parameter a which is the long value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country\nLong a = 591995\n\nOutput: I love my Country 591995Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Long astr = new Long(827); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Long(515); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 827\nWe are lost -\nResult after appending = We are lost -515\nStringBuffer append(CharSequence a) : This method is used to append the specified CharSequence to this sequence.Syntax :public StringBuffer append(CharSequence a)Parameter: The method accepts a single parameter a which is the CharSequence value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country \nCharSequence a = abcd\n\nOutput : I love my Countryabcd\nBelow program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\" string buffer = \" + sbf); CharSequence chSeq = \"geeks\"; // Appends the CharSequence sbf.append(chSeq); // Print the string buffer after appending System.out.println(\"After append = \" + sbf); }}Output:string buffer = Geeksfor\nAfter append = Geeksforgeeks\nStringBuffer append(CharSequence chseq, int start, int end) : This method is used to append a subsequence of the specified CharSequence to this StringBuffer.Syntax :StringBuffer append(CharSequence chseq, int start, int end)Parameter : The method accepts a three parameter:chseq(CharSequence): This refers to the CharSequence value.start(Integer): This refers to the starting index of the subsequence to be appended..end(Integer): This refers to the end index of the subsequence to be appended.Return Value : The method returns the string after the append operation is performed.Examples :Input :\nStringBuffer = Geeksforgeeks\nCharSequence chseq = abcd1234\nint start = 2\nint end = 7\n\nOutput :Geeksforgeekscd123\nBelow program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"we are the \"); System.out.println(\" string buffer = \" + sbf); CharSequence chSeq = \"wegeekss\"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println(\"After append string buffer = \" + sbf); }}Output:string buffer = we are the \nAfter append string buffer = we are the geeks\nStringBuffer append(Object obj) : This method is used to append the string representation of the Object argument to the StringBuffer.Syntax :StringBuffer append(Object obj)Parameter : The method accepts a single parameter obj which refers to the object needed to be appended.Return Value : The method returns the string after performing the append operation.Below programs illustrate the java.lang.StringBuffer.append() method.Program :// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\"string buffer = \" + sbf); Object objectvalue = \"geeks\"; // Here it appends the Object value sbf.append(objectvalue); System.out.println(\"After appending result is = \" + sbf); }}Output:string buffer = Geeksfor\nAfter appending result is = Geeksforgeeks\nStringBuffer append(String istr) : This method is used to append the specified string to this StringBuffer.Syntax :StringBuffer append(String istr)Parameter : The method accepts a single parameter istr of String type which refer to the value to be appended.Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\"string buffer = \" + sbf); String strvalue = \"geeks\"; // Here it appends the Object value sbf.append(strvalue); System.out.println(\"After appending result is = \" + sbf); }}Output:string buffer = Geeksfor\nAfter appending result is = Geeksforgeeks\nStringBuffer append(StringBuffer sbf) : This method is used to append the specified StringBuffer to this sequence or StringBuffer.Syntax :public StringBuffer append(StringBuffer sbf)Parameter : The method accepts a single parameter sbf refers to the StringBuffer to append.Return Value : The method returns StringBuffer to this sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer(\"Geeks\"); System.out.println(\"String buffer 1 = \" + sbf1); StringBuffer sbf2 = new StringBuffer(\"forgeeks \"); System.out.println(\"String buffer 2 = \" + sbf2); // Here it appends stringbuffer2 to stringbuffer1 sbf1.append(sbf2); System.out.println(\"After appending the result is = \" + sbf1); }}Output:String buffer 1 = Geeks\nString buffer 2 = forgeeks \nAfter appending the result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 45642,
"s": 44260,
"text": "StringBuffer append(boolean a) :The java.lang.StringBuffer.append(boolean a) is an inbuilt method in Java which is used to append the string representation of the boolean argument to a given sequence.Syntax :public StringBuffer append(boolean a)Parameter : This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended.Return Value : The method returns a reference to this object.Examples:Input: \nstring_buffer = \"I love my Country\" \nboolean a = true\n\nOutput: I love my Country true\nBelow program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// StringBuffer append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer(\"We are geeks and its really \"); System.out.println(\"Input: \" + sbf1); // Appending the boolean value sbf1.append(true); System.out.println(\"Output: \" + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer(\"We are lost - \"); System.out.println(\"Input: \" + sbf2); // Appending the boolean value sbf2.append(false); System.out.println(\"Output: \" + sbf2); }}Output:Input: We are geeks and its really \nOutput: We are geeks and its really true\n\nInput: We are lost - \nOutput: We are lost - false\n"
},
{
"code": null,
"e": 45651,
"s": 45642,
"text": "Syntax :"
},
{
"code": null,
"e": 45689,
"s": 45651,
"text": "public StringBuffer append(boolean a)"
},
{
"code": null,
"e": 45806,
"s": 45689,
"text": "Parameter : This method accepts a single parameter a of boolean type and refers to the Boolean value to be appended."
},
{
"code": null,
"e": 45868,
"s": 45806,
"text": "Return Value : The method returns a reference to this object."
},
{
"code": null,
"e": 45878,
"s": 45868,
"text": "Examples:"
},
{
"code": null,
"e": 45973,
"s": 45878,
"text": "Input: \nstring_buffer = \"I love my Country\" \nboolean a = true\n\nOutput: I love my Country true\n"
},
{
"code": null,
"e": 46043,
"s": 45973,
"text": "Below program illustrates the java.lang.StringBuffer.append() method:"
},
{
"code": "// Java program to illustrate the// StringBuffer append(boolean a)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer(\"We are geeks and its really \"); System.out.println(\"Input: \" + sbf1); // Appending the boolean value sbf1.append(true); System.out.println(\"Output: \" + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer(\"We are lost - \"); System.out.println(\"Input: \" + sbf2); // Appending the boolean value sbf2.append(false); System.out.println(\"Output: \" + sbf2); }}",
"e": 46696,
"s": 46043,
"text": null
},
{
"code": null,
"e": 46825,
"s": 46696,
"text": "Input: We are geeks and its really \nOutput: We are geeks and its really true\n\nInput: We are lost - \nOutput: We are lost - false\n"
},
{
"code": null,
"e": 48345,
"s": 46825,
"text": "java.lang.StringBuffer.append(char a) : This is an inbuilt method that appends the string representation of the char argument to the given sequence. The char argument is appended to the contents of this StringBuffer sequence.Syntax :public StringBuffer append(char a)Parameter : The method accepts a single parameter a which is the Char value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country \nchar a = A\n\nOutput: I love my Country ABelow programs illustrate the java.lang.StringBuffer.append(char a) method.// Java program to illustrate the// java.lang.StringBuffer.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its\"); /* Here it appends the char argument as string to the string buffer */ sbf.append('M'); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); /* Here it appends the char argument as string to the string buffer */ sbf.append('&'); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and itsM\nWe are lost -\nResult after appending = We are lost -&\n"
},
{
"code": null,
"e": 48354,
"s": 48345,
"text": "Syntax :"
},
{
"code": null,
"e": 48389,
"s": 48354,
"text": "public StringBuffer append(char a)"
},
{
"code": null,
"e": 48512,
"s": 48389,
"text": "Parameter : The method accepts a single parameter a which is the Char value whose string representation is to be appended."
},
{
"code": null,
"e": 48612,
"s": 48512,
"text": "Return Value: The method returns a string object after the append operation is performed.Examples :"
},
{
"code": null,
"e": 48694,
"s": 48612,
"text": "Input :\nStringBuffer = I love my Country \nchar a = A\n\nOutput: I love my Country A"
},
{
"code": null,
"e": 48770,
"s": 48694,
"text": "Below programs illustrate the java.lang.StringBuffer.append(char a) method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append(char a)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its\"); /* Here it appends the char argument as string to the string buffer */ sbf.append('M'); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); /* Here it appends the char argument as string to the string buffer */ sbf.append('&'); System.out.println(\"Result after appending = \" + sbf); }}",
"e": 49509,
"s": 48770,
"text": null
},
{
"code": null,
"e": 49640,
"s": 49509,
"text": "We are geeks and its really \nResult after appending = We are geeks and itsM\nWe are lost -\nResult after appending = We are lost -&\n"
},
{
"code": null,
"e": 51415,
"s": 49640,
"text": "StringBuffer append(char[] astr): The java.lang.StringBuffer.append(char[] astr) is the inbuilt method which appends the string representation of the char array argument to this StringBuffer sequence.Syntax :public StringBuffer append(char[] astr)Parameter : The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples:Input :\nStringBuffer = I love my Country \nchar[] astr = 'I', 'N', 'D', 'I', 'A'\n\nOutput: I love my Country INDIABelow program illustrates the java.lang.StringBuffer.append(char[] astr) method:// Java program to illustrate the// java.lang.StringBuffer.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Here it appends string representation of char array argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Here it appends string representation of char array argument to argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its GEEkS\nWe are lost -\nResult after appending = We are lost -abcd\n"
},
{
"code": null,
"e": 51424,
"s": 51415,
"text": "Syntax :"
},
{
"code": null,
"e": 51464,
"s": 51424,
"text": "public StringBuffer append(char[] astr)"
},
{
"code": null,
"e": 51594,
"s": 51464,
"text": "Parameter : The method accepts a single parameter astr which are the Char sequence whose string representation is to be appended."
},
{
"code": null,
"e": 51693,
"s": 51594,
"text": "Return Value: The method returns a string object after the append operation is performed.Examples:"
},
{
"code": null,
"e": 51809,
"s": 51693,
"text": "Input :\nStringBuffer = I love my Country \nchar[] astr = 'I', 'N', 'D', 'I', 'A'\n\nOutput: I love my Country INDIA"
},
{
"code": null,
"e": 51890,
"s": 51809,
"text": "Below program illustrates the java.lang.StringBuffer.append(char[] astr) method:"
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append(<em>char[] astr</em>)import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); // Char array char[] astr = new char[] { 'G', 'E', 'E', 'k', 'S' }; /* Here it appends string representation of char array argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); // Char array astr = new char[] { 'a', 'b', 'c', 'd' }; /* Here it appends string representation of char array argument to argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}",
"e": 52851,
"s": 51890,
"text": null
},
{
"code": null,
"e": 52990,
"s": 52851,
"text": "We are geeks and its really \nResult after appending = We are geeks and its GEEkS\nWe are lost -\nResult after appending = We are lost -abcd\n"
},
{
"code": null,
"e": 54643,
"s": 52990,
"text": "StringBuffer append(char[] cstr, int iset, int ilength) : This method appends the string representation of a subarray of the char array argument to this sequence. The Characters of the char array cstr, starting at index iset, are appended, in order, to the contents of this sequence. The length of this sequence increases by the value of ilength.Syntax :public StringBuffer append(char[] cstr, int iset, int ilenght)Parameter : This method accepts three parameters:cstr – This refers to the Char sequence.iset – This refers to the index of the first char to append.ilenght – This refers to the number of chars to append.Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuffer.append(char[] cstr, int iset, int ilength) method.// Java program to illustrate the// java.lang.StringBuffer append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sb = new StringBuffer(\"Geeks\"); System.out.println(\" String buffer before = \" + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', 'b', 'e', 'a', 'g', 'e', 'e', 'k' }; /* appends the string representation of char array argument to this string buffer with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the string buffer after appending System.out.println(\"After appending string buffer = \" + sb); }}Output:String buffer before = Geeks\nAfter appending string buffer = GeeksforGeeks\n"
},
{
"code": null,
"e": 54652,
"s": 54643,
"text": "Syntax :"
},
{
"code": null,
"e": 54715,
"s": 54652,
"text": "public StringBuffer append(char[] cstr, int iset, int ilenght)"
},
{
"code": null,
"e": 54765,
"s": 54715,
"text": "Parameter : This method accepts three parameters:"
},
{
"code": null,
"e": 54806,
"s": 54765,
"text": "cstr – This refers to the Char sequence."
},
{
"code": null,
"e": 54867,
"s": 54806,
"text": "iset – This refers to the index of the first char to append."
},
{
"code": null,
"e": 54923,
"s": 54867,
"text": "ilenght – This refers to the number of chars to append."
},
{
"code": null,
"e": 55116,
"s": 54923,
"text": "Return Value: The method returns a string object after the append operation is performed.Below program illustrates the java.lang.StringBuffer.append(char[] cstr, int iset, int ilength) method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer append(char[] cstr, int iset, int ilength)import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sb = new StringBuffer(\"Geeks\"); System.out.println(\" String buffer before = \" + sb); char[] cstr = new char[] { 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's', 'b', 'e', 'a', 'g', 'e', 'e', 'k' }; /* appends the string representation of char array argument to this string buffer with offset initially at index 0 and length as 8 */ sb.append(cstr, 0, 8); // Print the string buffer after appending System.out.println(\"After appending string buffer = \" + sb); }}",
"e": 55874,
"s": 55116,
"text": null
},
{
"code": null,
"e": 55951,
"s": 55874,
"text": "String buffer before = Geeks\nAfter appending string buffer = GeeksforGeeks\n"
},
{
"code": null,
"e": 57531,
"s": 55951,
"text": "StringBuffer append(double a) : This method simply appends the string representation of the double argument to this StringBuffer sequence.Syntax :public StringBuffer append(double a)Parameter: The method accepts a single parameter a which refers to the decimal value whose string representation is to be appended.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country\nDouble a = 54.82\nOutput: I love my Country 54.82Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); // char array Double astr = new Double(636.47); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Double(827.38); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 636.47\nWe are lost -\nResult after appending = We are lost -827.38\n"
},
{
"code": null,
"e": 57540,
"s": 57531,
"text": "Syntax :"
},
{
"code": null,
"e": 57577,
"s": 57540,
"text": "public StringBuffer append(double a)"
},
{
"code": null,
"e": 57709,
"s": 57577,
"text": "Parameter: The method accepts a single parameter a which refers to the decimal value whose string representation is to be appended."
},
{
"code": null,
"e": 57809,
"s": 57709,
"text": "Return Value: The method returns a string object after the append operation is performed.Examples :"
},
{
"code": null,
"e": 57899,
"s": 57809,
"text": "Input :\nStringBuffer = I love my Country\nDouble a = 54.82\nOutput: I love my Country 54.82"
},
{
"code": null,
"e": 57969,
"s": 57899,
"text": "Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); // char array Double astr = new Double(636.47); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Double(827.38); /*Here it appends string representation of Double argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}",
"e": 58831,
"s": 57969,
"text": null
},
{
"code": null,
"e": 58973,
"s": 58831,
"text": "We are geeks and its really \nResult after appending = We are geeks and its 636.47\nWe are lost -\nResult after appending = We are lost -827.38\n"
},
{
"code": null,
"e": 60533,
"s": 58973,
"text": "StringBuffer append(float f) : This method appends the string representation of the float argument to this sequence.Syntax :public StringBuffer append(float a)Parameter: The method accepts a single parameter a which is the float value whose string representation is to be appended.Return Value: StringBuffer.append(float a) method returns a reference the string object after the operation is performed.Examples :Input : \n StringBuffer = I love my Country \nfloat a = 5.2\n \nOutput: I love my Country 5.2Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this string buffer sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 6.47\nWe are lost -\nResult after appending = We are lost -27.38\n"
},
{
"code": null,
"e": 60542,
"s": 60533,
"text": "Syntax :"
},
{
"code": null,
"e": 60578,
"s": 60542,
"text": "public StringBuffer append(float a)"
},
{
"code": null,
"e": 60701,
"s": 60578,
"text": "Parameter: The method accepts a single parameter a which is the float value whose string representation is to be appended."
},
{
"code": null,
"e": 60823,
"s": 60701,
"text": "Return Value: StringBuffer.append(float a) method returns a reference the string object after the operation is performed."
},
{
"code": null,
"e": 60834,
"s": 60823,
"text": "Examples :"
},
{
"code": null,
"e": 60932,
"s": 60834,
"text": "Input : \n StringBuffer = I love my Country \nfloat a = 5.2\n \nOutput: I love my Country 5.2"
},
{
"code": null,
"e": 61002,
"s": 60932,
"text": "Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Float astr = new Float(6.47); /* Here it appends string representation of Float argument to this string buffer */ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Float(27.38); // Here it appends string representation of Float // argument to this string buffer sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}",
"e": 61839,
"s": 61002,
"text": null
},
{
"code": null,
"e": 61978,
"s": 61839,
"text": "We are geeks and its really \nResult after appending = We are geeks and its 6.47\nWe are lost -\nResult after appending = We are lost -27.38\n"
},
{
"code": null,
"e": 63442,
"s": 61978,
"text": "StringBuffer append(int i :) This method simply appends the string representation of the int argument to this StringBuffer sequence.Syntax :public StringBuffer append(int a)Parameter: The method accepts a single parameter a which is the int value.Return Value: The method returns a reference to this object.Examples :Input :\nStringBuffer = I love my Country \nint a = 55\n\nOutput: I love my Country 55Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Integer astr = new Integer(827); /*Here it appends string representation of Integer argument to argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this string buffer sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 827\nWe are lost -\nResult after appending = We are lost -515\n"
},
{
"code": null,
"e": 63476,
"s": 63442,
"text": "public StringBuffer append(int a)"
},
{
"code": null,
"e": 63551,
"s": 63476,
"text": "Parameter: The method accepts a single parameter a which is the int value."
},
{
"code": null,
"e": 63612,
"s": 63551,
"text": "Return Value: The method returns a reference to this object."
},
{
"code": null,
"e": 63623,
"s": 63612,
"text": "Examples :"
},
{
"code": null,
"e": 63707,
"s": 63623,
"text": "Input :\nStringBuffer = I love my Country \nint a = 55\n\nOutput: I love my Country 55"
},
{
"code": null,
"e": 63777,
"s": 63707,
"text": "Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Integer astr = new Integer(827); /*Here it appends string representation of Integer argument to argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Integer(515); // Here it appends string representation of Integer // argument to this string buffer sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}",
"e": 64630,
"s": 63777,
"text": null
},
{
"code": null,
"e": 64766,
"s": 64630,
"text": "We are geeks and its really \nResult after appending = We are geeks and its 827\nWe are lost -\nResult after appending = We are lost -515\n"
},
{
"code": null,
"e": 66248,
"s": 64766,
"text": "StringBuffer append(Long l) : This method simply appends the string representation of the long argument to this StringBuffer sequence.Syntax :public StringBuffer append(Long a)Parameter : The method accepts a single parameter a which is the long value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country\nLong a = 591995\n\nOutput: I love my Country 591995Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Long astr = new Long(827); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Long(515); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}Output:We are geeks and its really \nResult after appending = We are geeks and its 827\nWe are lost -\nResult after appending = We are lost -515\n"
},
{
"code": null,
"e": 66257,
"s": 66248,
"text": "Syntax :"
},
{
"code": null,
"e": 66292,
"s": 66257,
"text": "public StringBuffer append(Long a)"
},
{
"code": null,
"e": 66369,
"s": 66292,
"text": "Parameter : The method accepts a single parameter a which is the long value."
},
{
"code": null,
"e": 66469,
"s": 66369,
"text": "Return Value: The method returns a string object after the append operation is performed.Examples :"
},
{
"code": null,
"e": 66561,
"s": 66469,
"text": "Input :\nStringBuffer = I love my Country\nLong a = 591995\n\nOutput: I love my Country 591995"
},
{
"code": null,
"e": 66631,
"s": 66561,
"text": "Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { System.out.println(\"We are geeks and its really \"); StringBuffer sbf = new StringBuffer(\"We are geeks and its \"); Long astr = new Long(827); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); System.out.println(\"We are lost -\"); sbf = new StringBuffer(\"We are lost -\"); astr = new Long(515); /* Here it appends string representation of Long argument to this string buffer*/ sbf.append(astr); System.out.println(\"Result after appending = \" + sbf); }}",
"e": 67460,
"s": 66631,
"text": null
},
{
"code": null,
"e": 67596,
"s": 67460,
"text": "We are geeks and its really \nResult after appending = We are geeks and its 827\nWe are lost -\nResult after appending = We are lost -515\n"
},
{
"code": null,
"e": 68652,
"s": 67596,
"text": "StringBuffer append(CharSequence a) : This method is used to append the specified CharSequence to this sequence.Syntax :public StringBuffer append(CharSequence a)Parameter: The method accepts a single parameter a which is the CharSequence value.Return Value: The method returns a string object after the append operation is performed.Examples :Input :\nStringBuffer = I love my Country \nCharSequence a = abcd\n\nOutput : I love my Countryabcd\nBelow program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\" string buffer = \" + sbf); CharSequence chSeq = \"geeks\"; // Appends the CharSequence sbf.append(chSeq); // Print the string buffer after appending System.out.println(\"After append = \" + sbf); }}Output:string buffer = Geeksfor\nAfter append = Geeksforgeeks\n"
},
{
"code": null,
"e": 68661,
"s": 68652,
"text": "Syntax :"
},
{
"code": null,
"e": 68704,
"s": 68661,
"text": "public StringBuffer append(CharSequence a)"
},
{
"code": null,
"e": 68788,
"s": 68704,
"text": "Parameter: The method accepts a single parameter a which is the CharSequence value."
},
{
"code": null,
"e": 68878,
"s": 68788,
"text": "Return Value: The method returns a string object after the append operation is performed."
},
{
"code": null,
"e": 68889,
"s": 68878,
"text": "Examples :"
},
{
"code": null,
"e": 68990,
"s": 68889,
"text": "Input :\nStringBuffer = I love my Country \nCharSequence a = abcd\n\nOutput : I love my Countryabcd\n"
},
{
"code": null,
"e": 69060,
"s": 68990,
"text": "Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append()import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\" string buffer = \" + sbf); CharSequence chSeq = \"geeks\"; // Appends the CharSequence sbf.append(chSeq); // Print the string buffer after appending System.out.println(\"After append = \" + sbf); }}",
"e": 69542,
"s": 69060,
"text": null
},
{
"code": null,
"e": 69597,
"s": 69542,
"text": "string buffer = Geeksfor\nAfter append = Geeksforgeeks\n"
},
{
"code": null,
"e": 70965,
"s": 69597,
"text": "StringBuffer append(CharSequence chseq, int start, int end) : This method is used to append a subsequence of the specified CharSequence to this StringBuffer.Syntax :StringBuffer append(CharSequence chseq, int start, int end)Parameter : The method accepts a three parameter:chseq(CharSequence): This refers to the CharSequence value.start(Integer): This refers to the starting index of the subsequence to be appended..end(Integer): This refers to the end index of the subsequence to be appended.Return Value : The method returns the string after the append operation is performed.Examples :Input :\nStringBuffer = Geeksforgeeks\nCharSequence chseq = abcd1234\nint start = 2\nint end = 7\n\nOutput :Geeksforgeekscd123\nBelow program illustrates the java.lang.StringBuffer.append() method:// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"we are the \"); System.out.println(\" string buffer = \" + sbf); CharSequence chSeq = \"wegeekss\"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println(\"After append string buffer = \" + sbf); }}Output:string buffer = we are the \nAfter append string buffer = we are the geeks\n"
},
{
"code": null,
"e": 70974,
"s": 70965,
"text": "Syntax :"
},
{
"code": null,
"e": 71034,
"s": 70974,
"text": "StringBuffer append(CharSequence chseq, int start, int end)"
},
{
"code": null,
"e": 71084,
"s": 71034,
"text": "Parameter : The method accepts a three parameter:"
},
{
"code": null,
"e": 71144,
"s": 71084,
"text": "chseq(CharSequence): This refers to the CharSequence value."
},
{
"code": null,
"e": 71230,
"s": 71144,
"text": "start(Integer): This refers to the starting index of the subsequence to be appended.."
},
{
"code": null,
"e": 71308,
"s": 71230,
"text": "end(Integer): This refers to the end index of the subsequence to be appended."
},
{
"code": null,
"e": 71394,
"s": 71308,
"text": "Return Value : The method returns the string after the append operation is performed."
},
{
"code": null,
"e": 71405,
"s": 71394,
"text": "Examples :"
},
{
"code": null,
"e": 71527,
"s": 71405,
"text": "Input :\nStringBuffer = Geeksforgeeks\nCharSequence chseq = abcd1234\nint start = 2\nint end = 7\n\nOutput :Geeksforgeekscd123\n"
},
{
"code": null,
"e": 71597,
"s": 71527,
"text": "Below program illustrates the java.lang.StringBuffer.append() method:"
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"we are the \"); System.out.println(\" string buffer = \" + sbf); CharSequence chSeq = \"wegeekss\"; /* It appends the CharSequence with start index 2 and end index 4 */ sbf.append(chSeq, 2, 7); System.out.println(\"After append string buffer = \" + sbf); }}",
"e": 72105,
"s": 71597,
"text": null
},
{
"code": null,
"e": 72180,
"s": 72105,
"text": "string buffer = we are the \nAfter append string buffer = we are the geeks\n"
},
{
"code": null,
"e": 73150,
"s": 72180,
"text": "StringBuffer append(Object obj) : This method is used to append the string representation of the Object argument to the StringBuffer.Syntax :StringBuffer append(Object obj)Parameter : The method accepts a single parameter obj which refers to the object needed to be appended.Return Value : The method returns the string after performing the append operation.Below programs illustrate the java.lang.StringBuffer.append() method.Program :// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\"string buffer = \" + sbf); Object objectvalue = \"geeks\"; // Here it appends the Object value sbf.append(objectvalue); System.out.println(\"After appending result is = \" + sbf); }}Output:string buffer = Geeksfor\nAfter appending result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 73159,
"s": 73150,
"text": "Syntax :"
},
{
"code": null,
"e": 73191,
"s": 73159,
"text": "StringBuffer append(Object obj)"
},
{
"code": null,
"e": 73295,
"s": 73191,
"text": "Parameter : The method accepts a single parameter obj which refers to the object needed to be appended."
},
{
"code": null,
"e": 73379,
"s": 73295,
"text": "Return Value : The method returns the string after performing the append operation."
},
{
"code": null,
"e": 73449,
"s": 73379,
"text": "Below programs illustrate the java.lang.StringBuffer.append() method."
},
{
"code": null,
"e": 73459,
"s": 73449,
"text": "Program :"
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\"string buffer = \" + sbf); Object objectvalue = \"geeks\"; // Here it appends the Object value sbf.append(objectvalue); System.out.println(\"After appending result is = \" + sbf); }}",
"e": 73919,
"s": 73459,
"text": null
},
{
"code": null,
"e": 73987,
"s": 73919,
"text": "string buffer = Geeksfor\nAfter appending result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 74921,
"s": 73987,
"text": "StringBuffer append(String istr) : This method is used to append the specified string to this StringBuffer.Syntax :StringBuffer append(String istr)Parameter : The method accepts a single parameter istr of String type which refer to the value to be appended.Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\"string buffer = \" + sbf); String strvalue = \"geeks\"; // Here it appends the Object value sbf.append(strvalue); System.out.println(\"After appending result is = \" + sbf); }}Output:string buffer = Geeksfor\nAfter appending result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 74954,
"s": 74921,
"text": "StringBuffer append(String istr)"
},
{
"code": null,
"e": 75065,
"s": 74954,
"text": "Parameter : The method accepts a single parameter istr of String type which refer to the value to be appended."
},
{
"code": null,
"e": 75215,
"s": 75065,
"text": "Return Value : The method returns a specified string to this character sequence.Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf = new StringBuffer(\"Geeksfor\"); System.out.println(\"string buffer = \" + sbf); String strvalue = \"geeks\"; // Here it appends the Object value sbf.append(strvalue); System.out.println(\"After appending result is = \" + sbf); }}",
"e": 75669,
"s": 75215,
"text": null
},
{
"code": null,
"e": 75737,
"s": 75669,
"text": "string buffer = Geeksfor\nAfter appending result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 76799,
"s": 75737,
"text": "StringBuffer append(StringBuffer sbf) : This method is used to append the specified StringBuffer to this sequence or StringBuffer.Syntax :public StringBuffer append(StringBuffer sbf)Parameter : The method accepts a single parameter sbf refers to the StringBuffer to append.Return Value : The method returns StringBuffer to this sequence.Below program illustrates the java.lang.StringBuffer.append() method.// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer(\"Geeks\"); System.out.println(\"String buffer 1 = \" + sbf1); StringBuffer sbf2 = new StringBuffer(\"forgeeks \"); System.out.println(\"String buffer 2 = \" + sbf2); // Here it appends stringbuffer2 to stringbuffer1 sbf1.append(sbf2); System.out.println(\"After appending the result is = \" + sbf1); }}Output:String buffer 1 = Geeks\nString buffer 2 = forgeeks \nAfter appending the result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 76808,
"s": 76799,
"text": "Syntax :"
},
{
"code": null,
"e": 76853,
"s": 76808,
"text": "public StringBuffer append(StringBuffer sbf)"
},
{
"code": null,
"e": 76945,
"s": 76853,
"text": "Parameter : The method accepts a single parameter sbf refers to the StringBuffer to append."
},
{
"code": null,
"e": 77079,
"s": 76945,
"text": "Return Value : The method returns StringBuffer to this sequence.Below program illustrates the java.lang.StringBuffer.append() method."
},
{
"code": "// Java program to illustrate the// java.lang.StringBuffer.append() import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer(\"Geeks\"); System.out.println(\"String buffer 1 = \" + sbf1); StringBuffer sbf2 = new StringBuffer(\"forgeeks \"); System.out.println(\"String buffer 2 = \" + sbf2); // Here it appends stringbuffer2 to stringbuffer1 sbf1.append(sbf2); System.out.println(\"After appending the result is = \" + sbf1); }}",
"e": 77630,
"s": 77079,
"text": null
},
{
"code": null,
"e": 77729,
"s": 77630,
"text": "String buffer 1 = Geeks\nString buffer 2 = forgeeks \nAfter appending the result is = Geeksforgeeks\n"
},
{
"code": null,
"e": 77741,
"s": 77729,
"text": "anikaseth98"
},
{
"code": null,
"e": 77756,
"s": 77741,
"text": "Java-Functions"
},
{
"code": null,
"e": 77774,
"s": 77756,
"text": "Java-lang package"
},
{
"code": null,
"e": 77792,
"s": 77774,
"text": "java-StringBuffer"
},
{
"code": null,
"e": 77797,
"s": 77792,
"text": "Java"
},
{
"code": null,
"e": 77802,
"s": 77797,
"text": "Java"
},
{
"code": null,
"e": 77900,
"s": 77802,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 77951,
"s": 77900,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 77981,
"s": 77951,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 78000,
"s": 77981,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 78015,
"s": 78000,
"text": "Stream In Java"
},
{
"code": null,
"e": 78046,
"s": 78015,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 78064,
"s": 78046,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 78096,
"s": 78064,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 78116,
"s": 78096,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 78148,
"s": 78116,
"text": "Multidimensional Arrays in Java"
}
]
|
How to remove all .pyc files in Python? - GeeksforGeeks | 19 Dec, 2021
In this article, we are going to see how to remove all .pyc files in Python.
A *.pyc file is created by the Python interpreter when a *.py file is imported into any other python file. The *.pyc file contains the “compiled bytecode” of the imported module/program so that the “translation” from source code to bytecode can be skipped on subsequent imports of the *.py file. Having a *.pyc file saves the compilation time of converting the python source code to byte code, every time the file is imported. Thus speeding startup a little. But it’s still interpreted. Once the *.pyc file is generated, there is no need for the *.py file, unless the *.py file is modified. In Python 3.2, the compiled files (.pyc) are placed in a __pycache__ subdirectory and are named differently depending on which Python interpreter created them.
Before executing a python program python interpreter checks for the .pyc file. If the file is present, the virtual machine executes it. If not found, it checks for the .py file. If found, compile it to a .pyc file and then the python virtual machine executes it.
while working on a project having the extra .pyc file unnecessarily increases the file size. or to solve any terrible importing error, the .pyc are needed to be removed.
On OS X and Linux find method can be used to find all of the .pyc files, and then use its delete option to delete them. (In windows open windows terminal to use the find method).
The command to find all .pyc files in all folders, starting with the current one is:
find. -name '*.pyc'
If you want to delete all the files found, just add the -delete option:
find. -name '*.pyc' -delete
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 25614,
"s": 25537,
"text": "In this article, we are going to see how to remove all .pyc files in Python."
},
{
"code": null,
"e": 26365,
"s": 25614,
"text": "A *.pyc file is created by the Python interpreter when a *.py file is imported into any other python file. The *.pyc file contains the “compiled bytecode” of the imported module/program so that the “translation” from source code to bytecode can be skipped on subsequent imports of the *.py file. Having a *.pyc file saves the compilation time of converting the python source code to byte code, every time the file is imported. Thus speeding startup a little. But it’s still interpreted. Once the *.pyc file is generated, there is no need for the *.py file, unless the *.py file is modified. In Python 3.2, the compiled files (.pyc) are placed in a __pycache__ subdirectory and are named differently depending on which Python interpreter created them."
},
{
"code": null,
"e": 26628,
"s": 26365,
"text": "Before executing a python program python interpreter checks for the .pyc file. If the file is present, the virtual machine executes it. If not found, it checks for the .py file. If found, compile it to a .pyc file and then the python virtual machine executes it."
},
{
"code": null,
"e": 26798,
"s": 26628,
"text": "while working on a project having the extra .pyc file unnecessarily increases the file size. or to solve any terrible importing error, the .pyc are needed to be removed."
},
{
"code": null,
"e": 26977,
"s": 26798,
"text": "On OS X and Linux find method can be used to find all of the .pyc files, and then use its delete option to delete them. (In windows open windows terminal to use the find method)."
},
{
"code": null,
"e": 27062,
"s": 26977,
"text": "The command to find all .pyc files in all folders, starting with the current one is:"
},
{
"code": null,
"e": 27082,
"s": 27062,
"text": "find. -name '*.pyc'"
},
{
"code": null,
"e": 27154,
"s": 27082,
"text": "If you want to delete all the files found, just add the -delete option:"
},
{
"code": null,
"e": 27183,
"s": 27154,
"text": "find. -name '*.pyc' -delete"
},
{
"code": null,
"e": 27190,
"s": 27183,
"text": "Picked"
},
{
"code": null,
"e": 27197,
"s": 27190,
"text": "Python"
},
{
"code": null,
"e": 27295,
"s": 27197,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27327,
"s": 27295,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27369,
"s": 27327,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27411,
"s": 27369,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27438,
"s": 27411,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27494,
"s": 27438,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27533,
"s": 27494,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27555,
"s": 27533,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27586,
"s": 27555,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27615,
"s": 27586,
"text": "Create a directory in Python"
}
]
|
Logging Script Errors in JavaScript - GeeksforGeeks | 26 Sep, 2021
In this article, we will learn to log script Errors using JavaScript. It is useful in case where scripts from any other source run/executes under the website (Ex – in an iframe) or cases where any of your viewer makes use of Browser’s Console trying to alter the script or you want to monitor your JS code for errors it may get into when put in production.
Approach: We will learn 3 methods to accomplish this task — all following the same approach but different way to implement the approach and extract the useful Information. Use whichever suits best in your case.
window.addEventListener(“error”, //yourErrorLoggerFunction) — Attach an error event to the window object (DOM).document.querySelector(‘body’).onerror= //yourErrorLoggerFunction — Error Listener in the body tag -> Works both in Same Origin or Cross-Scripts of Same Origin.Create a script element and append it to the body tag of the source.
window.addEventListener(“error”, //yourErrorLoggerFunction) — Attach an error event to the window object (DOM).
document.querySelector(‘body’).onerror= //yourErrorLoggerFunction — Error Listener in the body tag -> Works both in Same Origin or Cross-Scripts of Same Origin.
Create a script element and append it to the body tag of the source.
All three method can be implemented both in same source or any external source.
Note — Make sure this is the first thing to be executed by the browser (In case you are not sure it is strongly recommended to use Method 2).
Method 1: In this method, we will attach an Event Listener to our window object. Whenever any script error occurs, the attached errorLogger Function is triggered and inside the errorLoggerFunction we will extract all useful information from the event Object that our errorLogger function receives.
Javascript
window.addEventListener("error", errorLog); function errorLog(event) { // Declare all variables as null // necessary in case of multiple // errors to be logged let msg = source = lineno = colno = error = time = ""; // Use prevent default in case you // don't want the error to be logged // in the console / hide the error event.preventDefault(); msg = event.message; source = event.filename; lineno = event.lineno; colno = event.colno; error = event.error; time = event.time; // This time is in ms and tells us // time after which the error occured // after the page was loaded // a lot other information can be // gathered - explore the event object // After extracting all the information // from this object now log it on your // server Database}
Find the HTML Code (Method 1):
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <title>Document</title></head> <body> <p style="font-size:20px;color:rgb(219, 0, 0)"> No Errors </p> <script> // Make Sure addEventListener is the // First thing to be Executed window.addEventListener("error", errorLog); // String to Prepare Error Paragraph let errorString = ""; const pElement = document.querySelector('p'); // This console.log creates Error console.log(a) function errorLog(event) { let msg = source = lineno = colno = error = time = ""; event.preventDefault(); msg = event.message; source = event.filename; lineno = event.lineno; colno = event.colno; error = event.error; time = event.time; errorString = `Script Error was Found<br> Message-: ${msg}<br>Source Info-: ${source} <br>Line No-: ${lineno}<br>Column No-: ${colno}<br>Error Info-: ${error}<br>Time at which Error Occured-: ${time}ms after Page Load<br><br><br><br>`; pElement.innerHTML = errorString; } </script></body> </html>
Example -METHOD 1
Method 2: In this method, we will make use of onerror Event Handler.
Step 1 — Get the body tag of that HTML Markup whichever is your case either the external HTML Markup or the Markup of the Currently loading Page.
Step 2 — Now when we have got the body tag in a const identifier let say const bodyTag we will add onerror Event Handler to the bodyTag.
Javascript
const bodyTag = // body tag of External HTML // Markup or of your page bodyTag.onerror = errorLogger; function errorLogger(msg, url, lineNo, columnNo, error) { // Now process your Error // Information as you desire}
Did you notice the difference in the logger function of the above two methods — Usually in case of firing of any event, the function attached to it receives an event object but in this case (method 2) we receive a pre-extracted information (For Detailed Reason Refer MDN WebDocs).
Note — Keep in mind the order of error information received in the loggerFunction- Total 5 Information — Sequence always being the same.
Find the HTML Code (Method 2):
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body onerror="errorLogger(message, source, lineno, colno, error)"> <p style="font-size:20px; color:rgb(219, 0, 0)"> </p> <script> // You can directly set the onerror // Attribute or use below 2 lines // Get body tag of External HTML // Markup or of your current page const bodyTag = document.querySelector('body'); // bodyTag.onerror = errorLogger; let errorString = ""; const pElement = document.querySelector('p'); function errorLogger(msg, url, lineNo, colNo, error) { // Now process your Error Information // as you desire errorString += `Script Error was Found <br>Message-: ${msg}<br>URL-: ${url} <br>Line No-: ${lineNo}<br>Column No-: ${colNo}<br>Error Info-: ${error}<br> <br><br><br>`; pElement.innerHTML += errorString; } </script></body> </html>
Example – METHOD 2
Method 3: In this method, we will attach a script element to the WebPage. This method is useful in cases when we want error logger to activate at a specific time or in cases of external script execution, etc.
Step 1 — Get the body tag of the Markup Page you are targeting it.
Step 2 — Prepare a script element and append it.
Javascript
const htmlDOM = // Get the DOM of //the Target Markup let errScr = htmlDOM.document .createElement('script'); errScr.type = 'text/javascript'; errScr.innerText = `window.addEventListener("error", errorLog);function errorLog(event) { //process the event object}`; htmlDOM.document.querySelector ('body').append(errScr);
Example – METHOD 3
Explanation of example — Method 3: As you can notice we have used iframe to access index.html of the same Page(Same-Origin) we planted a script in parentPage to logg errors in another WebPage.
Warning — Although you will be blocked but Beware Using these Methods in case of CROSS-SCRIPTING (CORS) (Scripts of Different Origin) without written permission from the owner of that Page.
Find the HTML Code (Method 3):
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"></head> <body> <iframe src="index.html" frameborder="0"> </iframe> <script> const htmlDOM = document .querySelector('iframe').contentDocument; let errScr = htmlDOM.createElement('script'); errScr.type = 'text/javascript'; errScr.innerText = `console.log("Script Loaded");window.addEventListener("error", errorLog);function errorLog(event){ console.log("Error can be Processed Now....Use the eventObject as used in method-1")}`; htmlDOM.querySelector('body').append(errScr); </script></body> </html>
Important Note –
You can make use of both innerText and innerHTML to write the js script but we recommend using innerText as presence any HTML entity in the script would create any unwanted error.In method 3, the target and the way of getting them may differ in different cases. So the code used in the implementation of this method may differ slightly but the approach would remain same.
You can make use of both innerText and innerHTML to write the js script but we recommend using innerText as presence any HTML entity in the script would create any unwanted error.
In method 3, the target and the way of getting them may differ in different cases. So the code used in the implementation of this method may differ slightly but the approach would remain same.
anikaseth98
anikakapoor
ruhelaa48
JavaScript-Errors
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 26139,
"s": 26111,
"text": "\n26 Sep, 2021"
},
{
"code": null,
"e": 26496,
"s": 26139,
"text": "In this article, we will learn to log script Errors using JavaScript. It is useful in case where scripts from any other source run/executes under the website (Ex – in an iframe) or cases where any of your viewer makes use of Browser’s Console trying to alter the script or you want to monitor your JS code for errors it may get into when put in production."
},
{
"code": null,
"e": 26707,
"s": 26496,
"text": "Approach: We will learn 3 methods to accomplish this task — all following the same approach but different way to implement the approach and extract the useful Information. Use whichever suits best in your case."
},
{
"code": null,
"e": 27047,
"s": 26707,
"text": "window.addEventListener(“error”, //yourErrorLoggerFunction) — Attach an error event to the window object (DOM).document.querySelector(‘body’).onerror= //yourErrorLoggerFunction — Error Listener in the body tag -> Works both in Same Origin or Cross-Scripts of Same Origin.Create a script element and append it to the body tag of the source."
},
{
"code": null,
"e": 27159,
"s": 27047,
"text": "window.addEventListener(“error”, //yourErrorLoggerFunction) — Attach an error event to the window object (DOM)."
},
{
"code": null,
"e": 27320,
"s": 27159,
"text": "document.querySelector(‘body’).onerror= //yourErrorLoggerFunction — Error Listener in the body tag -> Works both in Same Origin or Cross-Scripts of Same Origin."
},
{
"code": null,
"e": 27389,
"s": 27320,
"text": "Create a script element and append it to the body tag of the source."
},
{
"code": null,
"e": 27469,
"s": 27389,
"text": "All three method can be implemented both in same source or any external source."
},
{
"code": null,
"e": 27611,
"s": 27469,
"text": "Note — Make sure this is the first thing to be executed by the browser (In case you are not sure it is strongly recommended to use Method 2)."
},
{
"code": null,
"e": 27909,
"s": 27611,
"text": "Method 1: In this method, we will attach an Event Listener to our window object. Whenever any script error occurs, the attached errorLogger Function is triggered and inside the errorLoggerFunction we will extract all useful information from the event Object that our errorLogger function receives."
},
{
"code": null,
"e": 27920,
"s": 27909,
"text": "Javascript"
},
{
"code": "window.addEventListener(\"error\", errorLog); function errorLog(event) { // Declare all variables as null // necessary in case of multiple // errors to be logged let msg = source = lineno = colno = error = time = \"\"; // Use prevent default in case you // don't want the error to be logged // in the console / hide the error event.preventDefault(); msg = event.message; source = event.filename; lineno = event.lineno; colno = event.colno; error = event.error; time = event.time; // This time is in ms and tells us // time after which the error occured // after the page was loaded // a lot other information can be // gathered - explore the event object // After extracting all the information // from this object now log it on your // server Database}",
"e": 28757,
"s": 27920,
"text": null
},
{
"code": null,
"e": 28788,
"s": 28757,
"text": "Find the HTML Code (Method 1):"
},
{
"code": null,
"e": 28793,
"s": 28788,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <title>Document</title></head> <body> <p style=\"font-size:20px;color:rgb(219, 0, 0)\"> No Errors </p> <script> // Make Sure addEventListener is the // First thing to be Executed window.addEventListener(\"error\", errorLog); // String to Prepare Error Paragraph let errorString = \"\"; const pElement = document.querySelector('p'); // This console.log creates Error console.log(a) function errorLog(event) { let msg = source = lineno = colno = error = time = \"\"; event.preventDefault(); msg = event.message; source = event.filename; lineno = event.lineno; colno = event.colno; error = event.error; time = event.time; errorString = `Script Error was Found<br> Message-: ${msg}<br>Source Info-: ${source} <br>Line No-: ${lineno}<br>Column No-: ${colno}<br>Error Info-: ${error}<br>Time at which Error Occured-: ${time}ms after Page Load<br><br><br><br>`; pElement.innerHTML = errorString; } </script></body> </html>",
"e": 30158,
"s": 28793,
"text": null
},
{
"code": null,
"e": 30176,
"s": 30158,
"text": "Example -METHOD 1"
},
{
"code": null,
"e": 30246,
"s": 30176,
"text": "Method 2: In this method, we will make use of onerror Event Handler. "
},
{
"code": null,
"e": 30392,
"s": 30246,
"text": "Step 1 — Get the body tag of that HTML Markup whichever is your case either the external HTML Markup or the Markup of the Currently loading Page."
},
{
"code": null,
"e": 30529,
"s": 30392,
"text": "Step 2 — Now when we have got the body tag in a const identifier let say const bodyTag we will add onerror Event Handler to the bodyTag."
},
{
"code": null,
"e": 30540,
"s": 30529,
"text": "Javascript"
},
{
"code": "const bodyTag = // body tag of External HTML // Markup or of your page bodyTag.onerror = errorLogger; function errorLogger(msg, url, lineNo, columnNo, error) { // Now process your Error // Information as you desire}",
"e": 30776,
"s": 30540,
"text": null
},
{
"code": null,
"e": 31057,
"s": 30776,
"text": "Did you notice the difference in the logger function of the above two methods — Usually in case of firing of any event, the function attached to it receives an event object but in this case (method 2) we receive a pre-extracted information (For Detailed Reason Refer MDN WebDocs)."
},
{
"code": null,
"e": 31194,
"s": 31057,
"text": "Note — Keep in mind the order of error information received in the loggerFunction- Total 5 Information — Sequence always being the same."
},
{
"code": null,
"e": 31225,
"s": 31194,
"text": "Find the HTML Code (Method 2):"
},
{
"code": null,
"e": 31230,
"s": 31225,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body onerror=\"errorLogger(message, source, lineno, colno, error)\"> <p style=\"font-size:20px; color:rgb(219, 0, 0)\"> </p> <script> // You can directly set the onerror // Attribute or use below 2 lines // Get body tag of External HTML // Markup or of your current page const bodyTag = document.querySelector('body'); // bodyTag.onerror = errorLogger; let errorString = \"\"; const pElement = document.querySelector('p'); function errorLogger(msg, url, lineNo, colNo, error) { // Now process your Error Information // as you desire errorString += `Script Error was Found <br>Message-: ${msg}<br>URL-: ${url} <br>Line No-: ${lineNo}<br>Column No-: ${colNo}<br>Error Info-: ${error}<br> <br><br><br>`; pElement.innerHTML += errorString; } </script></body> </html>",
"e": 32388,
"s": 31230,
"text": null
},
{
"code": null,
"e": 32410,
"s": 32391,
"text": "Example – METHOD 2"
},
{
"code": null,
"e": 32621,
"s": 32412,
"text": "Method 3: In this method, we will attach a script element to the WebPage. This method is useful in cases when we want error logger to activate at a specific time or in cases of external script execution, etc."
},
{
"code": null,
"e": 32688,
"s": 32621,
"text": "Step 1 — Get the body tag of the Markup Page you are targeting it."
},
{
"code": null,
"e": 32738,
"s": 32688,
"text": "Step 2 — Prepare a script element and append it. "
},
{
"code": null,
"e": 32749,
"s": 32738,
"text": "Javascript"
},
{
"code": "const htmlDOM = // Get the DOM of //the Target Markup let errScr = htmlDOM.document .createElement('script'); errScr.type = 'text/javascript'; errScr.innerText = `window.addEventListener(\"error\", errorLog);function errorLog(event) { //process the event object}`; htmlDOM.document.querySelector ('body').append(errScr);",
"e": 33106,
"s": 32749,
"text": null
},
{
"code": null,
"e": 33125,
"s": 33106,
"text": "Example – METHOD 3"
},
{
"code": null,
"e": 33318,
"s": 33125,
"text": "Explanation of example — Method 3: As you can notice we have used iframe to access index.html of the same Page(Same-Origin) we planted a script in parentPage to logg errors in another WebPage."
},
{
"code": null,
"e": 33508,
"s": 33318,
"text": "Warning — Although you will be blocked but Beware Using these Methods in case of CROSS-SCRIPTING (CORS) (Scripts of Different Origin) without written permission from the owner of that Page."
},
{
"code": null,
"e": 33539,
"s": 33508,
"text": "Find the HTML Code (Method 3):"
},
{
"code": null,
"e": 33544,
"s": 33539,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"></head> <body> <iframe src=\"index.html\" frameborder=\"0\"> </iframe> <script> const htmlDOM = document .querySelector('iframe').contentDocument; let errScr = htmlDOM.createElement('script'); errScr.type = 'text/javascript'; errScr.innerText = `console.log(\"Script Loaded\");window.addEventListener(\"error\", errorLog);function errorLog(event){ console.log(\"Error can be Processed Now....Use the eventObject as used in method-1\")}`; htmlDOM.querySelector('body').append(errScr); </script></body> </html>",
"e": 34321,
"s": 33544,
"text": null
},
{
"code": null,
"e": 34338,
"s": 34321,
"text": "Important Note –"
},
{
"code": null,
"e": 34710,
"s": 34338,
"text": "You can make use of both innerText and innerHTML to write the js script but we recommend using innerText as presence any HTML entity in the script would create any unwanted error.In method 3, the target and the way of getting them may differ in different cases. So the code used in the implementation of this method may differ slightly but the approach would remain same."
},
{
"code": null,
"e": 34890,
"s": 34710,
"text": "You can make use of both innerText and innerHTML to write the js script but we recommend using innerText as presence any HTML entity in the script would create any unwanted error."
},
{
"code": null,
"e": 35083,
"s": 34890,
"text": "In method 3, the target and the way of getting them may differ in different cases. So the code used in the implementation of this method may differ slightly but the approach would remain same."
},
{
"code": null,
"e": 35095,
"s": 35083,
"text": "anikaseth98"
},
{
"code": null,
"e": 35107,
"s": 35095,
"text": "anikakapoor"
},
{
"code": null,
"e": 35117,
"s": 35107,
"text": "ruhelaa48"
},
{
"code": null,
"e": 35135,
"s": 35117,
"text": "JavaScript-Errors"
},
{
"code": null,
"e": 35140,
"s": 35135,
"text": "HTML"
},
{
"code": null,
"e": 35151,
"s": 35140,
"text": "JavaScript"
},
{
"code": null,
"e": 35168,
"s": 35151,
"text": "Web Technologies"
},
{
"code": null,
"e": 35173,
"s": 35168,
"text": "HTML"
},
{
"code": null,
"e": 35271,
"s": 35173,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35295,
"s": 35271,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 35336,
"s": 35295,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 35373,
"s": 35336,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 35402,
"s": 35373,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 35422,
"s": 35402,
"text": "Angular File Upload"
},
{
"code": null,
"e": 35462,
"s": 35422,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35507,
"s": 35462,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35568,
"s": 35507,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35640,
"s": 35568,
"text": "Differences between Functional Components and Class Components in React"
}
]
|
C++ Program to Find a triplet that sum to a given value - GeeksforGeeks | 21 Dec, 2021
Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false.
Examples:
Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There is a triplet (12, 3 and 9) present in the array whose sum is 24. Input: array = {1, 2, 3, 4, 5}, sum = 9 Output: 5, 3, 1 Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9.
Method 1: This is the naive approach towards solving the above problem.
Approach: A simple method is to generate all possible triplets and compare the sum of every triplet with the given value. The following code implements this simple method using three nested loops.
Algorithm: Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist.
Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist.
Given an array of length n and a sum s
Create three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)
The counter of these loops represents the index of 3 elements of the triplets.
Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.
If there is no triplet, then print that no triplet exist.
Implementation:
C++
#include <bits/stdc++.h>using namespace std; // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet bool find3Numbers(int A[], int arr_size, int sum) { int l, r; // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j < arr_size - 1; j++) { // Now look for the third number for (int k = j + 1; k < arr_size; k++) { if (A[i] + A[j] + A[k] == sum) { cout << "Triplet is " << A[i] << ", " << A[j] << ", " << A[k]; return true; } } } } // If we reach here, then no triplet was found return false; } /* Driver code */int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0; } // This is code is contributed by rathbhupendra
Triplet is 4, 10, 8
Complexity Analysis: Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)Space Complexity: O(1). As no extra space is required.
Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)
Space Complexity: O(1). As no extra space is required.
Method 2: This method uses sorting to increase the efficiency of the code.
Approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop.
Algorithm : Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
Sort the given array.
Loop over the array and fix the first element of the possible triplet, arr[i].
Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
If the sum is smaller than the required sum, increment the first pointer.
Else, If the sum is bigger, Decrease the end pointer to reduce the sum.
Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break.
Implementation:
C++
// C++ program to find a triplet#include <bits/stdc++.h>using namespace std; // returns true if there is triplet with sum equal// to 'sum' present in A[]. Also, prints the tripletbool find3Numbers(int A[], int arr_size, int sum){ int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now fix the first element one by one and find the other two elements */ for (int i = 0; i < arr_size - 2; i++) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other l = i + 1; // index of the first element in the // remaining elements r = arr_size - 1; // index of the last element while (l < r) { if (A[i] + A[l] + A[r] == sum) { printf("Triplet is %d, %d, %d", A[i], A[l], A[r]); return true; } else if (A[i] + A[l] + A[r] < sum) l++; else // A[i] + A[l] + A[r] > sum r--; } } // If we reach here, then no triplet was found return false;} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0;}
Triplet is 4, 8, 10
Complexity Analysis: Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.Space Complexity: O(1). As no extra space is required.
Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.
Space Complexity: O(1). As no extra space is required.
Method 3: This is a Hashing-based solution.
Approach: This approach uses extra space but is simpler than the two-pointers approach. Run two loops outer loop from start to end and inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x – arr[i] – arr[j]. If yes print the triplet.
Algorithm: Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set.
Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set.
Traverse the array from start to end. (loop counter i)
Create a HashMap or set to store unique pairs.
Run another loop from i+1 to end of the array. (loop counter j)
If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break
Insert the jth element in the set.
Implementation:
C++
// C++ program to find a triplet using Hashing#include <bits/stdc++.h>using namespace std; // returns true if there is triplet with sum equal// to 'sum' present in A[]. Also, prints the tripletbool find3Numbers(int A[], int arr_size, int sum){ // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Find pair in subarray A[i+1..n-1] // with sum equal to sum - A[i] unordered_set<int> s; int curr_sum = sum - A[i]; for (int j = i + 1; j < arr_size; j++) { if (s.find(curr_sum - A[j]) != s.end()) { printf("Triplet is %d, %d, %d", A[i], A[j], curr_sum - A[j]); return true; } s.insert(A[j]); } } // If we reach here, then no triplet was found return false;} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0;}
Output:
Triplet is 4, 8, 10
Time complexity: O(N^2) Auxiliary Space: O(N)
Please refer complete article on Find a triplet that sum to a given value for more details!
Accolite
Amazon
CarWale
Morgan Stanley
Samsung
two-pointer-algorithm
Arrays
C++
C++ Programs
Sorting
Morgan Stanley
Accolite
Amazon
Samsung
CarWale
two-pointer-algorithm
Arrays
Sorting
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 26248,
"s": 26041,
"text": "Given an array and a value, find if there is a triplet in array whose sum is equal to the given value. If there is such a triplet present in array, then print the triplet and return true. Else return false."
},
{
"code": null,
"e": 26260,
"s": 26248,
"text": "Examples: "
},
{
"code": null,
"e": 26545,
"s": 26260,
"text": "Input: array = {12, 3, 4, 1, 6, 9}, sum = 24; Output: 12, 3, 9 Explanation: There is a triplet (12, 3 and 9) present in the array whose sum is 24. Input: array = {1, 2, 3, 4, 5}, sum = 9 Output: 5, 3, 1 Explanation: There is a triplet (5, 3 and 1) present in the array whose sum is 9."
},
{
"code": null,
"e": 26623,
"s": 26549,
"text": "Method 1: This is the naive approach towards solving the above problem. "
},
{
"code": null,
"e": 26822,
"s": 26625,
"text": "Approach: A simple method is to generate all possible triplets and compare the sum of every triplet with the given value. The following code implements this simple method using three nested loops."
},
{
"code": null,
"e": 27290,
"s": 26822,
"text": "Algorithm: Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist."
},
{
"code": null,
"e": 27747,
"s": 27290,
"text": "Given an array of length n and a sum sCreate three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)The counter of these loops represents the index of 3 elements of the triplets.Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break.If there is no triplet, then print that no triplet exist."
},
{
"code": null,
"e": 27786,
"s": 27747,
"text": "Given an array of length n and a sum s"
},
{
"code": null,
"e": 27966,
"s": 27786,
"text": "Create three nested loop first loop runs from start to end (loop counter i), second loop runs from i+1 to end (loop counter j) and third loop runs from j+1 to end (loop counter k)"
},
{
"code": null,
"e": 28045,
"s": 27966,
"text": "The counter of these loops represents the index of 3 elements of the triplets."
},
{
"code": null,
"e": 28150,
"s": 28045,
"text": "Find the sum of ith, jth and kth element. If the sum is equal to given sum. Print the triplet and break."
},
{
"code": null,
"e": 28208,
"s": 28150,
"text": "If there is no triplet, then print that no triplet exist."
},
{
"code": null,
"e": 28224,
"s": 28208,
"text": "Implementation:"
},
{
"code": null,
"e": 28228,
"s": 28224,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // returns true if there is triplet with sum equal // to 'sum' present in A[]. Also, prints the triplet bool find3Numbers(int A[], int arr_size, int sum) { int l, r; // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Fix the second element as A[j] for (int j = i + 1; j < arr_size - 1; j++) { // Now look for the third number for (int k = j + 1; k < arr_size; k++) { if (A[i] + A[j] + A[k] == sum) { cout << \"Triplet is \" << A[i] << \", \" << A[j] << \", \" << A[k]; return true; } } } } // If we reach here, then no triplet was found return false; } /* Driver code */int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0; } // This is code is contributed by rathbhupendra",
"e": 29305,
"s": 28228,
"text": null
},
{
"code": null,
"e": 29325,
"s": 29305,
"text": "Triplet is 4, 10, 8"
},
{
"code": null,
"e": 29510,
"s": 29327,
"text": "Complexity Analysis: Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 29618,
"s": 29510,
"text": "Time Complexity: O(n3). There are three nested loops traversing the array, so the time complexity is O(n^3)"
},
{
"code": null,
"e": 29673,
"s": 29618,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 29749,
"s": 29673,
"text": "Method 2: This method uses sorting to increase the efficiency of the code. "
},
{
"code": null,
"e": 30120,
"s": 29749,
"text": "Approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find if there is a pair whose sum is equal to x – array[i]. Two pointers algorithm take linear time so it is better than a nested loop."
},
{
"code": null,
"e": 30556,
"s": 30120,
"text": "Algorithm : Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 30980,
"s": 30556,
"text": "Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 31002,
"s": 30980,
"text": "Sort the given array."
},
{
"code": null,
"e": 31081,
"s": 31002,
"text": "Loop over the array and fix the first element of the possible triplet, arr[i]."
},
{
"code": null,
"e": 31406,
"s": 31081,
"text": "Then fix two pointers, one at i + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 31650,
"s": 31406,
"text": "If the sum is smaller than the required sum, increment the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 31724,
"s": 31650,
"text": "If the sum is smaller than the required sum, increment the first pointer."
},
{
"code": null,
"e": 31796,
"s": 31724,
"text": "Else, If the sum is bigger, Decrease the end pointer to reduce the sum."
},
{
"code": null,
"e": 31896,
"s": 31796,
"text": "Else, if the sum of elements at two-pointer is equal to given sum then print the triplet and break."
},
{
"code": null,
"e": 31912,
"s": 31896,
"text": "Implementation:"
},
{
"code": null,
"e": 31916,
"s": 31912,
"text": "C++"
},
{
"code": "// C++ program to find a triplet#include <bits/stdc++.h>using namespace std; // returns true if there is triplet with sum equal// to 'sum' present in A[]. Also, prints the tripletbool find3Numbers(int A[], int arr_size, int sum){ int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now fix the first element one by one and find the other two elements */ for (int i = 0; i < arr_size - 2; i++) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other l = i + 1; // index of the first element in the // remaining elements r = arr_size - 1; // index of the last element while (l < r) { if (A[i] + A[l] + A[r] == sum) { printf(\"Triplet is %d, %d, %d\", A[i], A[l], A[r]); return true; } else if (A[i] + A[l] + A[r] < sum) l++; else // A[i] + A[l] + A[r] > sum r--; } } // If we reach here, then no triplet was found return false;} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0;}",
"e": 33254,
"s": 31916,
"text": null
},
{
"code": null,
"e": 33274,
"s": 33254,
"text": "Triplet is 4, 8, 10"
},
{
"code": null,
"e": 33564,
"s": 33274,
"text": "Complexity Analysis: Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal.Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 33779,
"s": 33564,
"text": "Time complexity: O(N^2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointers algorithm takes O(n) time and the first element can be fixed using another nested traversal."
},
{
"code": null,
"e": 33834,
"s": 33779,
"text": "Space Complexity: O(1). As no extra space is required."
},
{
"code": null,
"e": 33879,
"s": 33834,
"text": "Method 3: This is a Hashing-based solution. "
},
{
"code": null,
"e": 34242,
"s": 33879,
"text": "Approach: This approach uses extra space but is simpler than the two-pointers approach. Run two loops outer loop from start to end and inner loop from i+1 to end. Create a hashmap or set to store the elements in between i+1 to j-1. So if the given sum is x, check if there is a number in the set which is equal to x – arr[i] – arr[j]. If yes print the triplet. "
},
{
"code": null,
"e": 34589,
"s": 34242,
"text": "Algorithm: Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set."
},
{
"code": null,
"e": 34925,
"s": 34589,
"text": "Traverse the array from start to end. (loop counter i)Create a HashMap or set to store unique pairs.Run another loop from i+1 to end of the array. (loop counter j)If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and breakInsert the jth element in the set."
},
{
"code": null,
"e": 34980,
"s": 34925,
"text": "Traverse the array from start to end. (loop counter i)"
},
{
"code": null,
"e": 35027,
"s": 34980,
"text": "Create a HashMap or set to store unique pairs."
},
{
"code": null,
"e": 35091,
"s": 35027,
"text": "Run another loop from i+1 to end of the array. (loop counter j)"
},
{
"code": null,
"e": 35230,
"s": 35091,
"text": "If there is an element in the set which is equal to x- arr[i] – arr[j], then print the triplet (arr[i], arr[j], x-arr[i]-arr[j]) and break"
},
{
"code": null,
"e": 35265,
"s": 35230,
"text": "Insert the jth element in the set."
},
{
"code": null,
"e": 35281,
"s": 35265,
"text": "Implementation:"
},
{
"code": null,
"e": 35285,
"s": 35281,
"text": "C++"
},
{
"code": "// C++ program to find a triplet using Hashing#include <bits/stdc++.h>using namespace std; // returns true if there is triplet with sum equal// to 'sum' present in A[]. Also, prints the tripletbool find3Numbers(int A[], int arr_size, int sum){ // Fix the first element as A[i] for (int i = 0; i < arr_size - 2; i++) { // Find pair in subarray A[i+1..n-1] // with sum equal to sum - A[i] unordered_set<int> s; int curr_sum = sum - A[i]; for (int j = i + 1; j < arr_size; j++) { if (s.find(curr_sum - A[j]) != s.end()) { printf(\"Triplet is %d, %d, %d\", A[i], A[j], curr_sum - A[j]); return true; } s.insert(A[j]); } } // If we reach here, then no triplet was found return false;} /* Driver program to test above function */int main(){ int A[] = { 1, 4, 45, 6, 10, 8 }; int sum = 22; int arr_size = sizeof(A) / sizeof(A[0]); find3Numbers(A, arr_size, sum); return 0;}",
"e": 36341,
"s": 35285,
"text": null
},
{
"code": null,
"e": 36349,
"s": 36341,
"text": "Output:"
},
{
"code": null,
"e": 36369,
"s": 36349,
"text": "Triplet is 4, 8, 10"
},
{
"code": null,
"e": 36416,
"s": 36369,
"text": "Time complexity: O(N^2) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 36508,
"s": 36416,
"text": "Please refer complete article on Find a triplet that sum to a given value for more details!"
},
{
"code": null,
"e": 36517,
"s": 36508,
"text": "Accolite"
},
{
"code": null,
"e": 36524,
"s": 36517,
"text": "Amazon"
},
{
"code": null,
"e": 36532,
"s": 36524,
"text": "CarWale"
},
{
"code": null,
"e": 36547,
"s": 36532,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36555,
"s": 36547,
"text": "Samsung"
},
{
"code": null,
"e": 36577,
"s": 36555,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 36584,
"s": 36577,
"text": "Arrays"
},
{
"code": null,
"e": 36588,
"s": 36584,
"text": "C++"
},
{
"code": null,
"e": 36601,
"s": 36588,
"text": "C++ Programs"
},
{
"code": null,
"e": 36609,
"s": 36601,
"text": "Sorting"
},
{
"code": null,
"e": 36624,
"s": 36609,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 36633,
"s": 36624,
"text": "Accolite"
},
{
"code": null,
"e": 36640,
"s": 36633,
"text": "Amazon"
},
{
"code": null,
"e": 36648,
"s": 36640,
"text": "Samsung"
},
{
"code": null,
"e": 36656,
"s": 36648,
"text": "CarWale"
},
{
"code": null,
"e": 36678,
"s": 36656,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 36685,
"s": 36678,
"text": "Arrays"
},
{
"code": null,
"e": 36693,
"s": 36685,
"text": "Sorting"
},
{
"code": null,
"e": 36697,
"s": 36693,
"text": "CPP"
},
{
"code": null,
"e": 36795,
"s": 36697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36822,
"s": 36795,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36853,
"s": 36822,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 36878,
"s": 36853,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 36916,
"s": 36878,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 36937,
"s": 36916,
"text": "Next Greater Element"
},
{
"code": null,
"e": 36955,
"s": 36937,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 36974,
"s": 36955,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 37020,
"s": 36974,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 37063,
"s": 37020,
"text": "Map in C++ Standard Template Library (STL)"
}
]
|
Find sum of all elements in a matrix except the elements in row and/or column of given cell? - GeeksforGeeks | 06 Jul, 2021
Given a 2D matrix and a set of cell indexes e.g., an array of (i, j) where i indicates row and j column. For every given cell index (i, j), find sums of all matrix elements except the elements present in i’th row and/or j’th column.Example:
mat[][] = { {1, 1, 2}
{3, 4, 6}
{5, 3, 2} }
Array of Cell Indexes: {(0, 0), (1, 1), (0, 1)}
Output: 15, 10, 16
We strongly recommend you to minimize your browser and try this yourself first.A Naive Solution is to one by once consider all given cell indexes. For every cell index (i, j), find the sum of matrix elements that are not present either at i’th row or at j’th column. Below is C++ implementation of the Naive approach.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>#define R 3#define C 3using namespace std; // A structure to represent a cell indexstruct Cell{ int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1}; // A simple solution to find sums for a given array of cell indexesvoid printSums(int mat[][C], struct Cell arr[], int n){ // Iterate through all cell indexes for (int i=0; i<n; i++) { int sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (int j=0; j<R; j++) for (int k=0; k<C; k++) if (j != r && k != c) sum += mat[j][k]; cout << sum << endl; }} // Driver program to test aboveint main(){ int mat[][C] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; struct Cell arr[] = {{0, 0}, {1, 1}, {0, 1}}; int n = sizeof(arr)/sizeof(arr[0]); printSums(mat, arr, n); return 0;}
// Java implementation of the approachclass GFG{ static int R = 3; static int C = 3; // A structure to represent a cell index static class Cell { int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; // A simple solution to find sums for // a given array of cell indexes static void printSums(int mat[][], Cell arr[], int n) { // Iterate through all cell indexes for (int i = 0; i < n; i++) { int sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (int j = 0; j < R; j++) { for (int k = 0; k < C; k++) { if (j != r && k != c) { sum += mat[j][k]; } } } System.out.println(sum); } } // Driver code public static void main(String[] args) { int mat[][] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell arr[] = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.length; printSums(mat, arr, n); }} // This code is contributed by Princi Singh
# Python3 implementation of the approach # A structure to represent a cell indexclass Cell: def __init__(self, r, c): self.r = r # r is row, varies from 0 to R-1 self.c = c # c is column, varies from 0 to C-1 # A simple solution to find sums# for a given array of cell indexesdef printSums(mat, arr, n): # Iterate through all cell indexes for i in range(0, n): Sum = 0; r = arr[i].r; c = arr[i].c # Compute sum for current cell index for j in range(0, R): for k in range(0, C): if j != r and k != c: Sum += mat[j][k] print(Sum) # Driver Codeif __name__ == "__main__": mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] R = C = 3 arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] n = len(arr) printSums(mat, arr, n) # This code is contributed by Rituraj Jain
// C# implementation of the approachusing System; class GFG{ static int R = 3; static int C = 3; // A structure to represent a cell index public class Cell { public int r; // r is row, varies from 0 to R-1 public int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; // A simple solution to find sums for // a given array of cell indexes static void printSums(int [,]mat, Cell []arr, int n) { // Iterate through all cell indexes for (int i = 0; i < n; i++) { int sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (int j = 0; j < R; j++) { for (int k = 0; k < C; k++) { if (j != r && k != c) { sum += mat[j,k]; } } } Console.WriteLine(sum); } } // Driver code public static void Main(String[] args) { int [,]mat = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell []arr = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.Length; printSums(mat, arr, n); }} /* This code is contributed by PrinciRaj1992 */
<script>// javascript implementation of the approach var R = 3; var C = 3; // A structure to represent a cell index class Cell { constructor(r, c) { this.r = r; this.c = c; } } // A simple solution to find sums for // a given array of cell indexes function printSums(mat, arr , n) { // Iterate through all cell indexes for (i = 0; i < n; i++) { var sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (j = 0; j < R; j++) { for (k = 0; k < C; k++) { if (j != r && k != c) { sum += mat[j][k]; } } } document.write(sum+"<br/>"); } } // Driver code var mat = [ [ 1, 1, 2 ], [ 3, 4, 6 ], [ 5, 3, 2 ] ]; var arr = [ new Cell(0, 0), new Cell(1, 1), new Cell(0, 1) ]; var n = arr.length; printSums(mat, arr, n); // This code is contributed by aashish1995</script>
Output:
15
10
16
Time complexity of the above solution is O(n * R * C) where n is number of given cell indexes and R x C is matrix size. An Efficient Solution can compute all sums in O(R x C + n) time. The idea is to precompute total sum, row and column sums before processing the given array of indexes. Below are details 1. Calculate sum of matrix, call it sum. 2. Calculate sum of individual rows and columns. (row[] and col[]) 3. For a cell index (i, j), the desired sum will be “sum- row[i] – col[j] + arr[i][j]”Below is the implementation of above idea.
C++
Java
Python3
C#
Javascript
// An efficient C++ program to compute sum for given array of cell indexes#include<bits/stdc++.h>#define R 3#define C 3using namespace std; // A structure to represent a cell indexstruct Cell{ int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1}; void printSums(int mat[][C], struct Cell arr[], int n){ int sum = 0; int row[R] = {}; int col[C] = {}; // Compute sum of all elements, sum of every row and sum every column for (int i=0; i<R; i++) { for (int j=0; j<C; j++) { sum += mat[i][j]; col[j] += mat[i][j]; row[i] += mat[i][j]; } } // Compute the desired sum for all given cell indexes for (int i=0; i<n; i++) { int ro = arr[i].r, co = arr[i].c; cout << sum - row[ro] - col[co] + mat[ro][co] << endl; }} // Driver program to test above functionint main(){ int mat[][C] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; struct Cell arr[] = {{0, 0}, {1, 1}, {0, 1}}; int n = sizeof(arr)/sizeof(arr[0]); printSums(mat, arr, n); return 0;}
// An efficient Java program to compute// sum for given array of cell indexesclass GFG{static int R = 3;static int C = 3; // A structure to represent a cell indexstatic class Cell{ int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; static void printSums(int mat[][], Cell arr[], int n){ int sum = 0; int []row = new int[R]; int []col = new int[C]; // Compute sum of all elements, // sum of every row and sum every column for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { sum += mat[i][j]; col[j] += mat[i][j]; row[i] += mat[i][j]; } } // Compute the desired sum // for all given cell indexes for (int i = 0; i < n; i++) { int ro = arr[i].r, co = arr[i].c; System.out.println(sum - row[ro] - col[co] + mat[ro][co]); }} // Driver Codepublic static void main(String[] args){ int mat[][] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell arr[] = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.length; printSums(mat, arr, n);}} // This code is contributed by Princi Singh
# Python3 implementation of the approach # A structure to represent a cell indexclass Cell: def __init__(self, r, c): self.r = r # r is row, varies from 0 to R-1 self.c = c # c is column, varies from 0 to C-1 # A simple solution to find sums# for a given array of cell indexesdef printSums(mat, arr, n): Sum = 0 row, col = [0] * R, [0] * C # Compute sum of all elements, # sum of every row and sum every column for i in range(0, R): for j in range(0, C): Sum += mat[i][j] row[i] += mat[i][j] col[j] += mat[i][j] # Compute the desired sum # for all given cell indexes for i in range(0, n): r0, c0 = arr[i].r, arr[i].c print(Sum - row[r0] - col[c0] + mat[r0][c0]) # Driver Codeif __name__ == "__main__": mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] R = C = 3 arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] n = len(arr) printSums(mat, arr, n) # This code is contributed by Rituraj Jain
// An efficient C# program to compute// sum for given array of cell indexesusing System; class GFG{static int R = 3;static int C = 3; // A structure to represent a cell indexpublic class Cell{ public int r; // r is row, varies from 0 to R-1 public int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; static void printSums(int [,]mat, Cell []arr, int n){ int sum = 0; int []row = new int[R]; int []col = new int[C]; // Compute sum of all elements, // sum of every row and sum every column for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { sum += mat[i, j]; col[j] += mat[i, j]; row[i] += mat[i, j]; } } // Compute the desired sum // for all given cell indexes for (int i = 0; i < n; i++) { int ro = arr[i].r, co = arr[i].c; Console.WriteLine(sum - row[ro] - col[co] + mat[ro, co]); }} // Driver Codepublic static void Main(String[] args){ int [,]mat = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell []arr = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.Length; printSums(mat, arr, n);}} // This code is contributed by Rajput-Ji
<script> // An efficient Javascript program to compute// sum for given array of cell indexes var R = 3;var C = 3; // A structure to represent a cell indexclass Cell{ // r is row, varies from 0 to R-1 // c is column, varies from 0 to C-1 constructor(r, c) { this.r = r; this.c = c; } }; function printSums(mat, arr, n){ var sum = 0; var row = Array(R).fill(0); var col = Array(C).fill(0); // Compute sum of all elements, // sum of every row and sum every column for (var i = 0; i < R; i++) { for (var j = 0; j < C; j++) { sum += mat[i][j]; col[j] += mat[i][j]; row[i] += mat[i][j]; } } // Compute the desired sum // for all given cell indexes for (var i = 0; i < n; i++) { var ro = arr[i].r, co = arr[i].c; document.write(sum - row[ro] - col[co] + mat[ro][co] + "<br>"); }} // Driver Codevar mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]];var arr = [new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)];var n = arr.length;printSums(mat, arr, n); </script>
Output:
15
10
16
Time Complexity: O(R x C + n) Auxiliary Space: O(R + C)Thanks to Gaurav Ahirwar for suggesting this efficient solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
rituraj_jain
princi singh
princiraj1992
Rajput-Ji
aashish1995
rrrtnx
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Maximum size rectangle binary sub-matrix with all 1s
Min Cost Path | DP-6
Printing all solutions in N-Queen Problem
Rotate a matrix by 90 degree in clockwise direction without using any extra space
The Celebrity Problem
Search in a row wise and column wise sorted matrix
Python program to multiply two matrices
Efficiently compute sums of diagonals of a matrix | [
{
"code": null,
"e": 26783,
"s": 26755,
"text": "\n06 Jul, 2021"
},
{
"code": null,
"e": 27026,
"s": 26783,
"text": "Given a 2D matrix and a set of cell indexes e.g., an array of (i, j) where i indicates row and j column. For every given cell index (i, j), find sums of all matrix elements except the elements present in i’th row and/or j’th column.Example: "
},
{
"code": null,
"e": 27165,
"s": 27026,
"text": "mat[][] = { {1, 1, 2}\n {3, 4, 6}\n {5, 3, 2} }\nArray of Cell Indexes: {(0, 0), (1, 1), (0, 1)}\nOutput: 15, 10, 16"
},
{
"code": null,
"e": 27484,
"s": 27165,
"text": "We strongly recommend you to minimize your browser and try this yourself first.A Naive Solution is to one by once consider all given cell indexes. For every cell index (i, j), find the sum of matrix elements that are not present either at i’th row or at j’th column. Below is C++ implementation of the Naive approach. "
},
{
"code": null,
"e": 27488,
"s": 27484,
"text": "C++"
},
{
"code": null,
"e": 27493,
"s": 27488,
"text": "Java"
},
{
"code": null,
"e": 27501,
"s": 27493,
"text": "Python3"
},
{
"code": null,
"e": 27504,
"s": 27501,
"text": "C#"
},
{
"code": null,
"e": 27515,
"s": 27504,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>#define R 3#define C 3using namespace std; // A structure to represent a cell indexstruct Cell{ int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1}; // A simple solution to find sums for a given array of cell indexesvoid printSums(int mat[][C], struct Cell arr[], int n){ // Iterate through all cell indexes for (int i=0; i<n; i++) { int sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (int j=0; j<R; j++) for (int k=0; k<C; k++) if (j != r && k != c) sum += mat[j][k]; cout << sum << endl; }} // Driver program to test aboveint main(){ int mat[][C] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; struct Cell arr[] = {{0, 0}, {1, 1}, {0, 1}}; int n = sizeof(arr)/sizeof(arr[0]); printSums(mat, arr, n); return 0;}",
"e": 28414,
"s": 27515,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static int R = 3; static int C = 3; // A structure to represent a cell index static class Cell { int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; // A simple solution to find sums for // a given array of cell indexes static void printSums(int mat[][], Cell arr[], int n) { // Iterate through all cell indexes for (int i = 0; i < n; i++) { int sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (int j = 0; j < R; j++) { for (int k = 0; k < C; k++) { if (j != r && k != c) { sum += mat[j][k]; } } } System.out.println(sum); } } // Driver code public static void main(String[] args) { int mat[][] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell arr[] = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.length; printSums(mat, arr, n); }} // This code is contributed by Princi Singh",
"e": 29727,
"s": 28414,
"text": null
},
{
"code": "# Python3 implementation of the approach # A structure to represent a cell indexclass Cell: def __init__(self, r, c): self.r = r # r is row, varies from 0 to R-1 self.c = c # c is column, varies from 0 to C-1 # A simple solution to find sums# for a given array of cell indexesdef printSums(mat, arr, n): # Iterate through all cell indexes for i in range(0, n): Sum = 0; r = arr[i].r; c = arr[i].c # Compute sum for current cell index for j in range(0, R): for k in range(0, C): if j != r and k != c: Sum += mat[j][k] print(Sum) # Driver Codeif __name__ == \"__main__\": mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] R = C = 3 arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] n = len(arr) printSums(mat, arr, n) # This code is contributed by Rituraj Jain",
"e": 30591,
"s": 29727,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int R = 3; static int C = 3; // A structure to represent a cell index public class Cell { public int r; // r is row, varies from 0 to R-1 public int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; // A simple solution to find sums for // a given array of cell indexes static void printSums(int [,]mat, Cell []arr, int n) { // Iterate through all cell indexes for (int i = 0; i < n; i++) { int sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (int j = 0; j < R; j++) { for (int k = 0; k < C; k++) { if (j != r && k != c) { sum += mat[j,k]; } } } Console.WriteLine(sum); } } // Driver code public static void Main(String[] args) { int [,]mat = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell []arr = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.Length; printSums(mat, arr, n); }} /* This code is contributed by PrinciRaj1992 */",
"e": 31934,
"s": 30591,
"text": null
},
{
"code": "<script>// javascript implementation of the approach var R = 3; var C = 3; // A structure to represent a cell index class Cell { constructor(r, c) { this.r = r; this.c = c; } } // A simple solution to find sums for // a given array of cell indexes function printSums(mat, arr , n) { // Iterate through all cell indexes for (i = 0; i < n; i++) { var sum = 0, r = arr[i].r, c = arr[i].c; // Compute sum for current cell index for (j = 0; j < R; j++) { for (k = 0; k < C; k++) { if (j != r && k != c) { sum += mat[j][k]; } } } document.write(sum+\"<br/>\"); } } // Driver code var mat = [ [ 1, 1, 2 ], [ 3, 4, 6 ], [ 5, 3, 2 ] ]; var arr = [ new Cell(0, 0), new Cell(1, 1), new Cell(0, 1) ]; var n = arr.length; printSums(mat, arr, n); // This code is contributed by aashish1995</script>",
"e": 33014,
"s": 31934,
"text": null
},
{
"code": null,
"e": 33024,
"s": 33014,
"text": "Output: "
},
{
"code": null,
"e": 33033,
"s": 33024,
"text": "15\n10\n16"
},
{
"code": null,
"e": 33577,
"s": 33033,
"text": "Time complexity of the above solution is O(n * R * C) where n is number of given cell indexes and R x C is matrix size. An Efficient Solution can compute all sums in O(R x C + n) time. The idea is to precompute total sum, row and column sums before processing the given array of indexes. Below are details 1. Calculate sum of matrix, call it sum. 2. Calculate sum of individual rows and columns. (row[] and col[]) 3. For a cell index (i, j), the desired sum will be “sum- row[i] – col[j] + arr[i][j]”Below is the implementation of above idea. "
},
{
"code": null,
"e": 33581,
"s": 33577,
"text": "C++"
},
{
"code": null,
"e": 33586,
"s": 33581,
"text": "Java"
},
{
"code": null,
"e": 33594,
"s": 33586,
"text": "Python3"
},
{
"code": null,
"e": 33597,
"s": 33594,
"text": "C#"
},
{
"code": null,
"e": 33608,
"s": 33597,
"text": "Javascript"
},
{
"code": "// An efficient C++ program to compute sum for given array of cell indexes#include<bits/stdc++.h>#define R 3#define C 3using namespace std; // A structure to represent a cell indexstruct Cell{ int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1}; void printSums(int mat[][C], struct Cell arr[], int n){ int sum = 0; int row[R] = {}; int col[C] = {}; // Compute sum of all elements, sum of every row and sum every column for (int i=0; i<R; i++) { for (int j=0; j<C; j++) { sum += mat[i][j]; col[j] += mat[i][j]; row[i] += mat[i][j]; } } // Compute the desired sum for all given cell indexes for (int i=0; i<n; i++) { int ro = arr[i].r, co = arr[i].c; cout << sum - row[ro] - col[co] + mat[ro][co] << endl; }} // Driver program to test above functionint main(){ int mat[][C] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; struct Cell arr[] = {{0, 0}, {1, 1}, {0, 1}}; int n = sizeof(arr)/sizeof(arr[0]); printSums(mat, arr, n); return 0;}",
"e": 34691,
"s": 33608,
"text": null
},
{
"code": "// An efficient Java program to compute// sum for given array of cell indexesclass GFG{static int R = 3;static int C = 3; // A structure to represent a cell indexstatic class Cell{ int r; // r is row, varies from 0 to R-1 int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; static void printSums(int mat[][], Cell arr[], int n){ int sum = 0; int []row = new int[R]; int []col = new int[C]; // Compute sum of all elements, // sum of every row and sum every column for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { sum += mat[i][j]; col[j] += mat[i][j]; row[i] += mat[i][j]; } } // Compute the desired sum // for all given cell indexes for (int i = 0; i < n; i++) { int ro = arr[i].r, co = arr[i].c; System.out.println(sum - row[ro] - col[co] + mat[ro][co]); }} // Driver Codepublic static void main(String[] args){ int mat[][] = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell arr[] = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.length; printSums(mat, arr, n);}} // This code is contributed by Princi Singh",
"e": 36056,
"s": 34691,
"text": null
},
{
"code": "# Python3 implementation of the approach # A structure to represent a cell indexclass Cell: def __init__(self, r, c): self.r = r # r is row, varies from 0 to R-1 self.c = c # c is column, varies from 0 to C-1 # A simple solution to find sums# for a given array of cell indexesdef printSums(mat, arr, n): Sum = 0 row, col = [0] * R, [0] * C # Compute sum of all elements, # sum of every row and sum every column for i in range(0, R): for j in range(0, C): Sum += mat[i][j] row[i] += mat[i][j] col[j] += mat[i][j] # Compute the desired sum # for all given cell indexes for i in range(0, n): r0, c0 = arr[i].r, arr[i].c print(Sum - row[r0] - col[c0] + mat[r0][c0]) # Driver Codeif __name__ == \"__main__\": mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]] R = C = 3 arr = [Cell(0, 0), Cell(1, 1), Cell(0, 1)] n = len(arr) printSums(mat, arr, n) # This code is contributed by Rituraj Jain",
"e": 37045,
"s": 36056,
"text": null
},
{
"code": "// An efficient C# program to compute// sum for given array of cell indexesusing System; class GFG{static int R = 3;static int C = 3; // A structure to represent a cell indexpublic class Cell{ public int r; // r is row, varies from 0 to R-1 public int c; // c is column, varies from 0 to C-1 public Cell(int r, int c) { this.r = r; this.c = c; } }; static void printSums(int [,]mat, Cell []arr, int n){ int sum = 0; int []row = new int[R]; int []col = new int[C]; // Compute sum of all elements, // sum of every row and sum every column for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { sum += mat[i, j]; col[j] += mat[i, j]; row[i] += mat[i, j]; } } // Compute the desired sum // for all given cell indexes for (int i = 0; i < n; i++) { int ro = arr[i].r, co = arr[i].c; Console.WriteLine(sum - row[ro] - col[co] + mat[ro, co]); }} // Driver Codepublic static void Main(String[] args){ int [,]mat = {{1, 1, 2}, {3, 4, 6}, {5, 3, 2}}; Cell []arr = {new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)}; int n = arr.Length; printSums(mat, arr, n);}} // This code is contributed by Rajput-Ji",
"e": 38414,
"s": 37045,
"text": null
},
{
"code": "<script> // An efficient Javascript program to compute// sum for given array of cell indexes var R = 3;var C = 3; // A structure to represent a cell indexclass Cell{ // r is row, varies from 0 to R-1 // c is column, varies from 0 to C-1 constructor(r, c) { this.r = r; this.c = c; } }; function printSums(mat, arr, n){ var sum = 0; var row = Array(R).fill(0); var col = Array(C).fill(0); // Compute sum of all elements, // sum of every row and sum every column for (var i = 0; i < R; i++) { for (var j = 0; j < C; j++) { sum += mat[i][j]; col[j] += mat[i][j]; row[i] += mat[i][j]; } } // Compute the desired sum // for all given cell indexes for (var i = 0; i < n; i++) { var ro = arr[i].r, co = arr[i].c; document.write(sum - row[ro] - col[co] + mat[ro][co] + \"<br>\"); }} // Driver Codevar mat = [[1, 1, 2], [3, 4, 6], [5, 3, 2]];var arr = [new Cell(0, 0), new Cell(1, 1), new Cell(0, 1)];var n = arr.length;printSums(mat, arr, n); </script>",
"e": 39582,
"s": 38414,
"text": null
},
{
"code": null,
"e": 39592,
"s": 39582,
"text": "Output: "
},
{
"code": null,
"e": 39601,
"s": 39592,
"text": "15\n10\n16"
},
{
"code": null,
"e": 39845,
"s": 39601,
"text": "Time Complexity: O(R x C + n) Auxiliary Space: O(R + C)Thanks to Gaurav Ahirwar for suggesting this efficient solution.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 39858,
"s": 39845,
"text": "rituraj_jain"
},
{
"code": null,
"e": 39871,
"s": 39858,
"text": "princi singh"
},
{
"code": null,
"e": 39885,
"s": 39871,
"text": "princiraj1992"
},
{
"code": null,
"e": 39895,
"s": 39885,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39907,
"s": 39895,
"text": "aashish1995"
},
{
"code": null,
"e": 39914,
"s": 39907,
"text": "rrrtnx"
},
{
"code": null,
"e": 39921,
"s": 39914,
"text": "Matrix"
},
{
"code": null,
"e": 39928,
"s": 39921,
"text": "Matrix"
},
{
"code": null,
"e": 40026,
"s": 39928,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40069,
"s": 40026,
"text": "Maximum size square sub-matrix with all 1s"
},
{
"code": null,
"e": 40131,
"s": 40069,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 40184,
"s": 40131,
"text": "Maximum size rectangle binary sub-matrix with all 1s"
},
{
"code": null,
"e": 40205,
"s": 40184,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 40247,
"s": 40205,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 40329,
"s": 40247,
"text": "Rotate a matrix by 90 degree in clockwise direction without using any extra space"
},
{
"code": null,
"e": 40351,
"s": 40329,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 40402,
"s": 40351,
"text": "Search in a row wise and column wise sorted matrix"
},
{
"code": null,
"e": 40442,
"s": 40402,
"text": "Python program to multiply two matrices"
}
]
|
Angular7 - Event Binding | In this chapter, we will discuss how Event Binding works in Angular 7. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouse over, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture.
Let us consider an example to understand this better.
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1>Welcome to {{title}}.</h1>
</div>
<div> Months :
<select>
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable; then condition1 else condition2">
Condition is valid.
</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
<button (click) = "myClickFunction($event)">
Click Me
</button>
In the app.component.html file, we have defined a button and added a function to it using the click event.
Following is the syntax to define a button and add a function to it.
(click) = "myClickFunction($event)"
The function is defined in :app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May","June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
myClickFunction(event) {
//just added console.log which will display the event details in browser on click of the button.
alert("Button is clicked");
console.log(event);
}
}
Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot −
The styling for button is added in add.component.css −
button {
background-color: #2B3BCF;
border: none;
color: white;
padding: 10px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
}
Let us now add the onchange event to the dropdown.
The following line of code will help you add the change event to the dropdown −
app.component.html
<!--The content below is only a placeholder and can be replaced.-->
<div style = "text-align:center">
<h1>Welcome to {{title}}.</h1>
</div>
<div> Months :
<select (change) = "changemonths($event)">
<option *ngFor = "let i of months">{{i}}</option>
</select>
</div>
<br/>
<div>
<span *ngIf = "isavailable; then condition1 else condition2">
Condition is valid.
</span>
<ng-template #condition1>Condition is valid</ng-template>
<ng-template #condition2>Condition is invalid</ng-template>
</div>
<br/>
<button (click) = "myClickFunction($event)">
Click Me
</button>
The function is declared in the app.component.ts file −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "Feburary", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
myClickFunction(event) {
//just added console.log which will display the event
details in browser on click of the button.
alert("Button is clicked");
console.log(event);
}
changemonths(event) {
console.log("Changed month from the Dropdown");
console.log(event);
}
}
Select month from the dropdown and you see the console message “Changed month from the Dropdown” is displayed in the console along with the event.
Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below −
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
myClickFunction(event) {
//just added console.log which will display the event
details in browser on click of the button.
alert("Button is clicked"); console.log(event);
}
changemonths(event) {
alert("Changed month from the Dropdown");
}
}
When the value in dropdown is changed, a dialog box will appear and the following message will be displayed −
“Changed month from the Dropdown”.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2377,
"s": 2061,
"text": "In this chapter, we will discuss how Event Binding works in Angular 7. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouse over, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture."
},
{
"code": null,
"e": 2431,
"s": 2377,
"text": "Let us consider an example to understand this better."
},
{
"code": null,
"e": 2450,
"s": 2431,
"text": "app.component.html"
},
{
"code": null,
"e": 3010,
"s": 2450,
"text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>Welcome to {{title}}.</h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>\n<button (click) = \"myClickFunction($event)\">\n Click Me\n</button>"
},
{
"code": null,
"e": 3117,
"s": 3010,
"text": "In the app.component.html file, we have defined a button and added a function to it using the click event."
},
{
"code": null,
"e": 3186,
"s": 3117,
"text": "Following is the syntax to define a button and add a function to it."
},
{
"code": null,
"e": 3223,
"s": 3186,
"text": "(click) = \"myClickFunction($event)\"\n"
},
{
"code": null,
"e": 3268,
"s": 3223,
"text": "The function is defined in :app.component.ts"
},
{
"code": null,
"e": 3911,
"s": 3268,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7';\n \n // declared array of months.\n months = [\"January\", \"February\", \"March\", \"April\", \"May\",\"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"];\n \n isavailable = true; //variable is set to true\n myClickFunction(event) {\n //just added console.log which will display the event details in browser on click of the button.\n alert(\"Button is clicked\");\n console.log(event);\n }\n}"
},
{
"code": null,
"e": 4097,
"s": 3911,
"text": "Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot −"
},
{
"code": null,
"e": 4152,
"s": 4097,
"text": "The styling for button is added in add.component.css −"
},
{
"code": null,
"e": 4346,
"s": 4152,
"text": "button {\n background-color: #2B3BCF;\n border: none;\n color: white;\n padding: 10px 10px;\n text-align: center;\n text-decoration: none;\n display: inline-block;\n font-size: 20px;\n}\n"
},
{
"code": null,
"e": 4397,
"s": 4346,
"text": "Let us now add the onchange event to the dropdown."
},
{
"code": null,
"e": 4477,
"s": 4397,
"text": "The following line of code will help you add the change event to the dropdown −"
},
{
"code": null,
"e": 4496,
"s": 4477,
"text": "app.component.html"
},
{
"code": null,
"e": 5097,
"s": 4496,
"text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>Welcome to {{title}}.</h1>\n</div>\n\n<div> Months :\n <select (change) = \"changemonths($event)\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>\n<br/>\n\n<button (click) = \"myClickFunction($event)\">\n Click Me\n</button>"
},
{
"code": null,
"e": 5153,
"s": 5097,
"text": "The function is declared in the app.component.ts file −"
},
{
"code": null,
"e": 5914,
"s": 5153,
"text": "import { Component } from '@angular/core';\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Angular 7';\n \n // declared array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\", \"May\", \"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"];\n \n isavailable = true; //variable is set to true\n myClickFunction(event) {\n //just added console.log which will display the event \n details in browser on click of the button.\n alert(\"Button is clicked\");\n console.log(event);\n }\n changemonths(event) {\n console.log(\"Changed month from the Dropdown\");\n console.log(event);\n }\n}"
},
{
"code": null,
"e": 6061,
"s": 5914,
"text": "Select month from the dropdown and you see the console message “Changed month from the Dropdown” is displayed in the console along with the event."
},
{
"code": null,
"e": 6170,
"s": 6061,
"text": "Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below −"
},
{
"code": null,
"e": 6909,
"s": 6170,
"text": "import { Component } from '@angular/core';\n@Component({ \n selector: 'app-root', \n templateUrl: './app.component.html', \n styleUrls: ['./app.component.css'] \n}) \nexport class AppComponent { \n title = 'Angular 7'; \n \n // declared array of months. \n months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \n \"August\", \"September\", \"October\", \"November\", \"December\"]; \n \n isavailable = true; //variable is set to true \n myClickFunction(event) { \n //just added console.log which will display the event \n details in browser on click of the button. \n alert(\"Button is clicked\"); console.log(event); \n } \n changemonths(event) { \n alert(\"Changed month from the Dropdown\");\n } \n}"
},
{
"code": null,
"e": 7019,
"s": 6909,
"text": "When the value in dropdown is changed, a dialog box will appear and the following message will be displayed −"
},
{
"code": null,
"e": 7054,
"s": 7019,
"text": "“Changed month from the Dropdown”."
},
{
"code": null,
"e": 7089,
"s": 7054,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7103,
"s": 7089,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7138,
"s": 7103,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7152,
"s": 7138,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7187,
"s": 7152,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 7207,
"s": 7187,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 7242,
"s": 7207,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7259,
"s": 7242,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7292,
"s": 7259,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7304,
"s": 7292,
"text": " Senol Atac"
},
{
"code": null,
"e": 7339,
"s": 7304,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 7351,
"s": 7339,
"text": " Senol Atac"
},
{
"code": null,
"e": 7358,
"s": 7351,
"text": " Print"
},
{
"code": null,
"e": 7369,
"s": 7358,
"text": " Add Notes"
}
]
|
Indexing in MongoDB | 04 Jul, 2022
MongoDB is leading NoSQL database written in C++. It is high scalable and provides high performance and availability. It works on the concept of collections and documents. Collection in MongoDB is group of related documents that are bound together. The collection does not follow any schema which is one of the remarkable feature of MongoDB.
Indexing in MongoDB : MongoDB uses indexing in order to make the query processing more efficient. If there is no indexing, then the MongoDB must scan every document in the collection and retrieve only those documents that match the query. Indexes are special data structures that stores some information related to the documents such that it becomes easy for MongoDB to find the right data file. The indexes are order by the value of the field specified in the index.
Creating an Index : MongoDB provides a method called createIndex() that allows user to create an index.
Syntax –
db.COLLECTION_NAME.createIndex({KEY:1})
The key determines the field on the basis of which you want to create an index and 1 (or -1) determines the order in which these indexes will be arranged(ascending or descending).
Example –
db.mycol.createIndex({“age”:1})
{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}
The createIndex() method also has a number of optional parameters. These include:
background (Boolean)
unique (Boolean)
name (string)
sparse (Boolean)
expireAfterSeconds (integer)
hidden (Boolean)
storageEngine (Document)
Drop an index: In order to drop an index, MongoDB provides the dropIndex() method.
Syntax –
db.NAME_OF_COLLECTION.dropIndex({KEY:1})
The dropIndex() methods can only delete one index at a time. In order to delete (or drop) multiple indexes from the collection, MongoDB provides the dropIndexes() method that takes multiple indexes as its parameters.
Syntax –
db.NAME_OF_COLLECTION.dropIndexes({KEY1:1, KEY2, 1})
The dropIndex() methods can only delete one index at a time. In order to delete (or drop) multiple indexes from the collection, MongoDB provides the dropIndexes() method that takes multiple indexes as its parameters.
Get description of all indexes : The getIndexes() method in MongoDB gives a description of all the indexes that exists in the given collection.
Syntax –
db.NAME_OF_COLLECTION.getIndexes()
It will retrieve all the description of the indexes created within the collection.
sagar0719kumar
khushb99
DBMS
MongoDB
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Relational Model in DBMS
Introduction of Relational Algebra in DBMS
Types of Functional dependencies in DBMS
Difference between Where and Having Clause in SQL
MySQL | Regular expressions (Regexp)
MongoDB Cursor
Upsert in MongoDB
MongoDB - Index Types
Mongoose | findByIdAndUpdate() Function
Upload and Retrieve Image on MongoDB using Mongoose | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 396,
"s": 53,
"text": "MongoDB is leading NoSQL database written in C++. It is high scalable and provides high performance and availability. It works on the concept of collections and documents. Collection in MongoDB is group of related documents that are bound together. The collection does not follow any schema which is one of the remarkable feature of MongoDB. "
},
{
"code": null,
"e": 865,
"s": 396,
"text": "Indexing in MongoDB : MongoDB uses indexing in order to make the query processing more efficient. If there is no indexing, then the MongoDB must scan every document in the collection and retrieve only those documents that match the query. Indexes are special data structures that stores some information related to the documents such that it becomes easy for MongoDB to find the right data file. The indexes are order by the value of the field specified in the index. "
},
{
"code": null,
"e": 970,
"s": 865,
"text": "Creating an Index : MongoDB provides a method called createIndex() that allows user to create an index. "
},
{
"code": null,
"e": 981,
"s": 970,
"text": "Syntax – "
},
{
"code": null,
"e": 1022,
"s": 981,
"text": "db.COLLECTION_NAME.createIndex({KEY:1}) "
},
{
"code": null,
"e": 1203,
"s": 1022,
"text": "The key determines the field on the basis of which you want to create an index and 1 (or -1) determines the order in which these indexes will be arranged(ascending or descending). "
},
{
"code": null,
"e": 1215,
"s": 1203,
"text": "Example – "
},
{
"code": null,
"e": 1350,
"s": 1215,
"text": "db.mycol.createIndex({“age”:1})\n{\n“createdCollectionAutomatically” : false,\n“numIndexesBefore” : 1,\n“numIndexesAfter” : 2,\n“ok” : 1\n} "
},
{
"code": null,
"e": 1434,
"s": 1350,
"text": "The createIndex() method also has a number of optional parameters. These include: "
},
{
"code": null,
"e": 1456,
"s": 1434,
"text": "background (Boolean) "
},
{
"code": null,
"e": 1474,
"s": 1456,
"text": "unique (Boolean) "
},
{
"code": null,
"e": 1489,
"s": 1474,
"text": "name (string) "
},
{
"code": null,
"e": 1507,
"s": 1489,
"text": "sparse (Boolean) "
},
{
"code": null,
"e": 1536,
"s": 1507,
"text": "expireAfterSeconds (integer)"
},
{
"code": null,
"e": 1554,
"s": 1536,
"text": "hidden (Boolean) "
},
{
"code": null,
"e": 1580,
"s": 1554,
"text": "storageEngine (Document) "
},
{
"code": null,
"e": 1664,
"s": 1580,
"text": "Drop an index: In order to drop an index, MongoDB provides the dropIndex() method. "
},
{
"code": null,
"e": 1675,
"s": 1664,
"text": "Syntax – "
},
{
"code": null,
"e": 1717,
"s": 1675,
"text": "db.NAME_OF_COLLECTION.dropIndex({KEY:1}) "
},
{
"code": null,
"e": 1935,
"s": 1717,
"text": "The dropIndex() methods can only delete one index at a time. In order to delete (or drop) multiple indexes from the collection, MongoDB provides the dropIndexes() method that takes multiple indexes as its parameters. "
},
{
"code": null,
"e": 1946,
"s": 1935,
"text": "Syntax – "
},
{
"code": null,
"e": 2000,
"s": 1946,
"text": "db.NAME_OF_COLLECTION.dropIndexes({KEY1:1, KEY2, 1}) "
},
{
"code": null,
"e": 2218,
"s": 2000,
"text": "The dropIndex() methods can only delete one index at a time. In order to delete (or drop) multiple indexes from the collection, MongoDB provides the dropIndexes() method that takes multiple indexes as its parameters. "
},
{
"code": null,
"e": 2363,
"s": 2218,
"text": "Get description of all indexes : The getIndexes() method in MongoDB gives a description of all the indexes that exists in the given collection. "
},
{
"code": null,
"e": 2374,
"s": 2363,
"text": "Syntax – "
},
{
"code": null,
"e": 2410,
"s": 2374,
"text": "db.NAME_OF_COLLECTION.getIndexes() "
},
{
"code": null,
"e": 2494,
"s": 2410,
"text": "It will retrieve all the description of the indexes created within the collection. "
},
{
"code": null,
"e": 2509,
"s": 2494,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2518,
"s": 2509,
"text": "khushb99"
},
{
"code": null,
"e": 2523,
"s": 2518,
"text": "DBMS"
},
{
"code": null,
"e": 2531,
"s": 2523,
"text": "MongoDB"
},
{
"code": null,
"e": 2536,
"s": 2531,
"text": "DBMS"
},
{
"code": null,
"e": 2634,
"s": 2536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2659,
"s": 2634,
"text": "Relational Model in DBMS"
},
{
"code": null,
"e": 2702,
"s": 2659,
"text": "Introduction of Relational Algebra in DBMS"
},
{
"code": null,
"e": 2743,
"s": 2702,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 2793,
"s": 2743,
"text": "Difference between Where and Having Clause in SQL"
},
{
"code": null,
"e": 2830,
"s": 2793,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 2845,
"s": 2830,
"text": "MongoDB Cursor"
},
{
"code": null,
"e": 2863,
"s": 2845,
"text": "Upsert in MongoDB"
},
{
"code": null,
"e": 2885,
"s": 2863,
"text": "MongoDB - Index Types"
},
{
"code": null,
"e": 2925,
"s": 2885,
"text": "Mongoose | findByIdAndUpdate() Function"
}
]
|
Grouping Selectors in CSS | The CSS grouping selector is used to select multiple elements and style them together. This reduces the code and extra effort to declare common styles for each element. To group selectors, each selector is separated by a space.
The syntax for CSS grouping selector is as follows −
element, element {
/*declarations*/
}
The following examples illustrate CSS grouping selector −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
article, p, img {
display: block;
margin: auto;
text-align: center;
border-bottom: double orange;
}
</style>
</head>
<body>
<article>Demo Text</article>
<p>This is demo text.</p>
<br/>
<img src="https://www.tutorialspoint.com/swing/images/swing.jpg">
</body>
</html>
This gives the following output −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
div::after,p::after{
content: "Demo text";
margin: 4px;
box-shadow: inset 0 0 4px darkorange;
}
</style>
</head>
<body>
<div></div>
<p>This is example text.</p>
</body>
</html>
This gives the following output − | [
{
"code": null,
"e": 1415,
"s": 1187,
"text": "The CSS grouping selector is used to select multiple elements and style them together. This reduces the code and extra effort to declare common styles for each element. To group selectors, each selector is separated by a space."
},
{
"code": null,
"e": 1468,
"s": 1415,
"text": "The syntax for CSS grouping selector is as follows −"
},
{
"code": null,
"e": 1509,
"s": 1468,
"text": "element, element {\n /*declarations*/\n}"
},
{
"code": null,
"e": 1567,
"s": 1509,
"text": "The following examples illustrate CSS grouping selector −"
},
{
"code": null,
"e": 1578,
"s": 1567,
"text": " Live Demo"
},
{
"code": null,
"e": 1895,
"s": 1578,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\narticle, p, img {\n display: block;\n margin: auto;\n text-align: center;\n border-bottom: double orange;\n}\n</style>\n</head>\n<body>\n<article>Demo Text</article>\n<p>This is demo text.</p>\n<br/>\n<img src=\"https://www.tutorialspoint.com/swing/images/swing.jpg\">\n</body>\n</html>"
},
{
"code": null,
"e": 1929,
"s": 1895,
"text": "This gives the following output −"
},
{
"code": null,
"e": 1940,
"s": 1929,
"text": " Live Demo"
},
{
"code": null,
"e": 2164,
"s": 1940,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv::after,p::after{\n content: \"Demo text\";\n margin: 4px;\n box-shadow: inset 0 0 4px darkorange;\n}\n</style>\n</head>\n<body>\n<div></div>\n<p>This is example text.</p>\n</body>\n</html>"
},
{
"code": null,
"e": 2198,
"s": 2164,
"text": "This gives the following output −"
}
]
|
Java Program to Handle the Exception Methods | 17 Nov, 2020
An unlikely event which disrupts the normal flow of the program is known as an Exception. Java Exception Handling is an object-oriented way to handle exceptions. When an error occurs during the execution of the program, an exception object is created which contains the information about the hierarchy of the Exception and other information which is essential for debugging.
Types of Exceptions:
Checked Exceptions
Unchecked Exceptions
Handling the Exceptions:
Example 1:
We are asked to distribute chocolates to every class in the school based on the average performance of the class. We are given two arrays of equal length. One array contains the number of chocolates present in each box and the second array contains the number of students in each class. If the average performance of a class is below par, they are not eligible to get any chocolates and the number of chocolates present in the box will be equally distributed among all other boxes. Each class is given one chocolate box respectively.
So to divide the number of chocolates among the students in a class, we have to divide the number of chocolates by the number of students in the class. Suppose the average performance of a class is below par they wouldn’t get any chocolates and the number of students in that section would be zero. One can face a divide by zero exception while solving the above problem. In order to overcome it, we can use a try-catch block and ask the user to update the information given.
Below is the implementation of the above approach :
Java
// Java program to demonstrate Arithmetic Exception class GFG { public static void main(String[] args) { // Number of chocolates in each box int chocolates[] = { 106, 145, 123, 127, 125 }; // Number of students in class int students[] = { 35, 40, 0, 34, 60 }; // Number of chocolates given to each student of a // particular class int numChoc[] = new int[5]; try { for (int i = 0; i < 5; i++) { // Calculating the chocolates // to be distributed numChoc[i] = chocolates[i] / students[i]; } } // Catching Divide by Zero Exception catch (ArithmeticException error) { System.out.println("Arithmetic Exception"); System.out.println(error.getMessage() + " error."); } }}
Arithmetic Exception
/ by zero error.
Example 2:
Java has a robust Error Handling Mechanism that lets us handle multiple Exceptions in one try block using different catch blocks. Catch blocks in java are like if-else statements that will become active when an exception occurs. When an exception occurs, the program compares the exception object generated to the exception specified in the catch blocks. The program checks the first catch block then moves on to other and so-on until the generated exception is matched. If no catch block is matched, the program halts, and an exception is thrown at the console.
After an Exception is generated in the try block, the control immediately shifts to the catch block, and try block will no longer execute. Tinker with the below code by changing the sizes of the array or changing a particular element in the array2 to zero or initializing the answer array, to get a better understanding of Java Exception Handling.
Below code illustrates how various types of errors can be handled in a single try block.
Java
// Java Program to Handle Various Exceptions class GFG { public static void main(String[] args) { // Array1 Elements int[] array1 = { 2, 4, 6, 7, 8 }; // Array2 Elements int[] array2 = { 1, 2, 3, 4, 5 }; // Initialized to null value int[] ans = null; try { for (int i = 0; i < 5; i++) { ans[i] = array1[i] / array2[i]; // Generates Number Format Exception Integer.parseInt("Geeks for Geeks"); } } catch (ArithmeticException error) { System.out.println( "The catch block with Arithmetic Exception is executed"); } catch (NullPointerException error) { System.out.println( "The catch block with Null Pointer Exception is executed"); } catch (ArrayIndexOutOfBoundsException error) { System.out.println( "The catch block with Array Index Out Of Bounds Exception is executed"); } catch (NumberFormatException error) { System.out.println( "The catch block with Number Format Exception is executed"); } // Executes when an exception which // is not specified above occurs catch (Exception error) { System.out.println( "An unknown exception is found " + error.getMessage()); } // Executes after the catch block System.out.println("End of program"); }}
The catch block with Null Pointer Exception is executed
End of program
Java-Exception Handling
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 403,
"s": 28,
"text": "An unlikely event which disrupts the normal flow of the program is known as an Exception. Java Exception Handling is an object-oriented way to handle exceptions. When an error occurs during the execution of the program, an exception object is created which contains the information about the hierarchy of the Exception and other information which is essential for debugging."
},
{
"code": null,
"e": 424,
"s": 403,
"text": "Types of Exceptions:"
},
{
"code": null,
"e": 443,
"s": 424,
"text": "Checked Exceptions"
},
{
"code": null,
"e": 464,
"s": 443,
"text": "Unchecked Exceptions"
},
{
"code": null,
"e": 489,
"s": 464,
"text": "Handling the Exceptions:"
},
{
"code": null,
"e": 500,
"s": 489,
"text": "Example 1:"
},
{
"code": null,
"e": 1035,
"s": 500,
"text": "We are asked to distribute chocolates to every class in the school based on the average performance of the class. We are given two arrays of equal length. One array contains the number of chocolates present in each box and the second array contains the number of students in each class. If the average performance of a class is below par, they are not eligible to get any chocolates and the number of chocolates present in the box will be equally distributed among all other boxes. Each class is given one chocolate box respectively. "
},
{
"code": null,
"e": 1511,
"s": 1035,
"text": "So to divide the number of chocolates among the students in a class, we have to divide the number of chocolates by the number of students in the class. Suppose the average performance of a class is below par they wouldn’t get any chocolates and the number of students in that section would be zero. One can face a divide by zero exception while solving the above problem. In order to overcome it, we can use a try-catch block and ask the user to update the information given."
},
{
"code": null,
"e": 1563,
"s": 1511,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 1568,
"s": 1563,
"text": "Java"
},
{
"code": "// Java program to demonstrate Arithmetic Exception class GFG { public static void main(String[] args) { // Number of chocolates in each box int chocolates[] = { 106, 145, 123, 127, 125 }; // Number of students in class int students[] = { 35, 40, 0, 34, 60 }; // Number of chocolates given to each student of a // particular class int numChoc[] = new int[5]; try { for (int i = 0; i < 5; i++) { // Calculating the chocolates // to be distributed numChoc[i] = chocolates[i] / students[i]; } } // Catching Divide by Zero Exception catch (ArithmeticException error) { System.out.println(\"Arithmetic Exception\"); System.out.println(error.getMessage() + \" error.\"); } }}",
"e": 2451,
"s": 1568,
"text": null
},
{
"code": null,
"e": 2490,
"s": 2451,
"text": "Arithmetic Exception\n/ by zero error.\n"
},
{
"code": null,
"e": 2501,
"s": 2490,
"text": "Example 2:"
},
{
"code": null,
"e": 3065,
"s": 2501,
"text": "Java has a robust Error Handling Mechanism that lets us handle multiple Exceptions in one try block using different catch blocks. Catch blocks in java are like if-else statements that will become active when an exception occurs. When an exception occurs, the program compares the exception object generated to the exception specified in the catch blocks. The program checks the first catch block then moves on to other and so-on until the generated exception is matched. If no catch block is matched, the program halts, and an exception is thrown at the console."
},
{
"code": null,
"e": 3413,
"s": 3065,
"text": "After an Exception is generated in the try block, the control immediately shifts to the catch block, and try block will no longer execute. Tinker with the below code by changing the sizes of the array or changing a particular element in the array2 to zero or initializing the answer array, to get a better understanding of Java Exception Handling."
},
{
"code": null,
"e": 3503,
"s": 3413,
"text": "Below code illustrates how various types of errors can be handled in a single try block. "
},
{
"code": null,
"e": 3508,
"s": 3503,
"text": "Java"
},
{
"code": "// Java Program to Handle Various Exceptions class GFG { public static void main(String[] args) { // Array1 Elements int[] array1 = { 2, 4, 6, 7, 8 }; // Array2 Elements int[] array2 = { 1, 2, 3, 4, 5 }; // Initialized to null value int[] ans = null; try { for (int i = 0; i < 5; i++) { ans[i] = array1[i] / array2[i]; // Generates Number Format Exception Integer.parseInt(\"Geeks for Geeks\"); } } catch (ArithmeticException error) { System.out.println( \"The catch block with Arithmetic Exception is executed\"); } catch (NullPointerException error) { System.out.println( \"The catch block with Null Pointer Exception is executed\"); } catch (ArrayIndexOutOfBoundsException error) { System.out.println( \"The catch block with Array Index Out Of Bounds Exception is executed\"); } catch (NumberFormatException error) { System.out.println( \"The catch block with Number Format Exception is executed\"); } // Executes when an exception which // is not specified above occurs catch (Exception error) { System.out.println( \"An unknown exception is found \" + error.getMessage()); } // Executes after the catch block System.out.println(\"End of program\"); }}",
"e": 5031,
"s": 3508,
"text": null
},
{
"code": null,
"e": 5103,
"s": 5031,
"text": "The catch block with Null Pointer Exception is executed\nEnd of program\n"
},
{
"code": null,
"e": 5127,
"s": 5103,
"text": "Java-Exception Handling"
},
{
"code": null,
"e": 5151,
"s": 5127,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5156,
"s": 5151,
"text": "Java"
},
{
"code": null,
"e": 5170,
"s": 5156,
"text": "Java Programs"
},
{
"code": null,
"e": 5189,
"s": 5170,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5194,
"s": 5189,
"text": "Java"
}
]
|
Spring Boot - Cloud Configuration Client | Some applications may need configuration properties that may need a change and developers may need to take them down or restart the application to perform this. However, this might be lead to downtime in production and the need of restarting the application. Spring Cloud Configuration Server lets developers to load the new configuration properties without restarting the application and without any downtime.
First, download the Spring Boot project from https://start.spring.io/ and choose the Spring Cloud Config Client dependency. Now, add the Spring Cloud Starter Config dependency in your build configuration file.
Maven users can add the following dependency into the pom.xml file.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Gradle users can add the following dependency into the build.gradle file.
compile('org.springframework.cloud:spring-cloud-starter-config')
Now, you need to add the @RefreshScope annotation to your main Spring Boot application. The @RefreshScope annotation is used to load the configuration properties value from the Config server.
package com.example.configclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@SpringBootApplication
@RefreshScope
public class ConfigclientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigclientApplication.class, args);
}
}
Now, add the config server URL in your application.properties file and provide your application name.
Note − http://localhost:8888 config server should be run before starting the config client application.
spring.application.name = config-client
spring.cloud.config.uri = http://localhost:8888
The code for writing a simple REST Endpoint to read the welcome message from the configuration server is given below −
package com.example.configclient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RefreshScope
@RestController
public class ConfigclientApplication {
@Value("${welcome.message}")
String welcomeText;
public static void main(String[] args) {
SpringApplication.run(ConfigclientApplication.class, args);
}
@RequestMapping(value = "/")
public String welcomeText() {
return welcomeText;
}
}
You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −
For Maven, you can use the command shown below −
mvn clean install
After “BUILD SUCCESS”, you can find the JAR file under the target directory.
For Gradle, you can use the command shown below −
gradle clean build
After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory.
Now, run the JAR file by using the command shown here:
java –jar <JARFILE>
Now, the application has started on the Tomcat port 8080 as shown here −
You can see the log in console window; config-client application is fetching the configuration from the https://localhost:8888
2017-12-08 12:41:57.682 INFO 1104 --- [
main] c.c.c.ConfigServicePropertySourceLocator :
Fetching config from server at: http://localhost:8888
Now hit the URL, http://localhost:8080/ welcome message is loaded from the Configuration server.
Now, go and change the property value on the Configuration server and hit the actuator Endpoint POST URL http://localhost:8080/refresh and see the new configuration property value in the URL http://localhost:8080/ | [
{
"code": null,
"e": 3570,
"s": 3159,
"text": "Some applications may need configuration properties that may need a change and developers may need to take them down or restart the application to perform this. However, this might be lead to downtime in production and the need of restarting the application. Spring Cloud Configuration Server lets developers to load the new configuration properties without restarting the application and without any downtime."
},
{
"code": null,
"e": 3780,
"s": 3570,
"text": "First, download the Spring Boot project from https://start.spring.io/ and choose the Spring Cloud Config Client dependency. Now, add the Spring Cloud Starter Config dependency in your build configuration file."
},
{
"code": null,
"e": 3848,
"s": 3780,
"text": "Maven users can add the following dependency into the pom.xml file."
},
{
"code": null,
"e": 3979,
"s": 3848,
"text": "<dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-config</artifactId>\n</dependency>"
},
{
"code": null,
"e": 4053,
"s": 3979,
"text": "Gradle users can add the following dependency into the build.gradle file."
},
{
"code": null,
"e": 4119,
"s": 4053,
"text": "compile('org.springframework.cloud:spring-cloud-starter-config')\n"
},
{
"code": null,
"e": 4311,
"s": 4119,
"text": "Now, you need to add the @RefreshScope annotation to your main Spring Boot application. The @RefreshScope annotation is used to load the configuration properties value from the Config server."
},
{
"code": null,
"e": 4733,
"s": 4311,
"text": "package com.example.configclient;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.context.config.annotation.RefreshScope;\n\n@SpringBootApplication\n@RefreshScope\npublic class ConfigclientApplication {\n public static void main(String[] args) {\n SpringApplication.run(ConfigclientApplication.class, args);\n }\n}"
},
{
"code": null,
"e": 4835,
"s": 4733,
"text": "Now, add the config server URL in your application.properties file and provide your application name."
},
{
"code": null,
"e": 4939,
"s": 4835,
"text": "Note − http://localhost:8888 config server should be run before starting the config client application."
},
{
"code": null,
"e": 5028,
"s": 4939,
"text": "spring.application.name = config-client\nspring.cloud.config.uri = http://localhost:8888\n"
},
{
"code": null,
"e": 5147,
"s": 5028,
"text": "The code for writing a simple REST Endpoint to read the welcome message from the configuration server is given below −"
},
{
"code": null,
"e": 5925,
"s": 5147,
"text": "package com.example.configclient;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.context.config.annotation.RefreshScope;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@SpringBootApplication\n@RefreshScope\n@RestController\npublic class ConfigclientApplication {\n @Value(\"${welcome.message}\")\n String welcomeText;\n \n public static void main(String[] args) {\n SpringApplication.run(ConfigclientApplication.class, args);\n }\n @RequestMapping(value = \"/\")\n public String welcomeText() {\n return welcomeText;\n }\n}"
},
{
"code": null,
"e": 6050,
"s": 5925,
"text": "You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −"
},
{
"code": null,
"e": 6099,
"s": 6050,
"text": "For Maven, you can use the command shown below −"
},
{
"code": null,
"e": 6118,
"s": 6099,
"text": "mvn clean install\n"
},
{
"code": null,
"e": 6195,
"s": 6118,
"text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory."
},
{
"code": null,
"e": 6245,
"s": 6195,
"text": "For Gradle, you can use the command shown below −"
},
{
"code": null,
"e": 6265,
"s": 6245,
"text": "gradle clean build\n"
},
{
"code": null,
"e": 6349,
"s": 6265,
"text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory."
},
{
"code": null,
"e": 6407,
"s": 6349,
"text": "Now, run the JAR file by using the command shown here: "
},
{
"code": null,
"e": 6429,
"s": 6407,
"text": "java –jar <JARFILE> \n"
},
{
"code": null,
"e": 6502,
"s": 6429,
"text": "Now, the application has started on the Tomcat port 8080 as shown here −"
},
{
"code": null,
"e": 6629,
"s": 6502,
"text": "You can see the log in console window; config-client application is fetching the configuration from the https://localhost:8888"
},
{
"code": null,
"e": 6792,
"s": 6629,
"text": "2017-12-08 12:41:57.682 INFO 1104 --- [ \n main] c.c.c.ConfigServicePropertySourceLocator : \n Fetching config from server at: http://localhost:8888\n"
},
{
"code": null,
"e": 6889,
"s": 6792,
"text": "Now hit the URL, http://localhost:8080/ welcome message is loaded from the Configuration server."
}
]
|
numpy.random.choice() in Python | 15 Jul, 2020
With the help of choice() method, we can get the random samples of one dimensional array and return the random samples of numpy array.
Syntax : numpy.random.choice(a, size=None, replace=True, p=None)
Parameters:
1) a – 1-D array of numpy having random samples.
2) size – Output shape of random samples of numpy array.
3) replace – Whether the sample is with or without replacement.
4) p – The probability attach with every samples in a.
Output : Return the numpy array of random samples.
Example #1 :
In this example we can see that by using choice() method, we are able to get the random samples of numpy array, it can generate uniform or non-uniform samples by using this method.
Python3
# import choiceimport numpy as npimport matplotlib.pyplot as plt # Using choice() methodgfg = np.random.choice(13, 5000) count, bins, ignored = plt.hist(gfg, 25, density = True)plt.show()
Output :
Example #2 :
Python3
# import choiceimport numpy as npimport matplotlib.pyplot as plt # Using choice() methodgfg = np.random.choice(5, 1000, p =[0.2, 0.1, 0.3, 0.4, 0]) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Python numpy-Random
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jul, 2020"
},
{
"code": null,
"e": 189,
"s": 54,
"text": "With the help of choice() method, we can get the random samples of one dimensional array and return the random samples of numpy array."
},
{
"code": null,
"e": 254,
"s": 189,
"text": "Syntax : numpy.random.choice(a, size=None, replace=True, p=None)"
},
{
"code": null,
"e": 266,
"s": 254,
"text": "Parameters:"
},
{
"code": null,
"e": 315,
"s": 266,
"text": "1) a – 1-D array of numpy having random samples."
},
{
"code": null,
"e": 372,
"s": 315,
"text": "2) size – Output shape of random samples of numpy array."
},
{
"code": null,
"e": 436,
"s": 372,
"text": "3) replace – Whether the sample is with or without replacement."
},
{
"code": null,
"e": 492,
"s": 436,
"text": "4) p – The probability attach with every samples in a. "
},
{
"code": null,
"e": 543,
"s": 492,
"text": "Output : Return the numpy array of random samples."
},
{
"code": null,
"e": 556,
"s": 543,
"text": "Example #1 :"
},
{
"code": null,
"e": 737,
"s": 556,
"text": "In this example we can see that by using choice() method, we are able to get the random samples of numpy array, it can generate uniform or non-uniform samples by using this method."
},
{
"code": null,
"e": 745,
"s": 737,
"text": "Python3"
},
{
"code": "# import choiceimport numpy as npimport matplotlib.pyplot as plt # Using choice() methodgfg = np.random.choice(13, 5000) count, bins, ignored = plt.hist(gfg, 25, density = True)plt.show()",
"e": 935,
"s": 745,
"text": null
},
{
"code": null,
"e": 944,
"s": 935,
"text": "Output :"
},
{
"code": null,
"e": 957,
"s": 944,
"text": "Example #2 :"
},
{
"code": null,
"e": 965,
"s": 957,
"text": "Python3"
},
{
"code": "# import choiceimport numpy as npimport matplotlib.pyplot as plt # Using choice() methodgfg = np.random.choice(5, 1000, p =[0.2, 0.1, 0.3, 0.4, 0]) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()",
"e": 1182,
"s": 965,
"text": null
},
{
"code": null,
"e": 1191,
"s": 1182,
"text": "Output :"
},
{
"code": null,
"e": 1211,
"s": 1191,
"text": "Python numpy-Random"
},
{
"code": null,
"e": 1224,
"s": 1211,
"text": "Python-numpy"
},
{
"code": null,
"e": 1231,
"s": 1224,
"text": "Python"
},
{
"code": null,
"e": 1329,
"s": 1231,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1347,
"s": 1329,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1389,
"s": 1347,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1411,
"s": 1389,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1446,
"s": 1411,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1472,
"s": 1446,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1504,
"s": 1472,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1533,
"s": 1504,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1563,
"s": 1533,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1590,
"s": 1563,
"text": "Python Classes and Objects"
}
]
|
BeautifulSoup – Find tags by CSS class with CSS Selectors | 16 Jan, 2022
Prerequisites: Beautifulsoup
Beautifulsoup is a Python library used for web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. This powerful python tool can also be used to modify HTML webpages. This article depicts how beautifulsoup can be employed to find tag by CSS class with CSS Selectors. For this, find_all() method of the module is used.
Syntax:
find_all(class_=”class_name”)
Returns tags having a particular CSS class.
Approach:
Import module
Scrap data from a webpage.
Parse the string scraped to HTML.
Use find_all() function to get a list of tag with the given class name.
Print tags.
Example 1: Finding all tags of a particular CSS class from an HTML file.
Python3
# importing modulefrom bs4 import BeautifulSoup markup = """ <!DOCTYPE><html> <head><title>Example</title></head> <body> <div class="first"> Div with Class first </div> <p class="first"> Para with Class first </p> <div class="second"> Div with Class second </div> <span class="first"> Span with Class first </span> </body></html>""" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # printing tags with given class namefor i in soup.find_all(class_="first"): print(i.name)
Output:
div
p
span
Example 2: Finding all tags of a particular CSS class from a URL.
Python3
# importing modulefrom bs4 import BeautifulSoupimport requests URL = "https://www.geeksforgeeks.org/"html = requests.get(URL) # parsering string to HTMLsoup = BeautifulSoup(html.content, "html5lib") # printing tags with given class namefor i in soup.find_all(class_="article--container_content"): print(i.name)
Output:
div
saurabh1990aror
Picked
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jan, 2022"
},
{
"code": null,
"e": 81,
"s": 52,
"text": "Prerequisites: Beautifulsoup"
},
{
"code": null,
"e": 636,
"s": 81,
"text": "Beautifulsoup is a Python library used for web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. This powerful python tool can also be used to modify HTML webpages. This article depicts how beautifulsoup can be employed to find tag by CSS class with CSS Selectors. For this, find_all() method of the module is used."
},
{
"code": null,
"e": 644,
"s": 636,
"text": "Syntax:"
},
{
"code": null,
"e": 674,
"s": 644,
"text": "find_all(class_=”class_name”)"
},
{
"code": null,
"e": 718,
"s": 674,
"text": "Returns tags having a particular CSS class."
},
{
"code": null,
"e": 728,
"s": 718,
"text": "Approach:"
},
{
"code": null,
"e": 742,
"s": 728,
"text": "Import module"
},
{
"code": null,
"e": 769,
"s": 742,
"text": "Scrap data from a webpage."
},
{
"code": null,
"e": 803,
"s": 769,
"text": "Parse the string scraped to HTML."
},
{
"code": null,
"e": 875,
"s": 803,
"text": "Use find_all() function to get a list of tag with the given class name."
},
{
"code": null,
"e": 887,
"s": 875,
"text": "Print tags."
},
{
"code": null,
"e": 961,
"s": 887,
"text": "Example 1: Finding all tags of a particular CSS class from an HTML file."
},
{
"code": null,
"e": 969,
"s": 961,
"text": "Python3"
},
{
"code": "# importing modulefrom bs4 import BeautifulSoup markup = \"\"\" <!DOCTYPE><html> <head><title>Example</title></head> <body> <div class=\"first\"> Div with Class first </div> <p class=\"first\"> Para with Class first </p> <div class=\"second\"> Div with Class second </div> <span class=\"first\"> Span with Class first </span> </body></html>\"\"\" # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser') # printing tags with given class namefor i in soup.find_all(class_=\"first\"): print(i.name)",
"e": 1531,
"s": 969,
"text": null
},
{
"code": null,
"e": 1539,
"s": 1531,
"text": "Output:"
},
{
"code": null,
"e": 1550,
"s": 1539,
"text": "div\np\nspan"
},
{
"code": null,
"e": 1616,
"s": 1550,
"text": "Example 2: Finding all tags of a particular CSS class from a URL."
},
{
"code": null,
"e": 1624,
"s": 1616,
"text": "Python3"
},
{
"code": "# importing modulefrom bs4 import BeautifulSoupimport requests URL = \"https://www.geeksforgeeks.org/\"html = requests.get(URL) # parsering string to HTMLsoup = BeautifulSoup(html.content, \"html5lib\") # printing tags with given class namefor i in soup.find_all(class_=\"article--container_content\"): print(i.name)",
"e": 1938,
"s": 1624,
"text": null
},
{
"code": null,
"e": 1946,
"s": 1938,
"text": "Output:"
},
{
"code": null,
"e": 1950,
"s": 1946,
"text": "div"
},
{
"code": null,
"e": 1966,
"s": 1950,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 1973,
"s": 1966,
"text": "Picked"
},
{
"code": null,
"e": 1994,
"s": 1973,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 2015,
"s": 1994,
"text": "Python bs4-Exercises"
},
{
"code": null,
"e": 2022,
"s": 2015,
"text": "Python"
},
{
"code": null,
"e": 2120,
"s": 2022,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2152,
"s": 2120,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2179,
"s": 2152,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2200,
"s": 2179,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2223,
"s": 2200,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2279,
"s": 2223,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2310,
"s": 2279,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2352,
"s": 2310,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2394,
"s": 2352,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2433,
"s": 2394,
"text": "Python | Get unique values from a list"
}
]
|
Sort even-placed elements in increasing and odd-placed in decreasing order | 06 Jul, 2022
We are given an array of n distinct numbers. The task is to sort all even-placed numbers in increasing and odd-placed numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers.
Note that the first element is considered as even placed because of its index 0.
Examples:
Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}
Output: arr[] = {0, 2, 4, 6, 7, 5, 3, 1}
Even-place elements : 0, 2, 4, 6
Odd-place elements : 1, 3, 5, 7
Even-place elements in increasing order :
0, 2, 4, 6
Odd-Place elements in decreasing order :
7, 5, 3, 1
Input: arr[] = {3, 1, 2, 4, 5, 9, 13, 14, 12}
Output: {2, 3, 5, 12, 13, 14, 9, 4, 1}
Even-place elements : 3, 2, 5, 13, 12
Odd-place elements : 1, 4, 9, 14
Even-place elements in increasing order :
2, 3, 5, 12, 13
Odd-Place elements in decreasing order :
14, 9, 4, 1
The idea is simple. We create two auxiliary arrays evenArr[] and oddArr[] respectively. We traverse input array and put all even-placed elements in evenArr[] and odd placed elements in oddArr[]. Then we sort evenArr[] in ascending and oddArr[] in descending order. Finally, copy evenArr[] and oddArr[] to get the required result.
Implementation:
C++
Java
Python3
C#
Javascript
// Program to separately sort even-placed and odd// placed numbers and place them together in sorted// array.#include <bits/stdc++.h>using namespace std; void bitonicGenerator(int arr[], int n){ // create evenArr[] and oddArr[] vector<int> evenArr; vector<int> oddArr; // Put elements in oddArr[] and evenArr[] as // per their position for (int i = 0; i < n; i++) { if (!(i % 2)) evenArr.push_back(arr[i]); else oddArr.push_back(arr[i]); } // sort evenArr[] in ascending order // sort oddArr[] in descending order sort(evenArr.begin(), evenArr.end()); sort(oddArr.begin(), oddArr.end(), greater<int>()); int i = 0; for (int j = 0; j < evenArr.size(); j++) arr[i++] = evenArr[j]; for (int j = 0; j < oddArr.size(); j++) arr[i++] = oddArr[j];} // Driver Programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); bitonicGenerator(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}
// Java Program to separately sort// even-placed and odd placed numbers// and place them together in sorted// array.import java.util.*; class GFG { static void bitonicGenerator(int arr[], int n) { // create evenArr[] and oddArr[] Vector<Integer> evenArr = new Vector<Integer>(); Vector<Integer> oddArr = new Vector<Integer>(); // Put elements in oddArr[] and evenArr[] as // per their position for (int i = 0; i < n; i++) { if (i % 2 != 1) { evenArr.add(arr[i]); } else { oddArr.add(arr[i]); } } // sort evenArr[] in ascending order // sort oddArr[] in descending order Collections.sort(evenArr); Collections.sort(oddArr, Collections.reverseOrder()); int i = 0; for (int j = 0; j < evenArr.size(); j++) { arr[i++] = evenArr.get(j); } for (int j = 0; j < oddArr.size(); j++) { arr[i++] = oddArr.get(j); } } // Driver code public static void main(String[] args) { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }} /* This code contributed by PrinciRaj1992 */
# Python3 program to separately sort# even-placed and odd placed numbers# and place them together in sorted array.def bitonicGenerator(arr, n): # create evenArr[] and oddArr[] evenArr = [] oddArr = [] # Put elements in oddArr[] and evenArr[] # as per their position for i in range(n): if ((i % 2) == 0): evenArr.append(arr[i]) else: oddArr.append(arr[i]) # sort evenArr[] in ascending order # sort oddArr[] in descending order evenArr = sorted(evenArr) oddArr = sorted(oddArr) oddArr = oddArr[::-1] i = 0 for j in range(len(evenArr)): arr[i] = evenArr[j] i += 1 for j in range(len(oddArr)): arr[i] = oddArr[j] i += 1 # Driver Codearr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]n = len(arr)bitonicGenerator(arr, n)for i in arr: print(i, end = " ") # This code is contributed by Mohit Kumar
// C# Program to separately sort// even-placed and odd placed numbers// and place them together in sorted// array.using System;using System.Collections.Generic; class GFG{ static void bitonicGenerator(int []arr, int n) { // create evenArr[] and oddArr[] List<int> evenArr = new List<int>(); List<int> oddArr = new List<int>(); int i = 0; // Put elements in oddArr[] and evenArr[] as // per their position for (i = 0; i < n; i++) { if (i % 2 != 1) { evenArr.Add(arr[i]); } else { oddArr.Add(arr[i]); } } // sort evenArr[] in ascending order // sort oddArr[] in descending order evenArr.Sort(); oddArr.Sort(); oddArr.Reverse(); i = 0; for (int j = 0; j < evenArr.Count; j++) { arr[i++] = evenArr[j]; } for (int j = 0; j < oddArr.Count; j++) { arr[i++] = oddArr[j]; } } // Driver code public static void Main(String[] args) { int []arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.Length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } }} // This code contributed by Rajput-Ji
<script>// Javascript Program to separately sort// even-placed and odd placed numbers// and place them together in sorted// array. function bitonicGenerator(arr,n) { // create evenArr[] and oddArr[] let evenArr = []; let oddArr = []; // Put elements in oddArr[] and evenArr[] as // per their position for (let i = 0; i < n; i++) { if (i % 2 != 1) { evenArr.push(arr[i]); } else { oddArr.push(arr[i]); } } // sort evenArr[] in ascending order // sort oddArr[] in descending order evenArr.sort(function(a,b){return a-b;}); oddArr.sort(function(a,b){return b-a;}); let i = 0; for (let j = 0; j < evenArr.length; j++) { arr[i++] = evenArr[j]; } for (let j = 0; j < oddArr.length; j++) { arr[i++] = oddArr[j]; } } // Driver code let arr=[1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ]; let n = arr.length; bitonicGenerator(arr, n); for (let i = 0; i < n; i++) { document.write(arr[i] + " "); } // This code is contributed by unknown2108</script>
1 2 3 6 8 9 7 5 4 0
Time Complexity : O(n Log n) Space Complexity : O(n)
The above problem can also be solved without the use of Auxiliary space. The idea is to swap the first half odd index positions with the second half even index positions and then sort the first half array in increasing order and the second half array in decreasing order. Thanks to SWARUPANANDA DHUA for suggesting this.
Implementation:
C++
Java
Python3
C#
Javascript
// Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexity #include <bits/stdc++.h>using namespace std; void bitonicGenerator(int arr[], int n){ // first odd index int i = 1; // last index int j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { swap(arr[i], arr[j]); i += 2; j -= 2; } // Sort first half in increasing sort(arr, arr + (n + 1) / 2); // Sort second half in decreasing sort(arr + (n + 1) / 2, arr + n, greater<int>());} // Driver Programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); bitonicGenerator(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}// This code is contributed by SWARUPANANDA DHUA
// Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexityimport java.util.Arrays;class GFG { static void bitonicGenerator(int arr[], int n) { // first odd index int i = 1; // last index int j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { arr = swap(arr, i, j); i += 2; j -= 2; } // Sort first half in increasing Arrays.sort(arr, 0, (n + 1) / 2); // Sort second half in decreasing Arrays.sort(arr, (n + 1) / 2, n); int low = (n + 1) / 2, high = n - 1; // Reverse the second half while (low < high) { Integer temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; low++; high--; } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver Program public static void main(String[] args) { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }}// This code has been contributed by 29AjayKumar
# Python3 Program to sort even-placed elements in increasing and# odd-placed in decreasing order with constant space complexitydef bitonicGenerator(arr, n): # first odd index i = 1 # last index j = n - 1 # if last index is odd if (j % 2 != 0): # decrement j to even index j = j - 1 # swapping till half of array while (i < j) : arr[j], arr[i] = arr[i], arr[j] i = i + 2 j = j - 2 arr_f = [] arr_s = [] for i in range(int((n + 1) / 2)) : arr_f.append(arr[i]) i = int((n + 1) / 2) while( i < n ) : arr_s.append(arr[i]) i = i + 1 # Sort first half in increasing arr_f.sort() # Sort second half in decreasing arr_s.sort(reverse = True) for i in arr_s: arr_f.append(i) return arr_f # Driver Programarr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0]n = len(arr)arr = bitonicGenerator(arr, n)print(arr) # This code is contributed by Arnab Kundu
// Program to sort even-placed elements in// increasing and odd-placed in decreasing order// with constant space complexityusing System; class GFG{ static void bitonicGenerator(int []arr, int n) { // first odd index int i = 1; // last index int j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { arr = swap(arr, i, j); i += 2; j -= 2; } // Sort first half in increasing Array.Sort(arr, 0, (n + 1) / 2); // Sort second half in decreasing Array.Sort(arr, (n + 1) / 2, n - ((n + 1) / 2)); int low = (n + 1) / 2, high = n - 1; // Reverse the second half while (low < high) { int temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; low++; high--; } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver Code public static void Main(String[] args) { int []arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.Length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by PrinciRaj1992
<script>// Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexityfunction bitonicGenerator(arr, n){ // first odd index let i = 1; // last index let j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { arr = swap(arr, i, j); i += 2; j -= 2; } // Sort first half in increasing // Sort second half in decreasing let temp1 = arr.slice(0,Math.floor((n+1)/2)).sort(function(a,b){return a-b;}); let temp2 = arr.slice(Math.floor((n+1)/2),n).sort(function(a,b){return b-a;}); arr = temp1.concat(temp2); return arr;} function swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Programlet arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ];let n = arr.length;arr = bitonicGenerator(arr, n);document.write(arr.join(" ")); // This code is contributed by rag2127</script>
1 2 3 6 8 9 7 5 4 0
Time Complexity : O(n Log n) Space Complexity : O(1)
Another approach:Another efficient approach to solve the problem in O(1) Auxiliary space is by Using negative multiplication.
The steps involved are as follows:
Multiply all the elements at even placed index by -1.Sort the whole array. In this way, we can get all even placed index in the starting as they are negative numbers now.Now revert the sign of these elements.After this reverse the first half of the array which contains an even placed number to make it in increasing order.And then reverse the rest half of the array to make odd placed numbers in decreasing order.
Multiply all the elements at even placed index by -1.
Sort the whole array. In this way, we can get all even placed index in the starting as they are negative numbers now.
Now revert the sign of these elements.
After this reverse the first half of the array which contains an even placed number to make it in increasing order.
And then reverse the rest half of the array to make odd placed numbers in decreasing order.
Note: This method is only applicable if all the elements in the array are non-negative.
An illustrative example of the above approach:
Let given array: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}Array after multiplying by -1 to even placed elements: arr[] = {0, 1, -2, 3, -4, 5, -6, 7}Array after sorting: arr[] = {-6, -4, -2, 0, 1, 3, 5, 7}Array after reverting negative values: arr[] = {6, 4, 2, 0, 1, 3, 5, 7}After reversing the first half of array: arr[] = {0, 2, 4, 6, 1, 3, 5, 7}After reversing the second half of array: arr[] = {0, 2, 4, 6, 7, 5, 3, 1}
Below is the code for the above approach:
C++
// C++ Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexity#include <bits/stdc++.h>using namespace std; void bitonicGenerator(int arr[], int n){ // Making all even placed index // element negative for (int i = 0; i < n; i++) { if (i % 2==0) arr[i]=-1*arr[i]; } // Sorting the whole array sort(arr,arr+n); // Finding the middle value of // the array int mid=(n-1)/2; // Reverting the changed sign for (int i = 0; i <= mid; i++) { arr[i]=-1*arr[i]; } // Reverse first half of array reverse(arr,arr+mid+1); // Reverse second half of array reverse(arr+mid+1,arr+n);} // Driver Programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); bitonicGenerator(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // This code is contributed by Pushpesh Raj.
1 2 3 6 8 9 7 5 4 0
Time Complexity: O(n*log(n)) Space Complexity: O(1)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
princiraj1992
29AjayKumar
Rajput-Ji
mohit kumar 29
andrew1234
unknown2108
rag2127
pushpeshrajdx01
hardikkoriintern
STL
Zoho
Arrays
Sorting
Zoho
Arrays
Sorting
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Python | Using 2D arrays/lists the right way
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 311,
"s": 52,
"text": "We are given an array of n distinct numbers. The task is to sort all even-placed numbers in increasing and odd-placed numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers."
},
{
"code": null,
"e": 393,
"s": 311,
"text": "Note that the first element is considered as even placed because of its index 0. "
},
{
"code": null,
"e": 405,
"s": 393,
"text": "Examples: "
},
{
"code": null,
"e": 930,
"s": 405,
"text": "Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}\nOutput: arr[] = {0, 2, 4, 6, 7, 5, 3, 1}\nEven-place elements : 0, 2, 4, 6\nOdd-place elements : 1, 3, 5, 7\nEven-place elements in increasing order : \n0, 2, 4, 6\nOdd-Place elements in decreasing order : \n7, 5, 3, 1\n\nInput: arr[] = {3, 1, 2, 4, 5, 9, 13, 14, 12}\nOutput: {2, 3, 5, 12, 13, 14, 9, 4, 1}\nEven-place elements : 3, 2, 5, 13, 12\nOdd-place elements : 1, 4, 9, 14\nEven-place elements in increasing order : \n2, 3, 5, 12, 13\nOdd-Place elements in decreasing order : \n14, 9, 4, 1 "
},
{
"code": null,
"e": 1260,
"s": 930,
"text": "The idea is simple. We create two auxiliary arrays evenArr[] and oddArr[] respectively. We traverse input array and put all even-placed elements in evenArr[] and odd placed elements in oddArr[]. Then we sort evenArr[] in ascending and oddArr[] in descending order. Finally, copy evenArr[] and oddArr[] to get the required result."
},
{
"code": null,
"e": 1276,
"s": 1260,
"text": "Implementation:"
},
{
"code": null,
"e": 1280,
"s": 1276,
"text": "C++"
},
{
"code": null,
"e": 1285,
"s": 1280,
"text": "Java"
},
{
"code": null,
"e": 1293,
"s": 1285,
"text": "Python3"
},
{
"code": null,
"e": 1296,
"s": 1293,
"text": "C#"
},
{
"code": null,
"e": 1307,
"s": 1296,
"text": "Javascript"
},
{
"code": "// Program to separately sort even-placed and odd// placed numbers and place them together in sorted// array.#include <bits/stdc++.h>using namespace std; void bitonicGenerator(int arr[], int n){ // create evenArr[] and oddArr[] vector<int> evenArr; vector<int> oddArr; // Put elements in oddArr[] and evenArr[] as // per their position for (int i = 0; i < n; i++) { if (!(i % 2)) evenArr.push_back(arr[i]); else oddArr.push_back(arr[i]); } // sort evenArr[] in ascending order // sort oddArr[] in descending order sort(evenArr.begin(), evenArr.end()); sort(oddArr.begin(), oddArr.end(), greater<int>()); int i = 0; for (int j = 0; j < evenArr.size(); j++) arr[i++] = evenArr[j]; for (int j = 0; j < oddArr.size(); j++) arr[i++] = oddArr[j];} // Driver Programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); bitonicGenerator(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 2367,
"s": 1307,
"text": null
},
{
"code": "// Java Program to separately sort// even-placed and odd placed numbers// and place them together in sorted// array.import java.util.*; class GFG { static void bitonicGenerator(int arr[], int n) { // create evenArr[] and oddArr[] Vector<Integer> evenArr = new Vector<Integer>(); Vector<Integer> oddArr = new Vector<Integer>(); // Put elements in oddArr[] and evenArr[] as // per their position for (int i = 0; i < n; i++) { if (i % 2 != 1) { evenArr.add(arr[i]); } else { oddArr.add(arr[i]); } } // sort evenArr[] in ascending order // sort oddArr[] in descending order Collections.sort(evenArr); Collections.sort(oddArr, Collections.reverseOrder()); int i = 0; for (int j = 0; j < evenArr.size(); j++) { arr[i++] = evenArr.get(j); } for (int j = 0; j < oddArr.size(); j++) { arr[i++] = oddArr.get(j); } } // Driver code public static void main(String[] args) { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }} /* This code contributed by PrinciRaj1992 */",
"e": 3713,
"s": 2367,
"text": null
},
{
"code": "# Python3 program to separately sort# even-placed and odd placed numbers# and place them together in sorted array.def bitonicGenerator(arr, n): # create evenArr[] and oddArr[] evenArr = [] oddArr = [] # Put elements in oddArr[] and evenArr[] # as per their position for i in range(n): if ((i % 2) == 0): evenArr.append(arr[i]) else: oddArr.append(arr[i]) # sort evenArr[] in ascending order # sort oddArr[] in descending order evenArr = sorted(evenArr) oddArr = sorted(oddArr) oddArr = oddArr[::-1] i = 0 for j in range(len(evenArr)): arr[i] = evenArr[j] i += 1 for j in range(len(oddArr)): arr[i] = oddArr[j] i += 1 # Driver Codearr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]n = len(arr)bitonicGenerator(arr, n)for i in arr: print(i, end = \" \") # This code is contributed by Mohit Kumar",
"e": 4608,
"s": 3713,
"text": null
},
{
"code": "// C# Program to separately sort// even-placed and odd placed numbers// and place them together in sorted// array.using System;using System.Collections.Generic; class GFG{ static void bitonicGenerator(int []arr, int n) { // create evenArr[] and oddArr[] List<int> evenArr = new List<int>(); List<int> oddArr = new List<int>(); int i = 0; // Put elements in oddArr[] and evenArr[] as // per their position for (i = 0; i < n; i++) { if (i % 2 != 1) { evenArr.Add(arr[i]); } else { oddArr.Add(arr[i]); } } // sort evenArr[] in ascending order // sort oddArr[] in descending order evenArr.Sort(); oddArr.Sort(); oddArr.Reverse(); i = 0; for (int j = 0; j < evenArr.Count; j++) { arr[i++] = evenArr[j]; } for (int j = 0; j < oddArr.Count; j++) { arr[i++] = oddArr[j]; } } // Driver code public static void Main(String[] args) { int []arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.Length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } }} // This code contributed by Rajput-Ji",
"e": 5977,
"s": 4608,
"text": null
},
{
"code": "<script>// Javascript Program to separately sort// even-placed and odd placed numbers// and place them together in sorted// array. function bitonicGenerator(arr,n) { // create evenArr[] and oddArr[] let evenArr = []; let oddArr = []; // Put elements in oddArr[] and evenArr[] as // per their position for (let i = 0; i < n; i++) { if (i % 2 != 1) { evenArr.push(arr[i]); } else { oddArr.push(arr[i]); } } // sort evenArr[] in ascending order // sort oddArr[] in descending order evenArr.sort(function(a,b){return a-b;}); oddArr.sort(function(a,b){return b-a;}); let i = 0; for (let j = 0; j < evenArr.length; j++) { arr[i++] = evenArr[j]; } for (let j = 0; j < oddArr.length; j++) { arr[i++] = oddArr[j]; } } // Driver code let arr=[1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ]; let n = arr.length; bitonicGenerator(arr, n); for (let i = 0; i < n; i++) { document.write(arr[i] + \" \"); } // This code is contributed by unknown2108</script>",
"e": 7173,
"s": 5977,
"text": null
},
{
"code": null,
"e": 7194,
"s": 7173,
"text": "1 2 3 6 8 9 7 5 4 0 "
},
{
"code": null,
"e": 7247,
"s": 7194,
"text": "Time Complexity : O(n Log n) Space Complexity : O(n)"
},
{
"code": null,
"e": 7568,
"s": 7247,
"text": "The above problem can also be solved without the use of Auxiliary space. The idea is to swap the first half odd index positions with the second half even index positions and then sort the first half array in increasing order and the second half array in decreasing order. Thanks to SWARUPANANDA DHUA for suggesting this."
},
{
"code": null,
"e": 7584,
"s": 7568,
"text": "Implementation:"
},
{
"code": null,
"e": 7588,
"s": 7584,
"text": "C++"
},
{
"code": null,
"e": 7593,
"s": 7588,
"text": "Java"
},
{
"code": null,
"e": 7601,
"s": 7593,
"text": "Python3"
},
{
"code": null,
"e": 7604,
"s": 7601,
"text": "C#"
},
{
"code": null,
"e": 7615,
"s": 7604,
"text": "Javascript"
},
{
"code": "// Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexity #include <bits/stdc++.h>using namespace std; void bitonicGenerator(int arr[], int n){ // first odd index int i = 1; // last index int j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { swap(arr[i], arr[j]); i += 2; j -= 2; } // Sort first half in increasing sort(arr, arr + (n + 1) / 2); // Sort second half in decreasing sort(arr + (n + 1) / 2, arr + n, greater<int>());} // Driver Programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); bitonicGenerator(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}// This code is contributed by SWARUPANANDA DHUA",
"e": 8541,
"s": 7615,
"text": null
},
{
"code": "// Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexityimport java.util.Arrays;class GFG { static void bitonicGenerator(int arr[], int n) { // first odd index int i = 1; // last index int j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { arr = swap(arr, i, j); i += 2; j -= 2; } // Sort first half in increasing Arrays.sort(arr, 0, (n + 1) / 2); // Sort second half in decreasing Arrays.sort(arr, (n + 1) / 2, n); int low = (n + 1) / 2, high = n - 1; // Reverse the second half while (low < high) { Integer temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; low++; high--; } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver Program public static void main(String[] args) { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}// This code has been contributed by 29AjayKumar",
"e": 9976,
"s": 8541,
"text": null
},
{
"code": "# Python3 Program to sort even-placed elements in increasing and# odd-placed in decreasing order with constant space complexitydef bitonicGenerator(arr, n): # first odd index i = 1 # last index j = n - 1 # if last index is odd if (j % 2 != 0): # decrement j to even index j = j - 1 # swapping till half of array while (i < j) : arr[j], arr[i] = arr[i], arr[j] i = i + 2 j = j - 2 arr_f = [] arr_s = [] for i in range(int((n + 1) / 2)) : arr_f.append(arr[i]) i = int((n + 1) / 2) while( i < n ) : arr_s.append(arr[i]) i = i + 1 # Sort first half in increasing arr_f.sort() # Sort second half in decreasing arr_s.sort(reverse = True) for i in arr_s: arr_f.append(i) return arr_f # Driver Programarr = [ 1, 5, 8, 9, 6, 7, 3, 4, 2, 0]n = len(arr)arr = bitonicGenerator(arr, n)print(arr) # This code is contributed by Arnab Kundu",
"e": 10981,
"s": 9976,
"text": null
},
{
"code": "// Program to sort even-placed elements in// increasing and odd-placed in decreasing order// with constant space complexityusing System; class GFG{ static void bitonicGenerator(int []arr, int n) { // first odd index int i = 1; // last index int j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { arr = swap(arr, i, j); i += 2; j -= 2; } // Sort first half in increasing Array.Sort(arr, 0, (n + 1) / 2); // Sort second half in decreasing Array.Sort(arr, (n + 1) / 2, n - ((n + 1) / 2)); int low = (n + 1) / 2, high = n - 1; // Reverse the second half while (low < high) { int temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; low++; high--; } } static int[] swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr; } // Driver Code public static void Main(String[] args) { int []arr = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = arr.Length; bitonicGenerator(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by PrinciRaj1992",
"e": 12471,
"s": 10981,
"text": null
},
{
"code": "<script>// Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexityfunction bitonicGenerator(arr, n){ // first odd index let i = 1; // last index let j = n - 1; // if last index is odd if (j % 2 != 0) // decrement j to even index j--; // swapping till half of array while (i < j) { arr = swap(arr, i, j); i += 2; j -= 2; } // Sort first half in increasing // Sort second half in decreasing let temp1 = arr.slice(0,Math.floor((n+1)/2)).sort(function(a,b){return a-b;}); let temp2 = arr.slice(Math.floor((n+1)/2),n).sort(function(a,b){return b-a;}); arr = temp1.concat(temp2); return arr;} function swap(arr, i, j){ let temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; return arr;} // Driver Programlet arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0 ];let n = arr.length;arr = bitonicGenerator(arr, n);document.write(arr.join(\" \")); // This code is contributed by rag2127</script>",
"e": 13607,
"s": 12471,
"text": null
},
{
"code": null,
"e": 13628,
"s": 13607,
"text": "1 2 3 6 8 9 7 5 4 0 "
},
{
"code": null,
"e": 13681,
"s": 13628,
"text": "Time Complexity : O(n Log n) Space Complexity : O(1)"
},
{
"code": null,
"e": 13807,
"s": 13681,
"text": "Another approach:Another efficient approach to solve the problem in O(1) Auxiliary space is by Using negative multiplication."
},
{
"code": null,
"e": 13842,
"s": 13807,
"text": "The steps involved are as follows:"
},
{
"code": null,
"e": 14258,
"s": 13842,
"text": " Multiply all the elements at even placed index by -1.Sort the whole array. In this way, we can get all even placed index in the starting as they are negative numbers now.Now revert the sign of these elements.After this reverse the first half of the array which contains an even placed number to make it in increasing order.And then reverse the rest half of the array to make odd placed numbers in decreasing order."
},
{
"code": null,
"e": 14313,
"s": 14258,
"text": " Multiply all the elements at even placed index by -1."
},
{
"code": null,
"e": 14431,
"s": 14313,
"text": "Sort the whole array. In this way, we can get all even placed index in the starting as they are negative numbers now."
},
{
"code": null,
"e": 14470,
"s": 14431,
"text": "Now revert the sign of these elements."
},
{
"code": null,
"e": 14586,
"s": 14470,
"text": "After this reverse the first half of the array which contains an even placed number to make it in increasing order."
},
{
"code": null,
"e": 14678,
"s": 14586,
"text": "And then reverse the rest half of the array to make odd placed numbers in decreasing order."
},
{
"code": null,
"e": 14766,
"s": 14678,
"text": "Note: This method is only applicable if all the elements in the array are non-negative."
},
{
"code": null,
"e": 14813,
"s": 14766,
"text": "An illustrative example of the above approach:"
},
{
"code": null,
"e": 15227,
"s": 14813,
"text": "Let given array: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}Array after multiplying by -1 to even placed elements: arr[] = {0, 1, -2, 3, -4, 5, -6, 7}Array after sorting: arr[] = {-6, -4, -2, 0, 1, 3, 5, 7}Array after reverting negative values: arr[] = {6, 4, 2, 0, 1, 3, 5, 7}After reversing the first half of array: arr[] = {0, 2, 4, 6, 1, 3, 5, 7}After reversing the second half of array: arr[] = {0, 2, 4, 6, 7, 5, 3, 1}"
},
{
"code": null,
"e": 15269,
"s": 15227,
"text": "Below is the code for the above approach:"
},
{
"code": null,
"e": 15273,
"s": 15269,
"text": "C++"
},
{
"code": "// C++ Program to sort even-placed elements in increasing and// odd-placed in decreasing order with constant space complexity#include <bits/stdc++.h>using namespace std; void bitonicGenerator(int arr[], int n){ // Making all even placed index // element negative for (int i = 0; i < n; i++) { if (i % 2==0) arr[i]=-1*arr[i]; } // Sorting the whole array sort(arr,arr+n); // Finding the middle value of // the array int mid=(n-1)/2; // Reverting the changed sign for (int i = 0; i <= mid; i++) { arr[i]=-1*arr[i]; } // Reverse first half of array reverse(arr,arr+mid+1); // Reverse second half of array reverse(arr+mid+1,arr+n);} // Driver Programint main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); bitonicGenerator(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;} // This code is contributed by Pushpesh Raj.",
"e": 16267,
"s": 15273,
"text": null
},
{
"code": null,
"e": 16288,
"s": 16267,
"text": "1 2 3 6 8 9 7 5 4 0 "
},
{
"code": null,
"e": 16340,
"s": 16288,
"text": "Time Complexity: O(n*log(n)) Space Complexity: O(1)"
},
{
"code": null,
"e": 16652,
"s": 16340,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 16666,
"s": 16652,
"text": "princiraj1992"
},
{
"code": null,
"e": 16678,
"s": 16666,
"text": "29AjayKumar"
},
{
"code": null,
"e": 16688,
"s": 16678,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 16703,
"s": 16688,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 16714,
"s": 16703,
"text": "andrew1234"
},
{
"code": null,
"e": 16726,
"s": 16714,
"text": "unknown2108"
},
{
"code": null,
"e": 16734,
"s": 16726,
"text": "rag2127"
},
{
"code": null,
"e": 16750,
"s": 16734,
"text": "pushpeshrajdx01"
},
{
"code": null,
"e": 16767,
"s": 16750,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 16771,
"s": 16767,
"text": "STL"
},
{
"code": null,
"e": 16776,
"s": 16771,
"text": "Zoho"
},
{
"code": null,
"e": 16783,
"s": 16776,
"text": "Arrays"
},
{
"code": null,
"e": 16791,
"s": 16783,
"text": "Sorting"
},
{
"code": null,
"e": 16796,
"s": 16791,
"text": "Zoho"
},
{
"code": null,
"e": 16803,
"s": 16796,
"text": "Arrays"
},
{
"code": null,
"e": 16811,
"s": 16803,
"text": "Sorting"
},
{
"code": null,
"e": 16815,
"s": 16811,
"text": "STL"
},
{
"code": null,
"e": 16913,
"s": 16815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16945,
"s": 16913,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 16968,
"s": 16945,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 17024,
"s": 16968,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 17051,
"s": 17024,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 17096,
"s": 17051,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 17107,
"s": 17096,
"text": "Merge Sort"
},
{
"code": null,
"e": 17129,
"s": 17107,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 17139,
"s": 17129,
"text": "QuickSort"
},
{
"code": null,
"e": 17154,
"s": 17139,
"text": "Insertion Sort"
}
]
|
Python PIL | ImageSequence.Iterator() | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence.
ImageSequence.Iterator() This class implements an iterator object that can be used to loop over an image sequence. You can use the [ ] operator to access elements by index. This operator will raise an IndexError if you try to access a nonexistent frame.
Syntax: PIL.ImageSequence.Iterator(im)
Parameters:im – An image object.
Returns: An Image object.
Image Used:
# importing Image class from PIL package from PIL import Image, ImageSequence # creating a object im = Image.open(r"C:\Users\System-Pc\Desktop\home.png")index = 1for frame in ImageSequence.Iterator(im): frame.save("frame % d.png" % index) index = index + 1 im.getdata()im.show()
Output:
Another Example:Here we use another image .jpg extension.
Image Used:
# importing Image class from PIL package from PIL import Image, ImageSequence # creating a object im = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg")index = 1for frame in ImageSequence.Iterator(im): frame.save("frame % d.jpg" % index) index = index + 1 im.getdata()im.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageSequence module contains a wrapper class that lets you iterate over the frames of an image sequence."
},
{
"code": null,
"e": 497,
"s": 243,
"text": "ImageSequence.Iterator() This class implements an iterator object that can be used to loop over an image sequence. You can use the [ ] operator to access elements by index. This operator will raise an IndexError if you try to access a nonexistent frame."
},
{
"code": null,
"e": 536,
"s": 497,
"text": "Syntax: PIL.ImageSequence.Iterator(im)"
},
{
"code": null,
"e": 569,
"s": 536,
"text": "Parameters:im – An image object."
},
{
"code": null,
"e": 595,
"s": 569,
"text": "Returns: An Image object."
},
{
"code": null,
"e": 607,
"s": 595,
"text": "Image Used:"
},
{
"code": " # importing Image class from PIL package from PIL import Image, ImageSequence # creating a object im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\home.png\")index = 1for frame in ImageSequence.Iterator(im): frame.save(\"frame % d.png\" % index) index = index + 1 im.getdata()im.show()",
"e": 899,
"s": 607,
"text": null
},
{
"code": null,
"e": 907,
"s": 899,
"text": "Output:"
},
{
"code": null,
"e": 965,
"s": 907,
"text": "Another Example:Here we use another image .jpg extension."
},
{
"code": null,
"e": 977,
"s": 965,
"text": "Image Used:"
},
{
"code": " # importing Image class from PIL package from PIL import Image, ImageSequence # creating a object im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\")index = 1for frame in ImageSequence.Iterator(im): frame.save(\"frame % d.jpg\" % index) index = index + 1 im.getdata()im.show()",
"e": 1269,
"s": 977,
"text": null
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Output:"
},
{
"code": null,
"e": 1288,
"s": 1277,
"text": "Python-pil"
},
{
"code": null,
"e": 1295,
"s": 1288,
"text": "Python"
}
]
|
Convert Images to PDFs using Tkinter – Python | 20 Jan, 2022
Prerequisite: Tkinter, img2pdf
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to convert Multiple images to Multiple PDFs or Multiple Images to One PDF Using Tkinter in Python. For conversion, we will use the img2pdf Module.
img2pdf is an open-source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance the image (Brightness, contrast, and other things)
For installation runs this command into your terminal:
pip install img2pdf
Step 1: Create a Tkinter window and add Buttons, Labels, etc...
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # set Geometryroot.geometry('400x200') # Add Labels and ButtonsLabel(root, text = "IMAGE CONVERSION", font = "italic 15 bold").pack(pady = 10) Button(root, text = "Select Images", font = 14).pack(pady = 10) frame = Frame()frame.pack(pady = 20) Button(frame, text = "Image to PDF", relief = "solid", bg = "white", font = 15).pack(side = LEFT,padx = 10) Button(frame, text = "Images to PDF", relief = "solid", bg = "white",font = 15).pack() # Execute Tkinterroot.mainloop()
Step 2: We will create three functions; select_file(), image_to_pdf(), images_to_pdf()
select_file: It will help you to select the file
image_to_pdf: It is used for converting one image file to one pdf file
images_to_pdf: It is used for converting Multiple image files to one pdf file
Python3
def select_file(): global file_names file_names = askopenfilenames(initialdir = "/",title = "Select File") # IMAGE TO PDFdef image_to_pdf(): for index, file_name in enumerate(file_names): with open(f"file {index}.pdf", "wb") as f: f.write(img2pdf.convert(file_name)) # IMAGES TO PDFdef images_to_pdf(): with open(f"file.pdf","wb") as f: f.write(img2pdf.convert(file_names))
Below is the implementation:
Python3
# Import Modulefrom tkinter import *from tkinter.filedialog import askopenfilenamesimport img2pdf # Create Objectroot = Tk() # set Geometryroot.geometry('400x200') def select_file(): global file_names file_names = askopenfilenames(initialdir = "/", title = "Select File") # IMAGE TO PDFdef image_to_pdf(): for index, file_name in enumerate(file_names): with open(f"file {index}.pdf", "wb") as f: f.write(img2pdf.convert(file_name)) # IMAGES TO PDFdef images_to_pdf(): with open(f"file.pdf", "wb") as f: f.write(img2pdf.convert(file_names)) # Add Labels and ButtonsLabel(root, text = "IMAGE CONVERSION", font = "italic 15 bold").pack(pady = 10) Button(root, text = "Select Images", command = select_file, font = 14).pack(pady = 10) frame = Frame()frame.pack(pady = 20) Button(frame, text = "Image to PDF", command = image_to_pdf, relief = "solid", bg = "white", font = 15).pack(side = LEFT, padx = 10) Button(frame, text = "Images to PDF", command = images_to_pdf, relief = "solid", bg = "white", font = 15).pack() # Execute Tkinterroot.mainloop()
Output:
simmytarika5
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 59,
"s": 28,
"text": "Prerequisite: Tkinter, img2pdf"
},
{
"code": null,
"e": 545,
"s": 59,
"text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article, we will learn how to convert Multiple images to Multiple PDFs or Multiple Images to One PDF Using Tkinter in Python. For conversion, we will use the img2pdf Module."
},
{
"code": null,
"e": 738,
"s": 545,
"text": "img2pdf is an open-source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance the image (Brightness, contrast, and other things)"
},
{
"code": null,
"e": 793,
"s": 738,
"text": "For installation runs this command into your terminal:"
},
{
"code": null,
"e": 813,
"s": 793,
"text": "pip install img2pdf"
},
{
"code": null,
"e": 877,
"s": 813,
"text": "Step 1: Create a Tkinter window and add Buttons, Labels, etc..."
},
{
"code": null,
"e": 885,
"s": 877,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import * # Create Objectroot = Tk() # set Geometryroot.geometry('400x200') # Add Labels and ButtonsLabel(root, text = \"IMAGE CONVERSION\", font = \"italic 15 bold\").pack(pady = 10) Button(root, text = \"Select Images\", font = 14).pack(pady = 10) frame = Frame()frame.pack(pady = 20) Button(frame, text = \"Image to PDF\", relief = \"solid\", bg = \"white\", font = 15).pack(side = LEFT,padx = 10) Button(frame, text = \"Images to PDF\", relief = \"solid\", bg = \"white\",font = 15).pack() # Execute Tkinterroot.mainloop()",
"e": 1470,
"s": 885,
"text": null
},
{
"code": null,
"e": 1557,
"s": 1470,
"text": "Step 2: We will create three functions; select_file(), image_to_pdf(), images_to_pdf()"
},
{
"code": null,
"e": 1607,
"s": 1557,
"text": "select_file: It will help you to select the file "
},
{
"code": null,
"e": 1678,
"s": 1607,
"text": "image_to_pdf: It is used for converting one image file to one pdf file"
},
{
"code": null,
"e": 1756,
"s": 1678,
"text": "images_to_pdf: It is used for converting Multiple image files to one pdf file"
},
{
"code": null,
"e": 1764,
"s": 1756,
"text": "Python3"
},
{
"code": "def select_file(): global file_names file_names = askopenfilenames(initialdir = \"/\",title = \"Select File\") # IMAGE TO PDFdef image_to_pdf(): for index, file_name in enumerate(file_names): with open(f\"file {index}.pdf\", \"wb\") as f: f.write(img2pdf.convert(file_name)) # IMAGES TO PDFdef images_to_pdf(): with open(f\"file.pdf\",\"wb\") as f: f.write(img2pdf.convert(file_names))",
"e": 2177,
"s": 1764,
"text": null
},
{
"code": null,
"e": 2206,
"s": 2177,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 2214,
"s": 2206,
"text": "Python3"
},
{
"code": "# Import Modulefrom tkinter import *from tkinter.filedialog import askopenfilenamesimport img2pdf # Create Objectroot = Tk() # set Geometryroot.geometry('400x200') def select_file(): global file_names file_names = askopenfilenames(initialdir = \"/\", title = \"Select File\") # IMAGE TO PDFdef image_to_pdf(): for index, file_name in enumerate(file_names): with open(f\"file {index}.pdf\", \"wb\") as f: f.write(img2pdf.convert(file_name)) # IMAGES TO PDFdef images_to_pdf(): with open(f\"file.pdf\", \"wb\") as f: f.write(img2pdf.convert(file_names)) # Add Labels and ButtonsLabel(root, text = \"IMAGE CONVERSION\", font = \"italic 15 bold\").pack(pady = 10) Button(root, text = \"Select Images\", command = select_file, font = 14).pack(pady = 10) frame = Frame()frame.pack(pady = 20) Button(frame, text = \"Image to PDF\", command = image_to_pdf, relief = \"solid\", bg = \"white\", font = 15).pack(side = LEFT, padx = 10) Button(frame, text = \"Images to PDF\", command = images_to_pdf, relief = \"solid\", bg = \"white\", font = 15).pack() # Execute Tkinterroot.mainloop()",
"e": 3382,
"s": 2214,
"text": null
},
{
"code": null,
"e": 3390,
"s": 3382,
"text": "Output:"
},
{
"code": null,
"e": 3403,
"s": 3390,
"text": "simmytarika5"
},
{
"code": null,
"e": 3418,
"s": 3403,
"text": "python-utility"
},
{
"code": null,
"e": 3425,
"s": 3418,
"text": "Python"
}
]
|
Java Program to Iterate Vector using Enumeration | 10 Feb, 2022
The Vector class implements a growable array of objects. It is available in java.util package. It implements the List interface. The Enumeration interface defines the methods by which you can traverse the elements in a collection of objects. Now in order to add elements
Vector Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
java.util.Enumeration interface is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable( like Stack, Vector, HashTable, etc.) in a forward direction only and not in the backward direction.
You can use the Java.util.Vector.addElement() method to append a specified element to the end of this vector by increasing the size of the vector by 1. The functionality of this method is similar to that of the add() method of the Vector class.
Syntax:
boolean addElement(Object element)
Parameters: This function accepts a single parameter element of object type and refers to the element specified by this parameter is appended to the end of the vector.
Return Value: This is a void type method and does not return any value.
Example 1:
Java
// Java Program to Iterate Vector using Enumeration // Importing Enumeration classimport java.util.Enumeration; // Importing vector classimport java.util.Vector; public class GFG { // Main driver method public static void main(String a[]) { // Creating a new vector Vector<String> v = new Vector<String>(); // Adding elements to the end v.add("Welcome"); v.add("To"); v.add("Geeks for"); v.add("Geeks"); // Creating an object of enum Enumeration<String> en = v.elements(); while (en.hasMoreElements()) { // Print the elements using enum object // of the elements added in the vector System.out.println(en.nextElement()); } }}
Welcome
To
Geeks for
Geeks
Example 2:
Java
// Java Program to Iterate Vector using Enumeration // Importing Enumeration classimport java.util.Enumeration;// Importing Vector classimport java.util.Vector; public class GFG { // Main driver method public static void main(String a[]) { // Creating a vector object Vector<Integer> v = new Vector<Integer>(); // Adding elements to the end v.add(1); v.add(2); v.add(3); v.add(4); // Creating an enum object Enumeration<Integer> en = v.elements(); while (en.hasMoreElements()) { // Displaying elements of vector class // calling enum object System.out.println(en.nextElement()); } }}
1
2
3
4
avtarkumar719
Java-Vector
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 300,
"s": 28,
"text": "The Vector class implements a growable array of objects. It is available in java.util package. It implements the List interface. The Enumeration interface defines the methods by which you can traverse the elements in a collection of objects. Now in order to add elements "
},
{
"code": null,
"e": 315,
"s": 300,
"text": "Vector Syntax:"
},
{
"code": null,
"e": 420,
"s": 315,
"text": "public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable"
},
{
"code": null,
"e": 672,
"s": 420,
"text": "java.util.Enumeration interface is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable( like Stack, Vector, HashTable, etc.) in a forward direction only and not in the backward direction. "
},
{
"code": null,
"e": 917,
"s": 672,
"text": "You can use the Java.util.Vector.addElement() method to append a specified element to the end of this vector by increasing the size of the vector by 1. The functionality of this method is similar to that of the add() method of the Vector class."
},
{
"code": null,
"e": 925,
"s": 917,
"text": "Syntax:"
},
{
"code": null,
"e": 960,
"s": 925,
"text": "boolean addElement(Object element)"
},
{
"code": null,
"e": 1128,
"s": 960,
"text": "Parameters: This function accepts a single parameter element of object type and refers to the element specified by this parameter is appended to the end of the vector."
},
{
"code": null,
"e": 1200,
"s": 1128,
"text": "Return Value: This is a void type method and does not return any value."
},
{
"code": null,
"e": 1211,
"s": 1200,
"text": "Example 1:"
},
{
"code": null,
"e": 1216,
"s": 1211,
"text": "Java"
},
{
"code": "// Java Program to Iterate Vector using Enumeration // Importing Enumeration classimport java.util.Enumeration; // Importing vector classimport java.util.Vector; public class GFG { // Main driver method public static void main(String a[]) { // Creating a new vector Vector<String> v = new Vector<String>(); // Adding elements to the end v.add(\"Welcome\"); v.add(\"To\"); v.add(\"Geeks for\"); v.add(\"Geeks\"); // Creating an object of enum Enumeration<String> en = v.elements(); while (en.hasMoreElements()) { // Print the elements using enum object // of the elements added in the vector System.out.println(en.nextElement()); } }}",
"e": 1969,
"s": 1216,
"text": null
},
{
"code": null,
"e": 1999,
"s": 1972,
"text": "Welcome\nTo\nGeeks for\nGeeks"
},
{
"code": null,
"e": 2012,
"s": 2001,
"text": "Example 2:"
},
{
"code": null,
"e": 2019,
"s": 2014,
"text": "Java"
},
{
"code": "// Java Program to Iterate Vector using Enumeration // Importing Enumeration classimport java.util.Enumeration;// Importing Vector classimport java.util.Vector; public class GFG { // Main driver method public static void main(String a[]) { // Creating a vector object Vector<Integer> v = new Vector<Integer>(); // Adding elements to the end v.add(1); v.add(2); v.add(3); v.add(4); // Creating an enum object Enumeration<Integer> en = v.elements(); while (en.hasMoreElements()) { // Displaying elements of vector class // calling enum object System.out.println(en.nextElement()); } }}",
"e": 2731,
"s": 2019,
"text": null
},
{
"code": null,
"e": 2742,
"s": 2734,
"text": "1\n2\n3\n4"
},
{
"code": null,
"e": 2758,
"s": 2744,
"text": "avtarkumar719"
},
{
"code": null,
"e": 2770,
"s": 2758,
"text": "Java-Vector"
},
{
"code": null,
"e": 2777,
"s": 2770,
"text": "Picked"
},
{
"code": null,
"e": 2801,
"s": 2777,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2806,
"s": 2801,
"text": "Java"
},
{
"code": null,
"e": 2820,
"s": 2806,
"text": "Java Programs"
},
{
"code": null,
"e": 2839,
"s": 2820,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2844,
"s": 2839,
"text": "Java"
},
{
"code": null,
"e": 2942,
"s": 2844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2957,
"s": 2942,
"text": "Stream In Java"
},
{
"code": null,
"e": 2978,
"s": 2957,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2999,
"s": 2978,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3018,
"s": 2999,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3035,
"s": 3018,
"text": "Generics in Java"
},
{
"code": null,
"e": 3061,
"s": 3035,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3095,
"s": 3061,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3142,
"s": 3095,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3180,
"s": 3142,
"text": "Factory method design pattern in Java"
}
]
|
Traverse Through ArrayList in Forward Direction in Java | 11 Dec, 2020
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in a proper organized sequence). ArrayList can be traversed in the forward direction using multiple ways.
Example:
Input : ArrayList: [5, 6, 8, 10]
Output:
Value is : 5
Value is : 6
Value is : 8
Value is : 10
Approach 1: Using listIterator Method
Create a list iterator object of a given ArrayList.Use while loop with the condition as hasNext() method.If hasNext() method returns false, loop breaks.Else print the value using object.next() method.
Create a list iterator object of a given ArrayList.
Use while loop with the condition as hasNext() method.
If hasNext() method returns false, loop breaks.
Else print the value using object.next() method.
Example:
Java
// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); ListIterator<Integer> it = alist.listIterator(); while (it.hasNext()) { System.out.println("Value is : " + it.next()); } }}
Value is : 5
Value is : 6
Value is : 8
Value is : 10
Time Complexity: O(N), where N is the length of ArrayList.
Approach 2: Using For Loop
Print all the values in ArrayList using for loop. Size of ArrayList can be obtained using ArrayList.size() method and for accessing the element use ArrayList.get() method.
Implementation:
Java
// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); for (int i = 0; i < alist.size(); i++) System.out.println("Value is : " + alist.get(i)); }}
Value is : 5
Value is : 6
Value is : 8
Value is : 10
Time Complexity: O(N), where N is the length of ArrayList.
Approach 3: Using forEach Loop
Print all the values in ArrayList using for each loop.
Example:
Java
// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); for (Integer i : alist) System.out.println("Value is : " + i); }}
Value is : 5
Value is : 6
Value is : 8
Value is : 10
Time Complexity: O(N), where N is the length of ArrayList.
Approach 4: Using Lambda Function
Print all the values in ArrayList using the lambda function.
Example:
Java
// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); // lambda alist.forEach( i -> System.out.println("Value is : " + i)); }}
Value is : 5
Value is : 6
Value is : 8
Value is : 10
Time Complexity: O(N), where N is the length of ArrayList.
Java-ArrayList
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 384,
"s": 28,
"text": "ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. The listIterator() method of java.util.ArrayList class is used to return a list iterator over the elements in this list (in a proper organized sequence). ArrayList can be traversed in the forward direction using multiple ways."
},
{
"code": null,
"e": 393,
"s": 384,
"text": "Example:"
},
{
"code": null,
"e": 487,
"s": 393,
"text": "Input : ArrayList: [5, 6, 8, 10]\nOutput:\nValue is : 5\nValue is : 6\nValue is : 8\nValue is : 10"
},
{
"code": null,
"e": 525,
"s": 487,
"text": "Approach 1: Using listIterator Method"
},
{
"code": null,
"e": 726,
"s": 525,
"text": "Create a list iterator object of a given ArrayList.Use while loop with the condition as hasNext() method.If hasNext() method returns false, loop breaks.Else print the value using object.next() method."
},
{
"code": null,
"e": 778,
"s": 726,
"text": "Create a list iterator object of a given ArrayList."
},
{
"code": null,
"e": 833,
"s": 778,
"text": "Use while loop with the condition as hasNext() method."
},
{
"code": null,
"e": 881,
"s": 833,
"text": "If hasNext() method returns false, loop breaks."
},
{
"code": null,
"e": 930,
"s": 881,
"text": "Else print the value using object.next() method."
},
{
"code": null,
"e": 939,
"s": 930,
"text": "Example:"
},
{
"code": null,
"e": 944,
"s": 939,
"text": "Java"
},
{
"code": "// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); ListIterator<Integer> it = alist.listIterator(); while (it.hasNext()) { System.out.println(\"Value is : \" + it.next()); } }}",
"e": 1443,
"s": 944,
"text": null
},
{
"code": null,
"e": 1496,
"s": 1443,
"text": "Value is : 5\nValue is : 6\nValue is : 8\nValue is : 10"
},
{
"code": null,
"e": 1555,
"s": 1496,
"text": "Time Complexity: O(N), where N is the length of ArrayList."
},
{
"code": null,
"e": 1582,
"s": 1555,
"text": "Approach 2: Using For Loop"
},
{
"code": null,
"e": 1755,
"s": 1582,
"text": "Print all the values in ArrayList using for loop. Size of ArrayList can be obtained using ArrayList.size() method and for accessing the element use ArrayList.get() method. "
},
{
"code": null,
"e": 1771,
"s": 1755,
"text": "Implementation:"
},
{
"code": null,
"e": 1776,
"s": 1771,
"text": "Java"
},
{
"code": "// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); for (int i = 0; i < alist.size(); i++) System.out.println(\"Value is : \" + alist.get(i)); }}",
"e": 2257,
"s": 1776,
"text": null
},
{
"code": null,
"e": 2310,
"s": 2257,
"text": "Value is : 5\nValue is : 6\nValue is : 8\nValue is : 10"
},
{
"code": null,
"e": 2369,
"s": 2310,
"text": "Time Complexity: O(N), where N is the length of ArrayList."
},
{
"code": null,
"e": 2400,
"s": 2369,
"text": "Approach 3: Using forEach Loop"
},
{
"code": null,
"e": 2455,
"s": 2400,
"text": "Print all the values in ArrayList using for each loop."
},
{
"code": null,
"e": 2464,
"s": 2455,
"text": "Example:"
},
{
"code": null,
"e": 2469,
"s": 2464,
"text": "Java"
},
{
"code": "// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); for (Integer i : alist) System.out.println(\"Value is : \" + i); }}",
"e": 2894,
"s": 2469,
"text": null
},
{
"code": null,
"e": 2947,
"s": 2894,
"text": "Value is : 5\nValue is : 6\nValue is : 8\nValue is : 10"
},
{
"code": null,
"e": 3006,
"s": 2947,
"text": "Time Complexity: O(N), where N is the length of ArrayList."
},
{
"code": null,
"e": 3040,
"s": 3006,
"text": "Approach 4: Using Lambda Function"
},
{
"code": null,
"e": 3101,
"s": 3040,
"text": "Print all the values in ArrayList using the lambda function."
},
{
"code": null,
"e": 3110,
"s": 3101,
"text": "Example:"
},
{
"code": null,
"e": 3115,
"s": 3110,
"text": "Java"
},
{
"code": "// Traverse through ArrayList in// forward direction using Javaimport java.util.*;import java.io.*; class GFG { public static void main(String[] args) { ArrayList<Integer> alist = new ArrayList<>(); // adding element to arrlist alist.add(5); alist.add(6); alist.add(8); alist.add(10); // lambda alist.forEach( i -> System.out.println(\"Value is : \" + i)); }}",
"e": 3552,
"s": 3115,
"text": null
},
{
"code": null,
"e": 3605,
"s": 3552,
"text": "Value is : 5\nValue is : 6\nValue is : 8\nValue is : 10"
},
{
"code": null,
"e": 3664,
"s": 3605,
"text": "Time Complexity: O(N), where N is the length of ArrayList."
},
{
"code": null,
"e": 3679,
"s": 3664,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 3686,
"s": 3679,
"text": "Picked"
},
{
"code": null,
"e": 3710,
"s": 3686,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3715,
"s": 3710,
"text": "Java"
},
{
"code": null,
"e": 3729,
"s": 3715,
"text": "Java Programs"
},
{
"code": null,
"e": 3748,
"s": 3729,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3753,
"s": 3748,
"text": "Java"
}
]
|
Why is python best suited for Competitive Coding? | 04 Oct, 2021
When it comes to Product Based Companies, they need good coders and one needs to clear the Competitive Coding round in order to reach the interview rounds. Competitive coding is one such platform that will test your mental ability and speed at the same time.
Who should read this?
Any programmer who still hasn't tried python for
Competitive Coding MUST give this article a read.
This should clear up any doubts one has before
shifting to python.No matter how comfortable
a programming language may seem to you right now
Python is bound to feel even better.
Python has a tendency of sticking to people
like a bad habit !!
SPEED is a factor where python is second to none. The amount of code to be typed decreases drastically in comparison to conventional programming languages like C, C++, JAVA. Another most important point is that python arms its users with a wide variety of functionality, packages, and libraries that act as a supplement to the programmer’s mental ability. Ultimately the best thing about python is that it’s very simple and we need not waste much time on trivial matters like input, output, etc. It helps shift our focus to the problem at hand.Here I’m gonna list out some of my favorite features of Python which I’m sure will encourage you to start trying python for Competitive Coding.
1.Variable Independence Python doesn’t require us to declare variables and their Data-Types before using them. This also gives us the flexibility of range as long as it’s within reasonable limits of the Hardware i.e. no need to worry about integer and long integer. Type conversion is internally handled with flawless results.
Amazing Fact !!
For nested loops in python we can use the
same variable name in both inner and outer
for-loop variables without fear of
inconsistent data or any errors !!
2.Common Functions like sorted, min, max, count, etc. The min/max function helps us to find the minimum/maximum element from a list. The Sorted function allows us to sort a list and the count function helps us to count the number of occurrences of a particular element in a list. The best thing is that we can rest assured that the python libraries use the best possible algorithms for each of the above operations. For example, the sorted function is a very special sorting algorithm called TIMSORT that has a worst-case time complexity of O(n log n) which is the best a sorting algorithm can offer.
Reference: Python sorting algorithm
Python
# Python code to demonstrate working of min(),# max(), sorted() and count()arr = [10, 76, 87, 45, 22, 87, 90, 87, 66, 84, 87] print("Maximum = ",max(arr))print("Minimum = ",min(arr))print("The sorted array is = ",sorted(arr))print('Number of occurrences of 87 is = ',arr.count(87))
Output:
('Maximum = ', 90)
('Minimum = ', 10)
('The sorted array is = ', [10, 22, 45, 66, 76, 84, 87, 87, 87, 87, 90])
('Number of occurrences of 87 is = ', 4)
3.Lists in python combine the best aspects of arrays and linked lists. Python lists provide the unique functionality of deleting specific elements while keeping the memory locations in a contiguous manner. This feature renders the concept of Linked lists null and void. It’s like a linked list on STEROIDS! Moreover, Insertions can be performed at any desired location.
Python
# Python code to demonstrate list operationsarr = [00, 11, 22, 33, 44, 55, 66, 77, 88, 99] # deletion via index positiondel arr[5]print(arr) # deletion via specifying particular elementarr.remove(22)print(arr) # insertion at any arbitrary positionarr[-1] = "A random number"print(arr) # concept of sub-listsk = arr[:2]print(k)
Output:
[0, 11, 22, 33, 44, 66, 77, 88, 99]
[0, 11, 33, 44, 66, 77, 88, 99]
[0, 11, 33, 44, 66, 77, 88, 'A random number']
[0, 11]
4.Unique list operations – Backtracking, Sub-Lists. In case we are not sure about the list size then we can use the index position of -1 to access the last element. Similarly, -2 can be used for the second last element and so on. Thus we can backtrack a list. Also, we don’t have to specify any particular list size so it also works as a dynamic allocation array. A specific portion of a list can be extracted without having to traverse the list as is seen in the above example. A very astonishing fact about lists is that they can hold different data types. Gone are the days where lists used to be a homogeneous collection of data elements!!
Functions can return more than one value. Typically functions in other programming languages can return only one value but in python, we can return more than one value!! as is seen in the following code snippet.
Python
# Python code to demonstrate that a function# can easily return multiple values.def multi_return(*arr): k1 = arr[0] k2 = arr[1] return k1,k2 a,b = multi_return(11,22)print(a,' ',b) a,b = multi_return(55,66,77,88,99)print(a,' ',b)
Output:
11 22
55 66
5.A flexible number of arguments to a function. Arguments to a function may be passed in the form of a list whose size may vary every time we need to call the function. In the above example, we first called the function with 2 arguments and then with 5 arguments!!
If else and for loops are much more User Friendly. The if-else statement of python allows us to search for a particular element in a list without the need of traversing the entire list and checking each element. Some programming languages have a concept of a for each loop which is slightly different from a for a loop. It allows us to traverse a list where the loop variable takes upon the list values one by one. Python incorporates each loop concept in the for loop itself.
Python
# Python code to demonstrate quick searching arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] # searching made easyif 3 in arr: print("YES")else: print("NO") #foreach loopfor i in arr: print(i,end = ' ')
Output:
YES
1 2 3 4 5 6 7 8 9
Code Indentation. Python blocks of code are distinguished on the basis of their indentation. This provides better code readability and instills in us a good habit of indenting our code.
Concept of Sets and Dictionaries. A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. It’s like a list that doesn’t allow duplicate elements. A dictionary is like a list whose values can be accessed by user-defined keys instead of conventional numeric index values.
Python
# Python code to demonstrate use of dictionaries# and sets.a = {'a','b','c','d','e','a'} # the second 'a' is dropped to avoid repetitionprint(a) dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}print("dict['Name']: ", dict['Name'])print("dict['Age']: ", dict['Age'])
Output:
{'d', 'a', 'e', 'b', 'c'}
dict['Name']: Zara
dict['Age']: 7
Robust input statements. In competitive coding, we are often required to take ‘n’ space-separated integers as input and preferably save them in a list/array. Python provides functionality to do it all in a single line of code.!!
Python3
# Python code to demonstrate how to take space# separated inputs.arr = [int(a) for a in input().strip().split(' ')] print(arr)
ManasChhabra2
punamsingh628700
simmytarika5
Competitive Programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 311,
"s": 52,
"text": "When it comes to Product Based Companies, they need good coders and one needs to clear the Competitive Coding round in order to reach the interview rounds. Competitive coding is one such platform that will test your mental ability and speed at the same time."
},
{
"code": null,
"e": 707,
"s": 311,
"text": "Who should read this?\n Any programmer who still hasn't tried python for\n Competitive Coding MUST give this article a read.\n This should clear up any doubts one has before \n shifting to python.No matter how comfortable\n a programming language may seem to you right now\n Python is bound to feel even better.\n Python has a tendency of sticking to people\n like a bad habit !!"
},
{
"code": null,
"e": 1397,
"s": 707,
"text": "SPEED is a factor where python is second to none. The amount of code to be typed decreases drastically in comparison to conventional programming languages like C, C++, JAVA. Another most important point is that python arms its users with a wide variety of functionality, packages, and libraries that act as a supplement to the programmer’s mental ability. Ultimately the best thing about python is that it’s very simple and we need not waste much time on trivial matters like input, output, etc. It helps shift our focus to the problem at hand.Here I’m gonna list out some of my favorite features of Python which I’m sure will encourage you to start trying python for Competitive Coding. "
},
{
"code": null,
"e": 1725,
"s": 1397,
"text": "1.Variable Independence Python doesn’t require us to declare variables and their Data-Types before using them. This also gives us the flexibility of range as long as it’s within reasonable limits of the Hardware i.e. no need to worry about integer and long integer. Type conversion is internally handled with flawless results. "
},
{
"code": null,
"e": 1938,
"s": 1725,
"text": "Amazing Fact !!\n For nested loops in python we can use the \n same variable name in both inner and outer\n for-loop variables without fear of \n inconsistent data or any errors !!"
},
{
"code": null,
"e": 2540,
"s": 1938,
"text": "2.Common Functions like sorted, min, max, count, etc. The min/max function helps us to find the minimum/maximum element from a list. The Sorted function allows us to sort a list and the count function helps us to count the number of occurrences of a particular element in a list. The best thing is that we can rest assured that the python libraries use the best possible algorithms for each of the above operations. For example, the sorted function is a very special sorting algorithm called TIMSORT that has a worst-case time complexity of O(n log n) which is the best a sorting algorithm can offer. "
},
{
"code": null,
"e": 2576,
"s": 2540,
"text": "Reference: Python sorting algorithm"
},
{
"code": null,
"e": 2583,
"s": 2576,
"text": "Python"
},
{
"code": "# Python code to demonstrate working of min(),# max(), sorted() and count()arr = [10, 76, 87, 45, 22, 87, 90, 87, 66, 84, 87] print(\"Maximum = \",max(arr))print(\"Minimum = \",min(arr))print(\"The sorted array is = \",sorted(arr))print('Number of occurrences of 87 is = ',arr.count(87))",
"e": 2865,
"s": 2583,
"text": null
},
{
"code": null,
"e": 2874,
"s": 2865,
"text": "Output: "
},
{
"code": null,
"e": 3026,
"s": 2874,
"text": "('Maximum = ', 90)\n('Minimum = ', 10)\n('The sorted array is = ', [10, 22, 45, 66, 76, 84, 87, 87, 87, 87, 90])\n('Number of occurrences of 87 is = ', 4)"
},
{
"code": null,
"e": 3396,
"s": 3026,
"text": "3.Lists in python combine the best aspects of arrays and linked lists. Python lists provide the unique functionality of deleting specific elements while keeping the memory locations in a contiguous manner. This feature renders the concept of Linked lists null and void. It’s like a linked list on STEROIDS! Moreover, Insertions can be performed at any desired location."
},
{
"code": null,
"e": 3403,
"s": 3396,
"text": "Python"
},
{
"code": "# Python code to demonstrate list operationsarr = [00, 11, 22, 33, 44, 55, 66, 77, 88, 99] # deletion via index positiondel arr[5]print(arr) # deletion via specifying particular elementarr.remove(22)print(arr) # insertion at any arbitrary positionarr[-1] = \"A random number\"print(arr) # concept of sub-listsk = arr[:2]print(k)",
"e": 3730,
"s": 3403,
"text": null
},
{
"code": null,
"e": 3739,
"s": 3730,
"text": "Output: "
},
{
"code": null,
"e": 3862,
"s": 3739,
"text": "[0, 11, 22, 33, 44, 66, 77, 88, 99]\n[0, 11, 33, 44, 66, 77, 88, 99]\n[0, 11, 33, 44, 66, 77, 88, 'A random number']\n[0, 11]"
},
{
"code": null,
"e": 4506,
"s": 3862,
"text": "4.Unique list operations – Backtracking, Sub-Lists. In case we are not sure about the list size then we can use the index position of -1 to access the last element. Similarly, -2 can be used for the second last element and so on. Thus we can backtrack a list. Also, we don’t have to specify any particular list size so it also works as a dynamic allocation array. A specific portion of a list can be extracted without having to traverse the list as is seen in the above example. A very astonishing fact about lists is that they can hold different data types. Gone are the days where lists used to be a homogeneous collection of data elements!!"
},
{
"code": null,
"e": 4719,
"s": 4506,
"text": "Functions can return more than one value. Typically functions in other programming languages can return only one value but in python, we can return more than one value!! as is seen in the following code snippet. "
},
{
"code": null,
"e": 4726,
"s": 4719,
"text": "Python"
},
{
"code": "# Python code to demonstrate that a function# can easily return multiple values.def multi_return(*arr): k1 = arr[0] k2 = arr[1] return k1,k2 a,b = multi_return(11,22)print(a,' ',b) a,b = multi_return(55,66,77,88,99)print(a,' ',b)",
"e": 4969,
"s": 4726,
"text": null
},
{
"code": null,
"e": 4978,
"s": 4969,
"text": "Output: "
},
{
"code": null,
"e": 4994,
"s": 4978,
"text": "11 22\n55 66"
},
{
"code": null,
"e": 5260,
"s": 4994,
"text": "5.A flexible number of arguments to a function. Arguments to a function may be passed in the form of a list whose size may vary every time we need to call the function. In the above example, we first called the function with 2 arguments and then with 5 arguments!! "
},
{
"code": null,
"e": 5737,
"s": 5260,
"text": "If else and for loops are much more User Friendly. The if-else statement of python allows us to search for a particular element in a list without the need of traversing the entire list and checking each element. Some programming languages have a concept of a for each loop which is slightly different from a for a loop. It allows us to traverse a list where the loop variable takes upon the list values one by one. Python incorporates each loop concept in the for loop itself."
},
{
"code": null,
"e": 5744,
"s": 5737,
"text": "Python"
},
{
"code": "# Python code to demonstrate quick searching arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] # searching made easyif 3 in arr: print(\"YES\")else: print(\"NO\") #foreach loopfor i in arr: print(i,end = ' ')",
"e": 5942,
"s": 5744,
"text": null
},
{
"code": null,
"e": 5951,
"s": 5942,
"text": "Output: "
},
{
"code": null,
"e": 5974,
"s": 5951,
"text": "YES\n1 2 3 4 5 6 7 8 9 "
},
{
"code": null,
"e": 6160,
"s": 5974,
"text": "Code Indentation. Python blocks of code are distinguished on the basis of their indentation. This provides better code readability and instills in us a good habit of indenting our code."
},
{
"code": null,
"e": 6475,
"s": 6160,
"text": "Concept of Sets and Dictionaries. A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. It’s like a list that doesn’t allow duplicate elements. A dictionary is like a list whose values can be accessed by user-defined keys instead of conventional numeric index values. "
},
{
"code": null,
"e": 6482,
"s": 6475,
"text": "Python"
},
{
"code": "# Python code to demonstrate use of dictionaries# and sets.a = {'a','b','c','d','e','a'} # the second 'a' is dropped to avoid repetitionprint(a) dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}print(\"dict['Name']: \", dict['Name'])print(\"dict['Age']: \", dict['Age'])",
"e": 6751,
"s": 6482,
"text": null
},
{
"code": null,
"e": 6760,
"s": 6751,
"text": "Output: "
},
{
"code": null,
"e": 6822,
"s": 6760,
"text": "{'d', 'a', 'e', 'b', 'c'}\ndict['Name']: Zara\ndict['Age']: 7"
},
{
"code": null,
"e": 7052,
"s": 6822,
"text": "Robust input statements. In competitive coding, we are often required to take ‘n’ space-separated integers as input and preferably save them in a list/array. Python provides functionality to do it all in a single line of code.!! "
},
{
"code": null,
"e": 7060,
"s": 7052,
"text": "Python3"
},
{
"code": "# Python code to demonstrate how to take space# separated inputs.arr = [int(a) for a in input().strip().split(' ')] print(arr)",
"e": 7187,
"s": 7060,
"text": null
},
{
"code": null,
"e": 7201,
"s": 7187,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 7218,
"s": 7201,
"text": "punamsingh628700"
},
{
"code": null,
"e": 7231,
"s": 7218,
"text": "simmytarika5"
},
{
"code": null,
"e": 7255,
"s": 7231,
"text": "Competitive Programming"
},
{
"code": null,
"e": 7262,
"s": 7255,
"text": "Python"
}
]
|
Program for Best Fit algorithm in Memory Management | 09 Mar, 2022
Prerequisite : Partition allocation methodsBest fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions. Example:
Input : blockSize[] = {100, 500, 200, 300, 600};
processSize[] = {212, 417, 112, 426};
Output:
Process No. Process Size Block no.
1 212 4
2 417 2
3 112 3
4 426 5
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Implementation:
1- Input memory blocks and processes with sizes.
2- Initialize all memory blocks as free.
3- Start by picking each process and find the
minimum block size that can be assigned to
current process i.e., find min(bockSize[1],
blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign
it to the current process.
5- If not then leave that process and keep checking
the further processes.
Below is implementation.
C/C++
// C++ implementation of Best - Fit algorithm
#include<bits/stdc++.h>
using namespace std;
// Function to allocate memory to blocks as per Best fit
// algorithm
void bestFit(int blockSize[], int m, int processSize[], int n)
{
// Stores block id of the block allocated to a
// process
int allocation[n];
// Initially no block is assigned to any process
memset(allocation, -1, sizeof(allocation));
// pick each process and find suitable blocks
// according to its size ad assign to it
for (int i=0; i<n; i++)
{
// Find the best fit block for current process
int bestIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] > blockSize[j])
bestIdx = j;
}
}
// If we could find a block for current process
if (bestIdx != -1)
{
// allocate block j to p[i] process
allocation[i] = bestIdx;
// Reduce available memory in this block.
blockSize[bestIdx] -= processSize[i];
}
}
cout << "\nProcess No.\tProcess Size\tBlock no.\n";
for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}
// Driver code
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);
bestFit(blockSize, m, processSize, n);
return 0 ;
}
Java
Python3
C#
// Java implementation of Best - Fit algorithm public class GFG{ // Method to allocate memory to blocks as per Best fit // algorithm static void bestFit(int blockSize[], int m, int processSize[], int n) { // Stores block id of the block allocated to a // process int allocation[] = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.length; i++) allocation[i] = -1; // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int bestIdx = -1; for (int j=0; j<m; j++) { if (blockSize[j] >= processSize[i]) { if (bestIdx == -1) bestIdx = j; else if (blockSize[bestIdx] > blockSize[j]) bestIdx = j; } } // If we could find a block for current process if (bestIdx != -1) { // allocate block j to p[i] process allocation[i] = bestIdx; // Reduce available memory in this block. blockSize[bestIdx] -= processSize[i]; } } System.out.println("\nProcess No.\tProcess Size\tBlock no."); for (int i = 0; i < n; i++) { System.out.print(" " + (i+1) + "\t\t" + processSize[i] + "\t\t"); if (allocation[i] != -1) System.out.print(allocation[i] + 1); else System.out.print("Not Allocated"); System.out.println(); } } // Driver Method public static void main(String[] args) { int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = blockSize.length; int n = processSize.length; bestFit(blockSize, m, processSize, n); }}
# Python3 implementation of Best - Fit algorithm # Function to allocate memory to blocks# as per Best fit algorithmdef bestFit(blockSize, m, processSize, n): # Stores block id of the block # allocated to a process allocation = [-1] * n # pick each process and find suitable # blocks according to its size ad # assign to it for i in range(n): # Find the best fit block for # current process bestIdx = -1 for j in range(m): if blockSize[j] >= processSize[i]: if bestIdx == -1: bestIdx = j else if blockSize[bestIdx] > blockSize[j]: bestIdx = j # If we could find a block for # current process if bestIdx != -1: # allocate block j to p[i] process allocation[i] = bestIdx # Reduce available memory in this block. blockSize[bestIdx] -= processSize[i] print("Process No. Process Size Block no.") for i in range(n): print(i + 1, " ", processSize[i], end = " ") if allocation[i] != -1: print(allocation[i] + 1) else: print("Not Allocated") # Driver codeif __name__ == '__main__': blockSize = [100, 500, 200, 300, 600] processSize = [212, 417, 112, 426] m = len(blockSize) n = len(processSize) bestFit(blockSize, m, processSize, n) # This code is contributed by PranchalK
// C# implementation of Best - Fit algorithmusing System; public class GFG { // Method to allocate memory to blocks // as per Best fit // algorithm static void bestFit(int []blockSize, int m, int []processSize, int n) { // Stores block id of the block // allocated to a process int []allocation = new int[n]; // Initially no block is assigned to // any process for (int i = 0; i < allocation.Length; i++) allocation[i] = -1; // pick each process and find suitable // blocks according to its size ad // assign to it for (int i = 0; i < n; i++) { // Find the best fit block for // current process int bestIdx = -1; for (int j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { if (bestIdx == -1) bestIdx = j; else if (blockSize[bestIdx] > blockSize[j]) bestIdx = j; } } // If we could find a block for // current process if (bestIdx != -1) { // allocate block j to p[i] // process allocation[i] = bestIdx; // Reduce available memory in // this block. blockSize[bestIdx] -= processSize[i]; } } Console.WriteLine("\nProcess No.\tProcess" + " Size\tBlock no."); for (int i = 0; i < n; i++) { Console.Write(" " + (i+1) + "\t\t" + processSize[i] + "\t\t"); if (allocation[i] != -1) Console.Write(allocation[i] + 1); else Console.Write("Not Allocated"); Console.WriteLine(); } } // Driver Method public static void Main() { int []blockSize = {100, 500, 200, 300, 600}; int []processSize = {212, 417, 112, 426}; int m = blockSize.Length; int n = processSize.Length; bestFit(blockSize, m, processSize, n); }} // This code is contributed by nitin mittal.
Output:
Process No. Process Size Block no.
1 212 4
2 417 2
3 112 3
4 426 5
Is Best-Fit really best? Although, best fit minimizes the wastage space, it consumes a lot of processor time for searching the block which is close to required size. Also, Best-fit may perform poorer than other algorithms in some cases. For example, see below exercise.Example: Consider the requests from processes in given order 300K, 25K, 125K and 50K. Let there be two blocks of memory available of size 150K followed by a block size 350K.Best Fit: 300K is allocated from block of size 350K. 50 is left in the block. 25K is allocated from the remaining 50K block. 25K is left in the block. 125K is allocated from 150 K block. 25K is left in this block also. 50K can’t be allocated even if there is 25K + 25K space available.First Fit: 300K request is allocated from 350K block, 50K is left out. 25K is be allocated from 150K block, 125K is left out. Then 125K and 50K are allocated to remaining left out partitions. So, first fit can handle requests.
Best Fit algorithm in Memory Management | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersBest Fit algorithm in Memory Management | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=TQSVMBsK1kk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
PranchalKatiyar
surinderdawra388
memory-management
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Policemen catch thieves
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Minimum Number of Platforms Required for a Railway/Bus Station
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Difference between Prim's and Kruskal's algorithm for MST | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Prerequisite : Partition allocation methodsBest fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions. Example: "
},
{
"code": null,
"e": 470,
"s": 232,
"text": "Input : blockSize[] = {100, 500, 200, 300, 600};\n processSize[] = {212, 417, 112, 426};\nOutput:\nProcess No. Process Size Block no.\n 1 212 4\n 2 417 2\n 3 112 3\n 4 426 5"
},
{
"code": null,
"e": 485,
"s": 476,
"text": "Chapters"
},
{
"code": null,
"e": 512,
"s": 485,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 562,
"s": 512,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 585,
"s": 562,
"text": "captions off, selected"
},
{
"code": null,
"e": 593,
"s": 585,
"text": "English"
},
{
"code": null,
"e": 617,
"s": 593,
"text": "This is a modal window."
},
{
"code": null,
"e": 686,
"s": 617,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 708,
"s": 686,
"text": "End of dialog window."
},
{
"code": null,
"e": 1147,
"s": 708,
"text": "Implementation:\n1- Input memory blocks and processes with sizes.\n2- Initialize all memory blocks as free.\n3- Start by picking each process and find the\n minimum block size that can be assigned to\n current process i.e., find min(bockSize[1], \n blockSize[2],.....blockSize[n]) > \n processSize[current], if found then assign \n it to the current process.\n5- If not then leave that process and keep checking\n the further processes."
},
{
"code": null,
"e": 1173,
"s": 1147,
"text": "Below is implementation. "
},
{
"code": null,
"e": 1179,
"s": 1173,
"text": "C/C++"
},
{
"code": null,
"e": 3008,
"s": 1179,
"text": "\n// C++ implementation of Best - Fit algorithm\n#include<bits/stdc++.h>\nusing namespace std;\n\n// Function to allocate memory to blocks as per Best fit\n// algorithm\nvoid bestFit(int blockSize[], int m, int processSize[], int n)\n{\n // Stores block id of the block allocated to a\n // process\n int allocation[n];\n\n // Initially no block is assigned to any process\n memset(allocation, -1, sizeof(allocation));\n\n // pick each process and find suitable blocks\n // according to its size ad assign to it\n for (int i=0; i<n; i++)\n {\n // Find the best fit block for current process\n int bestIdx = -1;\n for (int j=0; j<m; j++)\n {\n if (blockSize[j] >= processSize[i])\n {\n if (bestIdx == -1)\n bestIdx = j;\n else if (blockSize[bestIdx] > blockSize[j])\n bestIdx = j;\n }\n }\n\n // If we could find a block for current process\n if (bestIdx != -1)\n {\n // allocate block j to p[i] process\n allocation[i] = bestIdx;\n\n // Reduce available memory in this block.\n blockSize[bestIdx] -= processSize[i];\n }\n }\n\n cout << \"\\nProcess No.\\tProcess Size\\tBlock no.\\n\";\n for (int i = 0; i < n; i++)\n {\n cout << \" \" << i+1 << \"\\t\\t\" << processSize[i] << \"\\t\\t\";\n if (allocation[i] != -1)\n cout << allocation[i] + 1;\n else\n cout << \"Not Allocated\";\n cout << endl;\n }\n}\n\n// Driver code\nint main()\n{\n int blockSize[] = {100, 500, 200, 300, 600};\n int processSize[] = {212, 417, 112, 426};\n int m = sizeof(blockSize)/sizeof(blockSize[0]);\n int n = sizeof(processSize)/sizeof(processSize[0]);\n\n bestFit(blockSize, m, processSize, n);\n\n return 0 ;\n}\n"
},
{
"code": null,
"e": 3013,
"s": 3008,
"text": "Java"
},
{
"code": null,
"e": 3021,
"s": 3013,
"text": "Python3"
},
{
"code": null,
"e": 3024,
"s": 3021,
"text": "C#"
},
{
"code": "// Java implementation of Best - Fit algorithm public class GFG{ // Method to allocate memory to blocks as per Best fit // algorithm static void bestFit(int blockSize[], int m, int processSize[], int n) { // Stores block id of the block allocated to a // process int allocation[] = new int[n]; // Initially no block is assigned to any process for (int i = 0; i < allocation.length; i++) allocation[i] = -1; // pick each process and find suitable blocks // according to its size ad assign to it for (int i=0; i<n; i++) { // Find the best fit block for current process int bestIdx = -1; for (int j=0; j<m; j++) { if (blockSize[j] >= processSize[i]) { if (bestIdx == -1) bestIdx = j; else if (blockSize[bestIdx] > blockSize[j]) bestIdx = j; } } // If we could find a block for current process if (bestIdx != -1) { // allocate block j to p[i] process allocation[i] = bestIdx; // Reduce available memory in this block. blockSize[bestIdx] -= processSize[i]; } } System.out.println(\"\\nProcess No.\\tProcess Size\\tBlock no.\"); for (int i = 0; i < n; i++) { System.out.print(\" \" + (i+1) + \"\\t\\t\" + processSize[i] + \"\\t\\t\"); if (allocation[i] != -1) System.out.print(allocation[i] + 1); else System.out.print(\"Not Allocated\"); System.out.println(); } } // Driver Method public static void main(String[] args) { int blockSize[] = {100, 500, 200, 300, 600}; int processSize[] = {212, 417, 112, 426}; int m = blockSize.length; int n = processSize.length; bestFit(blockSize, m, processSize, n); }}",
"e": 5141,
"s": 3024,
"text": null
},
{
"code": "# Python3 implementation of Best - Fit algorithm # Function to allocate memory to blocks# as per Best fit algorithmdef bestFit(blockSize, m, processSize, n): # Stores block id of the block # allocated to a process allocation = [-1] * n # pick each process and find suitable # blocks according to its size ad # assign to it for i in range(n): # Find the best fit block for # current process bestIdx = -1 for j in range(m): if blockSize[j] >= processSize[i]: if bestIdx == -1: bestIdx = j else if blockSize[bestIdx] > blockSize[j]: bestIdx = j # If we could find a block for # current process if bestIdx != -1: # allocate block j to p[i] process allocation[i] = bestIdx # Reduce available memory in this block. blockSize[bestIdx] -= processSize[i] print(\"Process No. Process Size Block no.\") for i in range(n): print(i + 1, \" \", processSize[i], end = \" \") if allocation[i] != -1: print(allocation[i] + 1) else: print(\"Not Allocated\") # Driver codeif __name__ == '__main__': blockSize = [100, 500, 200, 300, 600] processSize = [212, 417, 112, 426] m = len(blockSize) n = len(processSize) bestFit(blockSize, m, processSize, n) # This code is contributed by PranchalK",
"e": 6652,
"s": 5141,
"text": null
},
{
"code": "// C# implementation of Best - Fit algorithmusing System; public class GFG { // Method to allocate memory to blocks // as per Best fit // algorithm static void bestFit(int []blockSize, int m, int []processSize, int n) { // Stores block id of the block // allocated to a process int []allocation = new int[n]; // Initially no block is assigned to // any process for (int i = 0; i < allocation.Length; i++) allocation[i] = -1; // pick each process and find suitable // blocks according to its size ad // assign to it for (int i = 0; i < n; i++) { // Find the best fit block for // current process int bestIdx = -1; for (int j = 0; j < m; j++) { if (blockSize[j] >= processSize[i]) { if (bestIdx == -1) bestIdx = j; else if (blockSize[bestIdx] > blockSize[j]) bestIdx = j; } } // If we could find a block for // current process if (bestIdx != -1) { // allocate block j to p[i] // process allocation[i] = bestIdx; // Reduce available memory in // this block. blockSize[bestIdx] -= processSize[i]; } } Console.WriteLine(\"\\nProcess No.\\tProcess\" + \" Size\\tBlock no.\"); for (int i = 0; i < n; i++) { Console.Write(\" \" + (i+1) + \"\\t\\t\" + processSize[i] + \"\\t\\t\"); if (allocation[i] != -1) Console.Write(allocation[i] + 1); else Console.Write(\"Not Allocated\"); Console.WriteLine(); } } // Driver Method public static void Main() { int []blockSize = {100, 500, 200, 300, 600}; int []processSize = {212, 417, 112, 426}; int m = blockSize.Length; int n = processSize.Length; bestFit(blockSize, m, processSize, n); }} // This code is contributed by nitin mittal.",
"e": 9022,
"s": 6652,
"text": null
},
{
"code": null,
"e": 9032,
"s": 9022,
"text": "Output: "
},
{
"code": null,
"e": 9165,
"s": 9032,
"text": "Process No. Process Size Block no.\n 1 212 4\n 2 417 2\n 3 112 3\n 4 426 5"
},
{
"code": null,
"e": 10120,
"s": 9165,
"text": "Is Best-Fit really best? Although, best fit minimizes the wastage space, it consumes a lot of processor time for searching the block which is close to required size. Also, Best-fit may perform poorer than other algorithms in some cases. For example, see below exercise.Example: Consider the requests from processes in given order 300K, 25K, 125K and 50K. Let there be two blocks of memory available of size 150K followed by a block size 350K.Best Fit: 300K is allocated from block of size 350K. 50 is left in the block. 25K is allocated from the remaining 50K block. 25K is left in the block. 125K is allocated from 150 K block. 25K is left in this block also. 50K can’t be allocated even if there is 25K + 25K space available.First Fit: 300K request is allocated from 350K block, 50K is left out. 25K is be allocated from 150K block, 125K is left out. Then 125K and 50K are allocated to remaining left out partitions. So, first fit can handle requests. "
},
{
"code": null,
"e": 11016,
"s": 10120,
"text": "Best Fit algorithm in Memory Management | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersBest Fit algorithm in Memory Management | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=TQSVMBsK1kk\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 11438,
"s": 11016,
"text": "This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11451,
"s": 11438,
"text": "nitin mittal"
},
{
"code": null,
"e": 11467,
"s": 11451,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 11484,
"s": 11467,
"text": "surinderdawra388"
},
{
"code": null,
"e": 11502,
"s": 11484,
"text": "memory-management"
},
{
"code": null,
"e": 11509,
"s": 11502,
"text": "Greedy"
},
{
"code": null,
"e": 11516,
"s": 11509,
"text": "Greedy"
},
{
"code": null,
"e": 11614,
"s": 11516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11645,
"s": 11614,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 11664,
"s": 11645,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 11707,
"s": 11664,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 11735,
"s": 11707,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 11758,
"s": 11735,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 11782,
"s": 11758,
"text": "Policemen catch thieves"
},
{
"code": null,
"e": 11863,
"s": 11782,
"text": "Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)"
},
{
"code": null,
"e": 11926,
"s": 11863,
"text": "Minimum Number of Platforms Required for a Railway/Bus Station"
},
{
"code": null,
"e": 11997,
"s": 11926,
"text": "Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8"
}
]
|
How to Merge all excel files in a folder using Python? | 16 May, 2021
In this article, we will see how to combine all Excel files present in a folder into a single file.
The python libraries used are:
Pandas: Pandas is a python library developed for a python programming language for manipulating data and analyzing the data. It is widely used in Data Science and Data analytics.
Glob: The glob module matches all the pathnames matching a specified pattern according to rules used by Unix Shell.
Three Excel files will be used which will be combined into a single Excel file in a folder using python. The three Excel files are x1.xlsx, x2.xlsx, and x3.xlsx:
Firstly we have to import libraries and modules
Python3
# importing pandas libraries and # glob moduleimport pandas as pdimport glob
Setting the path of the folder where files are stored. This line of code will fetch the folder where the files are stored.
Python3
# path of the folderpath = r'test'
Displaying the names of files in the folder using Glob module. glob.glob( ) function will search for all the files in the given path with .xlsx extension. print(filenames) displays the names of all the files with xlsx extension.
Python3
# reading all the excel filesfilenames = glob.glob(path + "\*.xlsx")print('File names:', filenames)
Initializing Empty data frames. A Data Frame is a Table data structure in python for analyzing and manipulating the data. Here we have to initialize an empty data frame for storing the combined data in the three files
Python3
# Initializing empty data framefinalexcelsheet = pd.DataFrame()
Iterating through all the files in the folder one by one. We have to iterate through each file using for loop. The pd.concat() function will concatenate all the multiple sheets present in the excel files as in the case of the third excel file in this example and will store in a variable called df. finalexcelsheet.append( ) function will append the data present in df variable into finalexcelsheet one by one. Hence with this piece of code, you will be able to combine the Excel files with ease
Python3
# to iterate excel file one by one # inside the folderfor file in filenames: # combining multiple excel worksheets # into single data frames df = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index=True, sort=False) # Appending excel files one by one finalexcelsheet = finalexcelsheet.append( df, ignore_index=True)
Displaying the combined data. To display the combined file just write print(finalexcelsheet).
Python3
# to print the combined dataprint('Final Sheet:')display(finalexcelsheet)
Insert the combined data into a new Excel file.
Python3
# save combined datafinalexcelsheet.to_excel(r'Final.xlsx',index=False)
Below is the complete python program based on the above approach:
Python3
#import modulesimport pandas as pdimport glob # path of the folderpath = r'test' # reading all the excel filesfilenames = glob.glob(path + "\*.xlsx")print('File names:', filenames) # initializing empty data framefinalexcelsheet = pd.DataFrame() # to iterate excel file one by one # inside the folderfor file in filenames: # combining multiple excel worksheets # into single data frames df = pd.concat(pd.read_excel( file, sheet_name=None), ignore_index=True, sort=False) # appending excel files one by one finalexcelsheet = finalexcelsheet.append( df, ignore_index=True) # to print the combined dataprint('Final Sheet:')display(finalexcelsheet) finalexcelsheet.to_excel(r'Final.xlsx', index=False)
Output:
Final Excel:
Picked
Python-excel
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 128,
"s": 28,
"text": "In this article, we will see how to combine all Excel files present in a folder into a single file."
},
{
"code": null,
"e": 159,
"s": 128,
"text": "The python libraries used are:"
},
{
"code": null,
"e": 338,
"s": 159,
"text": "Pandas: Pandas is a python library developed for a python programming language for manipulating data and analyzing the data. It is widely used in Data Science and Data analytics."
},
{
"code": null,
"e": 454,
"s": 338,
"text": "Glob: The glob module matches all the pathnames matching a specified pattern according to rules used by Unix Shell."
},
{
"code": null,
"e": 616,
"s": 454,
"text": "Three Excel files will be used which will be combined into a single Excel file in a folder using python. The three Excel files are x1.xlsx, x2.xlsx, and x3.xlsx:"
},
{
"code": null,
"e": 664,
"s": 616,
"text": "Firstly we have to import libraries and modules"
},
{
"code": null,
"e": 672,
"s": 664,
"text": "Python3"
},
{
"code": "# importing pandas libraries and # glob moduleimport pandas as pdimport glob",
"e": 749,
"s": 672,
"text": null
},
{
"code": null,
"e": 872,
"s": 749,
"text": "Setting the path of the folder where files are stored. This line of code will fetch the folder where the files are stored."
},
{
"code": null,
"e": 880,
"s": 872,
"text": "Python3"
},
{
"code": "# path of the folderpath = r'test'",
"e": 915,
"s": 880,
"text": null
},
{
"code": null,
"e": 1144,
"s": 915,
"text": "Displaying the names of files in the folder using Glob module. glob.glob( ) function will search for all the files in the given path with .xlsx extension. print(filenames) displays the names of all the files with xlsx extension."
},
{
"code": null,
"e": 1152,
"s": 1144,
"text": "Python3"
},
{
"code": "# reading all the excel filesfilenames = glob.glob(path + \"\\*.xlsx\")print('File names:', filenames)",
"e": 1252,
"s": 1152,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1252,
"text": "Initializing Empty data frames. A Data Frame is a Table data structure in python for analyzing and manipulating the data. Here we have to initialize an empty data frame for storing the combined data in the three files"
},
{
"code": null,
"e": 1478,
"s": 1470,
"text": "Python3"
},
{
"code": "# Initializing empty data framefinalexcelsheet = pd.DataFrame()",
"e": 1542,
"s": 1478,
"text": null
},
{
"code": null,
"e": 2040,
"s": 1542,
"text": "Iterating through all the files in the folder one by one. We have to iterate through each file using for loop. The pd.concat() function will concatenate all the multiple sheets present in the excel files as in the case of the third excel file in this example and will store in a variable called df. finalexcelsheet.append( ) function will append the data present in df variable into finalexcelsheet one by one. Hence with this piece of code, you will be able to combine the Excel files with ease"
},
{
"code": null,
"e": 2048,
"s": 2040,
"text": "Python3"
},
{
"code": "# to iterate excel file one by one # inside the folderfor file in filenames: # combining multiple excel worksheets # into single data frames df = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index=True, sort=False) # Appending excel files one by one finalexcelsheet = finalexcelsheet.append( df, ignore_index=True)",
"e": 2420,
"s": 2048,
"text": null
},
{
"code": null,
"e": 2514,
"s": 2420,
"text": "Displaying the combined data. To display the combined file just write print(finalexcelsheet)."
},
{
"code": null,
"e": 2522,
"s": 2514,
"text": "Python3"
},
{
"code": "# to print the combined dataprint('Final Sheet:')display(finalexcelsheet)",
"e": 2596,
"s": 2522,
"text": null
},
{
"code": null,
"e": 2644,
"s": 2596,
"text": "Insert the combined data into a new Excel file."
},
{
"code": null,
"e": 2652,
"s": 2644,
"text": "Python3"
},
{
"code": "# save combined datafinalexcelsheet.to_excel(r'Final.xlsx',index=False)",
"e": 2724,
"s": 2652,
"text": null
},
{
"code": null,
"e": 2790,
"s": 2724,
"text": "Below is the complete python program based on the above approach:"
},
{
"code": null,
"e": 2798,
"s": 2790,
"text": "Python3"
},
{
"code": "#import modulesimport pandas as pdimport glob # path of the folderpath = r'test' # reading all the excel filesfilenames = glob.glob(path + \"\\*.xlsx\")print('File names:', filenames) # initializing empty data framefinalexcelsheet = pd.DataFrame() # to iterate excel file one by one # inside the folderfor file in filenames: # combining multiple excel worksheets # into single data frames df = pd.concat(pd.read_excel( file, sheet_name=None), ignore_index=True, sort=False) # appending excel files one by one finalexcelsheet = finalexcelsheet.append( df, ignore_index=True) # to print the combined dataprint('Final Sheet:')display(finalexcelsheet) finalexcelsheet.to_excel(r'Final.xlsx', index=False)",
"e": 3531,
"s": 2798,
"text": null
},
{
"code": null,
"e": 3539,
"s": 3531,
"text": "Output:"
},
{
"code": null,
"e": 3552,
"s": 3539,
"text": "Final Excel:"
},
{
"code": null,
"e": 3559,
"s": 3552,
"text": "Picked"
},
{
"code": null,
"e": 3572,
"s": 3559,
"text": "Python-excel"
},
{
"code": null,
"e": 3586,
"s": 3572,
"text": "Python-pandas"
},
{
"code": null,
"e": 3593,
"s": 3586,
"text": "Python"
}
]
|
MoviePy – Inserting Text in the Video | 30 Aug, 2020
In this article we will see how we can insert text to a video clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. VideoClip is the base class for all the other video clips in MoviePy. In order to do this we need to have ImageMagick installed else it will not work. Adding text to a video is similar to creating composite video.
In order to do so we have to do the following :1. Import the moviepy module2. Load the video file3. Create a text clip and set its position and duration4. Create a composite video clip using video file and the text clip.5. Show the final video.
Below is the implementation
# Import everything needed to edit video clips from moviepy.editor import * # loading video dsa gfg intro video clip = VideoFileClip("dsa_geek.mp4") # clipping of the video # getting video for only starting 10 seconds clip = clip.subclip(0, 10) # Reduce the audio volume (volume x 0.8) clip = clip.volumex(0.8) # Generate a text clip txt_clip = TextClip("GeeksforGeeks", fontsize = 75, color = 'black') # setting position of text in the center and duration will be 10 seconds txt_clip = txt_clip.set_pos('center').set_duration(10) # Overlay the text clip on the first video clip video = CompositeVideoClip([clip, txt_clip]) # showing video video.ipython_display(width = 280)
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Another example
# Import everything needed to edit video clips from moviepy.editor import * # loading video file clipclip = VideoFileClip("geeks.mp4") # clipping of the video # getting video for only starting 10 seconds clip = clip.subclip(0, 5) # Reduce the audio volume (volume x 0.5) clip = clip.volumex(0.5) # Generate a text clip txt_clip = TextClip("GfG-MoviePy", fontsize = 75, color = 'green') # setting position of text in the center and duration will be 5 seconds txt_clip = txt_clip.set_pos('bottom').set_duration(5) # Overlay the text clip on the first video clip video = CompositeVideoClip([clip, txt_clip]) # showing video video.ipython_display(width = 280)
Moviepy - Building video __temp__.mp4.
Moviepy - Writing video __temp__.mp4
Moviepy - Done !
Moviepy - video ready __temp__.mp4
Python-MoviePy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Aug, 2020"
},
{
"code": null,
"e": 531,
"s": 28,
"text": "In this article we will see how we can insert text to a video clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. VideoClip is the base class for all the other video clips in MoviePy. In order to do this we need to have ImageMagick installed else it will not work. Adding text to a video is similar to creating composite video."
},
{
"code": null,
"e": 776,
"s": 531,
"text": "In order to do so we have to do the following :1. Import the moviepy module2. Load the video file3. Create a text clip and set its position and duration4. Create a composite video clip using video file and the text clip.5. Show the final video."
},
{
"code": null,
"e": 804,
"s": 776,
"text": "Below is the implementation"
},
{
"code": "# Import everything needed to edit video clips from moviepy.editor import * # loading video dsa gfg intro video clip = VideoFileClip(\"dsa_geek.mp4\") # clipping of the video # getting video for only starting 10 seconds clip = clip.subclip(0, 10) # Reduce the audio volume (volume x 0.8) clip = clip.volumex(0.8) # Generate a text clip txt_clip = TextClip(\"GeeksforGeeks\", fontsize = 75, color = 'black') # setting position of text in the center and duration will be 10 seconds txt_clip = txt_clip.set_pos('center').set_duration(10) # Overlay the text clip on the first video clip video = CompositeVideoClip([clip, txt_clip]) # showing video video.ipython_display(width = 280) ",
"e": 1508,
"s": 804,
"text": null
},
{
"code": null,
"e": 1758,
"s": 1508,
"text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n"
},
{
"code": null,
"e": 1774,
"s": 1758,
"text": "Another example"
},
{
"code": "# Import everything needed to edit video clips from moviepy.editor import * # loading video file clipclip = VideoFileClip(\"geeks.mp4\") # clipping of the video # getting video for only starting 10 seconds clip = clip.subclip(0, 5) # Reduce the audio volume (volume x 0.5) clip = clip.volumex(0.5) # Generate a text clip txt_clip = TextClip(\"GfG-MoviePy\", fontsize = 75, color = 'green') # setting position of text in the center and duration will be 5 seconds txt_clip = txt_clip.set_pos('bottom').set_duration(5) # Overlay the text clip on the first video clip video = CompositeVideoClip([clip, txt_clip]) # showing video video.ipython_display(width = 280) ",
"e": 2459,
"s": 1774,
"text": null
},
{
"code": null,
"e": 2709,
"s": 2459,
"text": "Moviepy - Building video __temp__.mp4.\nMoviepy - Writing video __temp__.mp4\n\n \nMoviepy - Done !\nMoviepy - video ready __temp__.mp4\n"
},
{
"code": null,
"e": 2724,
"s": 2709,
"text": "Python-MoviePy"
},
{
"code": null,
"e": 2731,
"s": 2724,
"text": "Python"
},
{
"code": null,
"e": 2829,
"s": 2731,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2847,
"s": 2829,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2889,
"s": 2847,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2911,
"s": 2889,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2937,
"s": 2911,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2969,
"s": 2937,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2998,
"s": 2969,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3025,
"s": 2998,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3046,
"s": 3025,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3069,
"s": 3046,
"text": "Introduction To PYTHON"
}
]
|
C program to create hard link and soft link - GeeksforGeeks | 30 Nov, 2021
There are two types of links, i.e., a soft link and a hard link to a file. C library has a function link() that creates a new hard link to an existing file. The function symlink() to create a soft link. If the link file/path already exists, it will not be overwritten. Both function link() and symlink() return 0 on success. If any error occurs, then -1 is returned. Otherwise, ‘errno’ (Error Number) is set appropriately.
Soft Link: A soft link (also known as a Symbolic link) acts as a pointer or a reference to the file name. It does not access the data available in the original file. If the earlier file is deleted, the soft link will point to a file that does not exist anymore.
Hard Link: A hard link acts as a copy (mirrored) of the selected file. It accesses the data available in the original file.If the earlier selected file is deleted, the hard link to the file will still contain the data of that file.
Function to create a Hard Link:
L = link(FILE1, FILE2), creates a hard link named FILE2 to an existing FILE1.
where, L is the value returned by the link() function.
Function to create a Soft Link:
sL = symlink(FILE1, FILE2), creates a soft link named FILE2 to an existing FILE1.
where, sL is the value returned by the symlink() function
Program 1: Below is the C program to create a hard link to an existing file:
C
// C program to create an Hard Link// to the existing file#include <stdio.h>#include <stdlib.h>#include <unistd.h> // Driver Codeint main(int argc, char* argv[]){ // Link function int l = link(argv[1], argv[2]); // argv[1] is existing file name // argv[2] is link file name if (l == 0) { printf("Hard Link created" " succuessfuly"); } return 0;}
Output:
Program 2: Below is the C program to create a Soft link to an existing file:
C
// C program to create an Soft Link// to the existing file#include <stdio.h>#include <stdlib.h>#include <unistd.h> // Driver Codeint main(int argc, char* argv[]){ // Symlink function int sl = symlink(argv[1], argv[2]); // argv[1] is existing file name // argv[2] is soft link file name if (sl == 0) { printf("Soft Link created" " succuessfuly"); } return 0;}
Output:
madeng5555
File Handling
C Language
C Programs
File Handling
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
UDP Server-Client implementation in C
Header files in C/C++ and its uses | [
{
"code": null,
"e": 23817,
"s": 23789,
"text": "\n30 Nov, 2021"
},
{
"code": null,
"e": 24240,
"s": 23817,
"text": "There are two types of links, i.e., a soft link and a hard link to a file. C library has a function link() that creates a new hard link to an existing file. The function symlink() to create a soft link. If the link file/path already exists, it will not be overwritten. Both function link() and symlink() return 0 on success. If any error occurs, then -1 is returned. Otherwise, ‘errno’ (Error Number) is set appropriately."
},
{
"code": null,
"e": 24502,
"s": 24240,
"text": "Soft Link: A soft link (also known as a Symbolic link) acts as a pointer or a reference to the file name. It does not access the data available in the original file. If the earlier file is deleted, the soft link will point to a file that does not exist anymore."
},
{
"code": null,
"e": 24734,
"s": 24502,
"text": "Hard Link: A hard link acts as a copy (mirrored) of the selected file. It accesses the data available in the original file.If the earlier selected file is deleted, the hard link to the file will still contain the data of that file."
},
{
"code": null,
"e": 24766,
"s": 24734,
"text": "Function to create a Hard Link:"
},
{
"code": null,
"e": 24844,
"s": 24766,
"text": "L = link(FILE1, FILE2), creates a hard link named FILE2 to an existing FILE1."
},
{
"code": null,
"e": 24899,
"s": 24844,
"text": "where, L is the value returned by the link() function."
},
{
"code": null,
"e": 24931,
"s": 24899,
"text": "Function to create a Soft Link:"
},
{
"code": null,
"e": 25013,
"s": 24931,
"text": "sL = symlink(FILE1, FILE2), creates a soft link named FILE2 to an existing FILE1."
},
{
"code": null,
"e": 25071,
"s": 25013,
"text": "where, sL is the value returned by the symlink() function"
},
{
"code": null,
"e": 25148,
"s": 25071,
"text": "Program 1: Below is the C program to create a hard link to an existing file:"
},
{
"code": null,
"e": 25150,
"s": 25148,
"text": "C"
},
{
"code": "// C program to create an Hard Link// to the existing file#include <stdio.h>#include <stdlib.h>#include <unistd.h> // Driver Codeint main(int argc, char* argv[]){ // Link function int l = link(argv[1], argv[2]); // argv[1] is existing file name // argv[2] is link file name if (l == 0) { printf(\"Hard Link created\" \" succuessfuly\"); } return 0;}",
"e": 25543,
"s": 25150,
"text": null
},
{
"code": null,
"e": 25551,
"s": 25543,
"text": "Output:"
},
{
"code": null,
"e": 25628,
"s": 25551,
"text": "Program 2: Below is the C program to create a Soft link to an existing file:"
},
{
"code": null,
"e": 25630,
"s": 25628,
"text": "C"
},
{
"code": "// C program to create an Soft Link// to the existing file#include <stdio.h>#include <stdlib.h>#include <unistd.h> // Driver Codeint main(int argc, char* argv[]){ // Symlink function int sl = symlink(argv[1], argv[2]); // argv[1] is existing file name // argv[2] is soft link file name if (sl == 0) { printf(\"Soft Link created\" \" succuessfuly\"); } return 0;}",
"e": 26036,
"s": 25630,
"text": null
},
{
"code": null,
"e": 26044,
"s": 26036,
"text": "Output:"
},
{
"code": null,
"e": 26055,
"s": 26044,
"text": "madeng5555"
},
{
"code": null,
"e": 26069,
"s": 26055,
"text": "File Handling"
},
{
"code": null,
"e": 26080,
"s": 26069,
"text": "C Language"
},
{
"code": null,
"e": 26091,
"s": 26080,
"text": "C Programs"
},
{
"code": null,
"e": 26105,
"s": 26091,
"text": "File Handling"
},
{
"code": null,
"e": 26203,
"s": 26105,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26212,
"s": 26203,
"text": "Comments"
},
{
"code": null,
"e": 26225,
"s": 26212,
"text": "Old Comments"
},
{
"code": null,
"e": 26263,
"s": 26225,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26289,
"s": 26263,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 26309,
"s": 26289,
"text": "Multithreading in C"
},
{
"code": null,
"e": 26331,
"s": 26309,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 26372,
"s": 26331,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26385,
"s": 26372,
"text": "Strings in C"
},
{
"code": null,
"e": 26426,
"s": 26385,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 26467,
"s": 26426,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 26505,
"s": 26467,
"text": "UDP Server-Client implementation in C"
}
]
|
DC.js - Legend | Legend is an attachable screen customization. It can be added to other DC charts to render horizontal legend labels. This chapter explains about legend in detail.
Legend supports the following important methods. Let us go through each one of them in detail.
This method is used to set an automatic width for legend items on or off. If true, itemWidth is ignored. It is defined below −
legend.autoItemWidth = function (width) {
if (!arguments.length) {
return _width;
}
}
This method is used to set or get a gap between the legend items. It is defined as follows −
legend.gap = function (gap) {
if (!arguments.length) {
return _gap;
}
}
This method is used to position the legend horizontally and is defined as follows.
_legend.horizontal = function (h) {
if (!arguments.length) {
return _h;
}
};
This method is used to set or get the legend item height.
legend.itemHeight = function (itemHeight) {
if (!arguments.length) {
return _itemHeight;
}
};
This method is used to set or get the legend the item width for a horizontal legend.
_legend.itemWidth = function (itemWidth) {
if (!arguments.length) {
return _itemWidth;
}
};
This method is used to set or get the legend text function. The legend widget uses this function to render the legend text for each item. If no function is specified, the legend widget will display the names associated with each group. A simple example is shown below −
legend.legendText(dc.pluck('name'))
This method is used to display the maximum number of legend items.
It is used to set or get the x-coordinate for a legend widget and is defined below −
legend.x = function (x) {
if (!arguments.length) {
return _x;
}
};
Similarly, you can also perform the y-coordinate.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2222,
"s": 2059,
"text": "Legend is an attachable screen customization. It can be added to other DC charts to render horizontal legend labels. This chapter explains about legend in detail."
},
{
"code": null,
"e": 2317,
"s": 2222,
"text": "Legend supports the following important methods. Let us go through each one of them in detail."
},
{
"code": null,
"e": 2444,
"s": 2317,
"text": "This method is used to set an automatic width for legend items on or off. If true, itemWidth is ignored. It is defined below −"
},
{
"code": null,
"e": 2542,
"s": 2444,
"text": "legend.autoItemWidth = function (width) {\n if (!arguments.length) {\n return _width;\n }\n}"
},
{
"code": null,
"e": 2635,
"s": 2542,
"text": "This method is used to set or get a gap between the legend items. It is defined as follows −"
},
{
"code": null,
"e": 2719,
"s": 2635,
"text": "legend.gap = function (gap) {\n if (!arguments.length) {\n return _gap;\n }\n}"
},
{
"code": null,
"e": 2802,
"s": 2719,
"text": "This method is used to position the legend horizontally and is defined as follows."
},
{
"code": null,
"e": 2891,
"s": 2802,
"text": "_legend.horizontal = function (h) {\n if (!arguments.length) {\n return _h;\n }\n};"
},
{
"code": null,
"e": 2949,
"s": 2891,
"text": "This method is used to set or get the legend item height."
},
{
"code": null,
"e": 3055,
"s": 2949,
"text": "legend.itemHeight = function (itemHeight) {\n if (!arguments.length) {\n return _itemHeight;\n }\n};"
},
{
"code": null,
"e": 3140,
"s": 3055,
"text": "This method is used to set or get the legend the item width for a horizontal legend."
},
{
"code": null,
"e": 3244,
"s": 3140,
"text": "_legend.itemWidth = function (itemWidth) {\n if (!arguments.length) {\n return _itemWidth;\n }\n};"
},
{
"code": null,
"e": 3514,
"s": 3244,
"text": "This method is used to set or get the legend text function. The legend widget uses this function to render the legend text for each item. If no function is specified, the legend widget will display the names associated with each group. A simple example is shown below −"
},
{
"code": null,
"e": 3550,
"s": 3514,
"text": "legend.legendText(dc.pluck('name'))"
},
{
"code": null,
"e": 3617,
"s": 3550,
"text": "This method is used to display the maximum number of legend items."
},
{
"code": null,
"e": 3702,
"s": 3617,
"text": "It is used to set or get the x-coordinate for a legend widget and is defined below −"
},
{
"code": null,
"e": 3781,
"s": 3702,
"text": "legend.x = function (x) {\n if (!arguments.length) {\n return _x;\n }\n};"
},
{
"code": null,
"e": 3831,
"s": 3781,
"text": "Similarly, you can also perform the y-coordinate."
},
{
"code": null,
"e": 3838,
"s": 3831,
"text": " Print"
},
{
"code": null,
"e": 3849,
"s": 3838,
"text": " Add Notes"
}
]
|
Hibernate session differences between load() and get() - 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
Differences between load() and get() method is one of the most popular interview question in hibernate. Irrespective of experience or fresher, every person will face this question in telephonic or face to face interview.
Not only the interview point of view, in order to understanding the internals of hibernate everybody should aware of the differences between load() and get() methods.
In order to get the details from the database in hibernate, we can call either load() or get() method. By using the load() or get() method we can load (read) the data from the database.
The load and get methods are both looking like a same, and also these two are generates same output. But the functionality wise there are few differences in internally.
In this tutorial we will discuss all possible differences between load() and get() methods with examples.
Before going to discuss about the differences directly, It is mandatory to know what exactly are the load and get methods and how they are working internally.
In order to get the details from the database, we can use the load() method. The load is a instance method which is coming from the hibernate Session object. We can call the load() with two parameters.
session.load(Class class, Serializable id);
session.load(String classname, Serializable id);
By using the above two methods we can load the data from the database. When ever the load() method is called, the hibernate creates a proxy object of a POJO class (provided as parameter), and it will set the id to the proxy object, then it returns the proxy object to the program. Based on the operations performed on the proxy object, the hibernate will decide whether to go cache or database to load the data. This process is called lazy loading. When we access non-id property (not a primary key) of proxy object then hibernate first goes to first level cache and if that object doesn’t available in the cache then hibernate goes to database for loading an object.
Example: Student.java
package com.onlinetutorialspoint.pojo;
public class Student implements java.io.Serializable {
private Integer id;
private String name;
private Integer rollNumber;
public Student() {
}
public Student(Integer id, String name, Integer rollNumber) {
this.id = id;
this.name = name;
this.rollNumber = rollNumber;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRollNumber() {
return this.rollNumber;
}
public void setRollNumber(Integer rollNumber) {
this.rollNumber = rollNumber;
}
}
Creating Mapping File Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Jun 10, 2015 11:42:29 AM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
<class catalog="onlinetutorialspoint" name="com.onlinetutorialspoint.pojo.Student" table="student">
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="identity"/>
</id>
<property name="name" type="string">
<column length="50" name="name"/>
</property>
<property name="rollNumber" type="java.lang.Integer">
<column name="rollnumber"/>
</property>
</class>
</hibernate-mapping>
Create a Main class DbOperations.java
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbOperations {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Object o = session.load(Student.class, 101);
Student s = (Student) o;
// For getting the Id property hibernate will not go to Cache or Database.
// It will take from the Proxy.
System.out.println("StudentId : " + s.getId());
// As name is a non-id property, hibernate first checks in cache,
// If the value doesn't found in the cache then it will go to data base and fetch the values
System.out.println("Student Name : " + s.getName());
}
}
Output :
If we observe the output, after printing the StudentId (Id Property) hibernate insert statements will be executed. Hence while loading the load() method hibernate will create the proxy object and assigned id to that proxy.
When ever we ask for id property it will take from the proxy only, this process is called as lazy loading. If we ask for non-id properties, then it will goto first level of cache or Database. If the corresponding Object is not found in the database, it returns (load() method) ObjectNotFoundException. Example :
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbOperations {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Object o = session.load(Student.class, 102);
Student s = (Student) o;
// For getting the Id property hibernate will not go to Cache or Database.
// It will take from the Proxy.
System.out.println("StudentId : " + s.getId());
// As name is a non-id property, hibernate first checks in cache,
// If the value doesn't found in the cache then it will go to data base and fetch the values, If // it doesn't exist even in database throws ObjectNotFoundException
System.out.println("Student Name : " + s.getName());
}
}
Output :
Like wise load() method, in order to get the details from the database we can use the get() method as well. We can call the get() method with two parameters.
session.get(Class class,Serializable id);
session.get(String className,Serializable id);
session.get(Class class,Serializable id);
session.get(String className,Serializable id);
When we call the get() method, then hibernate first goes to first level cache and if that object doesn’t exist in the first level cache then it goes to database and loads the object from database. If Id doesn’t exist in the database, then get() method returns null. When get() method is called no proxy object is created, hence it is called as early loading.
Example :
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbOperations {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Object o = session.get(Student.class, 101);
}
}
Output :
On the above example, we didn’t do any operations on the “o”. We didn’t even type cast it, but the hibernate directly went to database and get the details from the database and stored the details in first level cache.
If we use the object “o” the details are getting from the cache.
Example :
package com.onlinetutorialspoint.service;
import com.onlinetutorialspoint.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DbOperations {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
Session session = factory.openSession();
Object o = session.get(Student.class, 101);
Student student = (Student) o;
System.out.println("Student Id : " + student.getId());
System.out.println("Student Name : " + student.getName());
System.out.println("Student rollNumber : " + student.getRollNumber());
}
}
Output :
When calling the load() method hibernate creates an proxy object and returns the proxy object, but in the case of get() method there is no concept called proxy it directly hit the database.
load() method loads an object lazily, where as get() method loads an object early.
performance point of view load() method is recommended when compared to get() method.
If the given id doesn’t exist the load() method throws ObjectNotFoundException, where as get() methods returns null.
When calling the load() method hibernate creates an proxy object and returns the proxy object, but in the case of get() method there is no concept called proxy it directly hit the database.
load() method loads an object lazily, where as get() method loads an object early.
performance point of view load() method is recommended when compared to get() method.
If the given id doesn’t exist the load() method throws ObjectNotFoundException, where as get() methods returns null.
Happy Learning 🙂
sessionget() Example with Maven
File size: 29 KB
Downloads: 785
Hibernate cache first level example
Difference between update vs merge in Hibernate example
hibernate update query example
Different types of Object States in Hibernate
Top 7 Interview Questions in Hibernate
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Hibernate Filter Example Xml Configuration
Hibernate Composite Key Mapping Example
Generator Classes in Hibernate
Top 10 Advantages of Hibernate
Basic Hibernate Example with XML Configuration
Singleton Hibernate SessionFactory Example
Hibernate Projection with Example
Hibernate Interceptor Example
Hibernate cache first level example
Difference between update vs merge in Hibernate example
hibernate update query example
Different types of Object States in Hibernate
Top 7 Interview Questions in Hibernate
hbm2ddl.auto Example in Hibernate XML Config
Hibernate Native SQL Query Example
Hibernate Filter Example Xml Configuration
Hibernate Composite Key Mapping Example
Generator Classes in Hibernate
Top 10 Advantages of Hibernate
Basic Hibernate Example with XML Configuration
Singleton Hibernate SessionFactory Example
Hibernate Projection with Example
Hibernate Interceptor Example
raviteja
March 20, 2018 at 4:06 am - Reply
in getCurrentSession of session object load it works or not?
raviteja
March 20, 2018 at 4:07 am - Reply
get and load methods can check the l2 or sechond level cache or not?
raviteja
March 20, 2018 at 4:06 am - Reply
in getCurrentSession of session object load it works or not?
in getCurrentSession of session object load it works or not?
raviteja
March 20, 2018 at 4:07 am - Reply
get and load methods can check the l2 or sechond level cache or not?
get and load methods can check the l2 or sechond level cache or not?
Δ
Hibernate – Introduction
Hibernate – Advantages
Hibernate – Download and Setup
Hibernate – Sql Dialect list
Hibernate – Helloworld – XML
Hibernate – Install Tools in Eclipse
Hibernate – Object States
Hibernate – Helloworld – Annotations
Hibernate – One to One Mapping – XML
Hibernate – One to One Mapping foreign key – XML
Hibernate – One To Many -XML
Hibernate – One To Many – Annotations
Hibernate – Many to Many Mapping – XML
Hibernate – Many to One – XML
Hibernate – Composite Key Mapping
Hibernate – Named Query
Hibernate – Native SQL Query
Hibernate – load() vs get()
Hibernate Criteria API with Example
Hibernate – Restrictions
Hibernate – Projection
Hibernate – Query Language (HQL)
Hibernate – Groupby Criteria HQL
Hibernate – Orderby Criteria
Hibernate – HQLSelect Operation
Hibernate – HQL Update, Delete
Hibernate – Update Query
Hibernate – Update vs Merge
Hibernate – Right Join
Hibernate – Left Join
Hibernate – Pagination
Hibernate – Generator Classes
Hibernate – Custom Generator
Hibernate – Inheritance Mappings
Hibernate – Table per Class
Hibernate – Table per Sub Class
Hibernate – Table per Concrete Class
Hibernate – Table per Class Annotations
Hibernate – Stored Procedures
Hibernate – @Formula Annotation
Hibernate – Singleton SessionFactory
Hibernate – Interceptor
hbm2ddl.auto Example in Hibernate XML Config
Hibernate – First Level Cache | [
{
"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": 619,
"s": 398,
"text": "Differences between load() and get() method is one of the most popular interview question in hibernate. Irrespective of experience or fresher, every person will face this question in telephonic or face to face interview."
},
{
"code": null,
"e": 786,
"s": 619,
"text": "Not only the interview point of view, in order to understanding the internals of hibernate everybody should aware of the differences between load() and get() methods."
},
{
"code": null,
"e": 972,
"s": 786,
"text": "In order to get the details from the database in hibernate, we can call either load() or get() method. By using the load() or get() method we can load (read) the data from the database."
},
{
"code": null,
"e": 1141,
"s": 972,
"text": "The load and get methods are both looking like a same, and also these two are generates same output. But the functionality wise there are few differences in internally."
},
{
"code": null,
"e": 1247,
"s": 1141,
"text": "In this tutorial we will discuss all possible differences between load() and get() methods with examples."
},
{
"code": null,
"e": 1406,
"s": 1247,
"text": "Before going to discuss about the differences directly, It is mandatory to know what exactly are the load and get methods and how they are working internally."
},
{
"code": null,
"e": 1608,
"s": 1406,
"text": "In order to get the details from the database, we can use the load() method. The load is a instance method which is coming from the hibernate Session object. We can call the load() with two parameters."
},
{
"code": null,
"e": 1652,
"s": 1608,
"text": "session.load(Class class, Serializable id);"
},
{
"code": null,
"e": 1701,
"s": 1652,
"text": "session.load(String classname, Serializable id);"
},
{
"code": null,
"e": 2369,
"s": 1701,
"text": "By using the above two methods we can load the data from the database. When ever the load() method is called, the hibernate creates a proxy object of a POJO class (provided as parameter), and it will set the id to the proxy object, then it returns the proxy object to the program. Based on the operations performed on the proxy object, the hibernate will decide whether to go cache or database to load the data. This process is called lazy loading. When we access non-id property (not a primary key) of proxy object then hibernate first goes to first level cache and if that object doesn’t available in the cache then hibernate goes to database for loading an object."
},
{
"code": null,
"e": 2391,
"s": 2369,
"text": "Example: Student.java"
},
{
"code": null,
"e": 3194,
"s": 2391,
"text": "package com.onlinetutorialspoint.pojo;\n\npublic class Student implements java.io.Serializable {\n\n private Integer id;\n private String name;\n private Integer rollNumber;\n\n public Student() {\n }\n\n public Student(Integer id, String name, Integer rollNumber) {\n this.id = id;\n this.name = name;\n this.rollNumber = rollNumber;\n }\n\n public Integer getId() {\n return this.id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getRollNumber() {\n return this.rollNumber;\n }\n\n public void setRollNumber(Integer rollNumber) {\n this.rollNumber = rollNumber;\n }\n\n}\n"
},
{
"code": null,
"e": 3232,
"s": 3194,
"text": "Creating Mapping File Student.hbm.xml"
},
{
"code": null,
"e": 3954,
"s": 3232,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd\">\n<!-- Generated Jun 10, 2015 11:42:29 AM by Hibernate Tools 3.6.0 -->\n<hibernate-mapping>\n <class catalog=\"onlinetutorialspoint\" name=\"com.onlinetutorialspoint.pojo.Student\" table=\"student\">\n <id name=\"id\" type=\"java.lang.Integer\">\n <column name=\"id\"/>\n <generator class=\"identity\"/>\n </id>\n <property name=\"name\" type=\"string\">\n <column length=\"50\" name=\"name\"/>\n </property>\n <property name=\"rollNumber\" type=\"java.lang.Integer\">\n <column name=\"rollnumber\"/>\n </property>\n </class>\n</hibernate-mapping>\n"
},
{
"code": null,
"e": 3992,
"s": 3954,
"text": "Create a Main class DbOperations.java"
},
{
"code": null,
"e": 5007,
"s": 3992,
"text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class DbOperations {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n Object o = session.load(Student.class, 101);\n Student s = (Student) o;\n// For getting the Id property hibernate will not go to Cache or Database.\n// It will take from the Proxy.\n System.out.println(\"StudentId : \" + s.getId());\n\n// As name is a non-id property, hibernate first checks in cache,\n// If the value doesn't found in the cache then it will go to data base and fetch the values\n System.out.println(\"Student Name : \" + s.getName());\n\n }\n}\n"
},
{
"code": null,
"e": 5016,
"s": 5007,
"text": "Output :"
},
{
"code": null,
"e": 5240,
"s": 5016,
"text": "If we observe the output, after printing the StudentId (Id Property) hibernate insert statements will be executed. Hence while loading the load() method hibernate will create the proxy object and assigned id to that proxy."
},
{
"code": null,
"e": 5552,
"s": 5240,
"text": "When ever we ask for id property it will take from the proxy only, this process is called as lazy loading. If we ask for non-id properties, then it will goto first level of cache or Database. If the corresponding Object is not found in the database, it returns (load() method) ObjectNotFoundException. Example :"
},
{
"code": null,
"e": 6648,
"s": 5552,
"text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class DbOperations {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n Object o = session.load(Student.class, 102);\n Student s = (Student) o;\n// For getting the Id property hibernate will not go to Cache or Database.\n// It will take from the Proxy.\n System.out.println(\"StudentId : \" + s.getId());\n\n// As name is a non-id property, hibernate first checks in cache,\n// If the value doesn't found in the cache then it will go to data base and fetch the values, If // it doesn't exist even in database throws ObjectNotFoundException\n System.out.println(\"Student Name : \" + s.getName());\n\n }\n}\n\n"
},
{
"code": null,
"e": 6657,
"s": 6648,
"text": "Output :"
},
{
"code": null,
"e": 6815,
"s": 6657,
"text": "Like wise load() method, in order to get the details from the database we can use the get() method as well. We can call the get() method with two parameters."
},
{
"code": null,
"e": 6906,
"s": 6815,
"text": "\nsession.get(Class class,Serializable id);\nsession.get(String className,Serializable id);\n"
},
{
"code": null,
"e": 6948,
"s": 6906,
"text": "session.get(Class class,Serializable id);"
},
{
"code": null,
"e": 6995,
"s": 6948,
"text": "session.get(String className,Serializable id);"
},
{
"code": null,
"e": 7354,
"s": 6995,
"text": "When we call the get() method, then hibernate first goes to first level cache and if that object doesn’t exist in the first level cache then it goes to database and loads the object from database. If Id doesn’t exist in the database, then get() method returns null. When get() method is called no proxy object is created, hence it is called as early loading."
},
{
"code": null,
"e": 7364,
"s": 7354,
"text": "Example :"
},
{
"code": null,
"e": 7929,
"s": 7364,
"text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class DbOperations {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n Object o = session.get(Student.class, 101);\n }\n}\n\n"
},
{
"code": null,
"e": 7938,
"s": 7929,
"text": "Output :"
},
{
"code": null,
"e": 8156,
"s": 7938,
"text": "On the above example, we didn’t do any operations on the “o”. We didn’t even type cast it, but the hibernate directly went to database and get the details from the database and stored the details in first level cache."
},
{
"code": null,
"e": 8221,
"s": 8156,
"text": "If we use the object “o” the details are getting from the cache."
},
{
"code": null,
"e": 8231,
"s": 8221,
"text": "Example :"
},
{
"code": null,
"e": 9044,
"s": 8231,
"text": "package com.onlinetutorialspoint.service;\n\nimport com.onlinetutorialspoint.pojo.Student;\nimport org.hibernate.Session;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.cfg.Configuration;\n\npublic class DbOperations {\n\n public static void main(String[] args) {\n Configuration configuration = new Configuration();\n configuration.configure(\"hibernate.cfg.xml\");\n SessionFactory factory = configuration.buildSessionFactory();\n Session session = factory.openSession();\n Object o = session.get(Student.class, 101);\n Student student = (Student) o;\n System.out.println(\"Student Id : \" + student.getId());\n System.out.println(\"Student Name : \" + student.getName());\n System.out.println(\"Student rollNumber : \" + student.getRollNumber());\n }\n}\n\n"
},
{
"code": null,
"e": 9053,
"s": 9044,
"text": "Output :"
},
{
"code": null,
"e": 9533,
"s": 9053,
"text": "\n When calling the load() method hibernate creates an proxy object and returns the proxy object, but in the case of get() method there is no concept called proxy it directly hit the database.\nload() method loads an object lazily, where as get() method loads an object early.\nperformance point of view load() method is recommended when compared to get() method.\nIf the given id doesn’t exist the load() method throws ObjectNotFoundException, where as get() methods returns null.\n"
},
{
"code": null,
"e": 9725,
"s": 9533,
"text": " When calling the load() method hibernate creates an proxy object and returns the proxy object, but in the case of get() method there is no concept called proxy it directly hit the database."
},
{
"code": null,
"e": 9808,
"s": 9725,
"text": "load() method loads an object lazily, where as get() method loads an object early."
},
{
"code": null,
"e": 9894,
"s": 9808,
"text": "performance point of view load() method is recommended when compared to get() method."
},
{
"code": null,
"e": 10011,
"s": 9894,
"text": "If the given id doesn’t exist the load() method throws ObjectNotFoundException, where as get() methods returns null."
},
{
"code": null,
"e": 10028,
"s": 10011,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 10096,
"s": 10028,
"text": "\n\nsessionget() Example with Maven\n\nFile size: 29 KB\nDownloads: 785\n"
},
{
"code": null,
"e": 10685,
"s": 10096,
"text": "\nHibernate cache first level example\nDifference between update vs merge in Hibernate example\nhibernate update query example\nDifferent types of Object States in Hibernate\nTop 7 Interview Questions in Hibernate\nhbm2ddl.auto Example in Hibernate XML Config\nHibernate Native SQL Query Example\nHibernate Filter Example Xml Configuration\nHibernate Composite Key Mapping Example\nGenerator Classes in Hibernate\nTop 10 Advantages of Hibernate\nBasic Hibernate Example with XML Configuration\nSingleton Hibernate SessionFactory Example\nHibernate Projection with Example\nHibernate Interceptor Example\n"
},
{
"code": null,
"e": 10721,
"s": 10685,
"text": "Hibernate cache first level example"
},
{
"code": null,
"e": 10777,
"s": 10721,
"text": "Difference between update vs merge in Hibernate example"
},
{
"code": null,
"e": 10808,
"s": 10777,
"text": "hibernate update query example"
},
{
"code": null,
"e": 10854,
"s": 10808,
"text": "Different types of Object States in Hibernate"
},
{
"code": null,
"e": 10893,
"s": 10854,
"text": "Top 7 Interview Questions in Hibernate"
},
{
"code": null,
"e": 10938,
"s": 10893,
"text": "hbm2ddl.auto Example in Hibernate XML Config"
},
{
"code": null,
"e": 10973,
"s": 10938,
"text": "Hibernate Native SQL Query Example"
},
{
"code": null,
"e": 11016,
"s": 10973,
"text": "Hibernate Filter Example Xml Configuration"
},
{
"code": null,
"e": 11056,
"s": 11016,
"text": "Hibernate Composite Key Mapping Example"
},
{
"code": null,
"e": 11087,
"s": 11056,
"text": "Generator Classes in Hibernate"
},
{
"code": null,
"e": 11118,
"s": 11087,
"text": "Top 10 Advantages of Hibernate"
},
{
"code": null,
"e": 11165,
"s": 11118,
"text": "Basic Hibernate Example with XML Configuration"
},
{
"code": null,
"e": 11208,
"s": 11165,
"text": "Singleton Hibernate SessionFactory Example"
},
{
"code": null,
"e": 11242,
"s": 11208,
"text": "Hibernate Projection with Example"
},
{
"code": null,
"e": 11272,
"s": 11242,
"text": "Hibernate Interceptor Example"
},
{
"code": null,
"e": 11512,
"s": 11272,
"text": "\n\n\n\n\n\nraviteja\nMarch 20, 2018 at 4:06 am - Reply \n\nin getCurrentSession of session object load it works or not?\n\n\n\n\n\n\n\n\n\nraviteja\nMarch 20, 2018 at 4:07 am - Reply \n\nget and load methods can check the l2 or sechond level cache or not?\n\n\n\n\n"
},
{
"code": null,
"e": 11627,
"s": 11512,
"text": "\n\n\n\n\nraviteja\nMarch 20, 2018 at 4:06 am - Reply \n\nin getCurrentSession of session object load it works or not?\n\n\n\n"
},
{
"code": null,
"e": 11688,
"s": 11627,
"text": "in getCurrentSession of session object load it works or not?"
},
{
"code": null,
"e": 11811,
"s": 11688,
"text": "\n\n\n\n\nraviteja\nMarch 20, 2018 at 4:07 am - Reply \n\nget and load methods can check the l2 or sechond level cache or not?\n\n\n\n"
},
{
"code": null,
"e": 11880,
"s": 11811,
"text": "get and load methods can check the l2 or sechond level cache or not?"
},
{
"code": null,
"e": 11886,
"s": 11884,
"text": "Δ"
},
{
"code": null,
"e": 11912,
"s": 11886,
"text": " Hibernate – Introduction"
},
{
"code": null,
"e": 11936,
"s": 11912,
"text": " Hibernate – Advantages"
},
{
"code": null,
"e": 11968,
"s": 11936,
"text": " Hibernate – Download and Setup"
},
{
"code": null,
"e": 11998,
"s": 11968,
"text": " Hibernate – Sql Dialect list"
},
{
"code": null,
"e": 12028,
"s": 11998,
"text": " Hibernate – Helloworld – XML"
},
{
"code": null,
"e": 12066,
"s": 12028,
"text": " Hibernate – Install Tools in Eclipse"
},
{
"code": null,
"e": 12093,
"s": 12066,
"text": " Hibernate – Object States"
},
{
"code": null,
"e": 12131,
"s": 12093,
"text": " Hibernate – Helloworld – Annotations"
},
{
"code": null,
"e": 12169,
"s": 12131,
"text": " Hibernate – One to One Mapping – XML"
},
{
"code": null,
"e": 12219,
"s": 12169,
"text": " Hibernate – One to One Mapping foreign key – XML"
},
{
"code": null,
"e": 12249,
"s": 12219,
"text": " Hibernate – One To Many -XML"
},
{
"code": null,
"e": 12288,
"s": 12249,
"text": " Hibernate – One To Many – Annotations"
},
{
"code": null,
"e": 12328,
"s": 12288,
"text": " Hibernate – Many to Many Mapping – XML"
},
{
"code": null,
"e": 12359,
"s": 12328,
"text": " Hibernate – Many to One – XML"
},
{
"code": null,
"e": 12394,
"s": 12359,
"text": " Hibernate – Composite Key Mapping"
},
{
"code": null,
"e": 12419,
"s": 12394,
"text": " Hibernate – Named Query"
},
{
"code": null,
"e": 12449,
"s": 12419,
"text": " Hibernate – Native SQL Query"
},
{
"code": null,
"e": 12478,
"s": 12449,
"text": " Hibernate – load() vs get()"
},
{
"code": null,
"e": 12515,
"s": 12478,
"text": " Hibernate Criteria API with Example"
},
{
"code": null,
"e": 12541,
"s": 12515,
"text": " Hibernate – Restrictions"
},
{
"code": null,
"e": 12565,
"s": 12541,
"text": " Hibernate – Projection"
},
{
"code": null,
"e": 12599,
"s": 12565,
"text": " Hibernate – Query Language (HQL)"
},
{
"code": null,
"e": 12633,
"s": 12599,
"text": " Hibernate – Groupby Criteria HQL"
},
{
"code": null,
"e": 12663,
"s": 12633,
"text": " Hibernate – Orderby Criteria"
},
{
"code": null,
"e": 12696,
"s": 12663,
"text": " Hibernate – HQLSelect Operation"
},
{
"code": null,
"e": 12728,
"s": 12696,
"text": " Hibernate – HQL Update, Delete"
},
{
"code": null,
"e": 12754,
"s": 12728,
"text": " Hibernate – Update Query"
},
{
"code": null,
"e": 12783,
"s": 12754,
"text": " Hibernate – Update vs Merge"
},
{
"code": null,
"e": 12807,
"s": 12783,
"text": " Hibernate – Right Join"
},
{
"code": null,
"e": 12830,
"s": 12807,
"text": " Hibernate – Left Join"
},
{
"code": null,
"e": 12854,
"s": 12830,
"text": " Hibernate – Pagination"
},
{
"code": null,
"e": 12885,
"s": 12854,
"text": " Hibernate – Generator Classes"
},
{
"code": null,
"e": 12915,
"s": 12885,
"text": " Hibernate – Custom Generator"
},
{
"code": null,
"e": 12949,
"s": 12915,
"text": " Hibernate – Inheritance Mappings"
},
{
"code": null,
"e": 12978,
"s": 12949,
"text": " Hibernate – Table per Class"
},
{
"code": null,
"e": 13011,
"s": 12978,
"text": " Hibernate – Table per Sub Class"
},
{
"code": null,
"e": 13049,
"s": 13011,
"text": " Hibernate – Table per Concrete Class"
},
{
"code": null,
"e": 13091,
"s": 13049,
"text": " Hibernate – Table per Class Annotations"
},
{
"code": null,
"e": 13122,
"s": 13091,
"text": " Hibernate – Stored Procedures"
},
{
"code": null,
"e": 13155,
"s": 13122,
"text": " Hibernate – @Formula Annotation"
},
{
"code": null,
"e": 13193,
"s": 13155,
"text": " Hibernate – Singleton SessionFactory"
},
{
"code": null,
"e": 13218,
"s": 13193,
"text": " Hibernate – Interceptor"
},
{
"code": null,
"e": 13264,
"s": 13218,
"text": " hbm2ddl.auto Example in Hibernate XML Config"
}
]
|
Swift - If Statement | An if statement consists of a Boolean expression followed by one or more statements.
The syntax of an if statement in Swift 4 is as follows −
if boolean_expression {
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.
var varA:Int = 10;
/* Check the boolean condition using if statement */
if varA < 20 {
/* If condition is true then print the following */
print("varA is less than 20");
}
print("Value of variable varA is \(varA)");
When we run the above program using playground, we get the following result.
varA is less than 20
Value of variable varA is 10
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2338,
"s": 2253,
"text": "An if statement consists of a Boolean expression followed by one or more statements."
},
{
"code": null,
"e": 2395,
"s": 2338,
"text": "The syntax of an if statement in Swift 4 is as follows −"
},
{
"code": null,
"e": 2491,
"s": 2395,
"text": "if boolean_expression {\n /* statement(s) will execute if the boolean expression is true */\n}\n"
},
{
"code": null,
"e": 2754,
"s": 2491,
"text": "If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed."
},
{
"code": null,
"e": 2978,
"s": 2754,
"text": "var varA:Int = 10;\n\n/* Check the boolean condition using if statement */\nif varA < 20 {\n /* If condition is true then print the following */\n print(\"varA is less than 20\");\n}\n\nprint(\"Value of variable varA is \\(varA)\");"
},
{
"code": null,
"e": 3055,
"s": 2978,
"text": "When we run the above program using playground, we get the following result."
},
{
"code": null,
"e": 3106,
"s": 3055,
"text": "varA is less than 20\nValue of variable varA is 10\n"
},
{
"code": null,
"e": 3139,
"s": 3106,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3154,
"s": 3139,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 3187,
"s": 3154,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3206,
"s": 3187,
"text": " Three Millennials"
},
{
"code": null,
"e": 3238,
"s": 3206,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3257,
"s": 3238,
"text": " Three Millennials"
},
{
"code": null,
"e": 3290,
"s": 3257,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3307,
"s": 3290,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3339,
"s": 3307,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 3359,
"s": 3339,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 3394,
"s": 3359,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3411,
"s": 3394,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 3418,
"s": 3411,
"text": " Print"
},
{
"code": null,
"e": 3429,
"s": 3418,
"text": " Add Notes"
}
]
|
Tryit Editor v3.6 - Show Python | f = open("demofile.txt", "r") | []
|
Image Processing with Python — Application of Fourier Transformation | by Tonichi Edeza | Towards Data Science | One of the more advanced topics in image processing has to do with the concept of Fourier Transformation. Put very briefly, some images contain systematic noise that users may want to remove. If such noise is regular enough, employing Fourier Transformation adjustments may aid in image processing. In this article we shall see exactly how to do this.
Let us begin.
As always, start by importing the required Python libraries.
import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imread, imshowfrom skimage.color import rgb2hsv, rgb2gray, rgb2yuvfrom skimage import color, exposure, transformfrom skimage.exposure import equalize_hist
First let us load the image we will use for this article.
dark_image = imread('against_the_light.png')
The image we will be using is the one above. It as image of a street taken when the sun was facing directly at the camera. For this simple exercise we shall try to find a way to eliminate (or least drastically reduce) the powerlines in the back.
As a start, let us convert our image into greyscale.
dark_image_grey = rgb2gray(dark_image)plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(dark_image_grey, cmap='gray');
Excellent, from here we can now easily use the fft function found in Skimage.
dark_image_grey_fourier = np.fft.fftshift(np.fft.fft2(dark_image_grey))plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(np.log(abs(dark_image_grey_fourier)), cmap='gray');
In the image we can see two very clear distortions. The white vertical and horizontal lines refer to the sharp horizontal and vertical elements of the image. Let us see what happens if we mask one of them.
def fourier_masker_ver(image, i): f_size = 15 dark_image_grey_fourier = np.fft.fftshift(np.fft.fft2(rgb2gray(image))) dark_image_grey_fourier[:225, 235:240] = i dark_image_grey_fourier[-225:,235:240] = i fig, ax = plt.subplots(1,3,figsize=(15,15)) ax[0].imshow(np.log(abs(dark_image_grey_fourier)), cmap='gray') ax[0].set_title('Masked Fourier', fontsize = f_size) ax[1].imshow(rgb2gray(image), cmap = 'gray') ax[1].set_title('Greyscale Image', fontsize = f_size); ax[2].imshow(abs(np.fft.ifft2(dark_image_grey_fourier)), cmap='gray') ax[2].set_title('Transformed Greyscale Image', fontsize = f_size); fourier_masker(dark_image, 1)
We can see that the horizontal power cables have significantly reduced in size. As an interesting experiment, let us see what would happen if we masked the horizontal line instead.
def fourier_masker_hor(image, i): f_size = 15 dark_image_grey_fourier = np.fft.fftshift(np.fft.fft2(rgb2gray(image))) dark_image_grey_fourier[235:240, :230] = i dark_image_grey_fourier[235:240,-230:] = i fig, ax = plt.subplots(1,3,figsize=(15,15)) ax[0].imshow(np.log(abs(dark_image_grey_fourier)), cmap='gray') ax[0].set_title('Masked Fourier', fontsize = f_size) ax[1].imshow(rgb2gray(image), cmap = 'gray') ax[1].set_title('Greyscale Image', fontsize = f_size); ax[2].imshow(abs(np.fft.ifft2(dark_image_grey_fourier)), cmap='gray') ax[2].set_title('Transformed Greyscale Image', fontsize = f_size);fourier_masker_hor(dark_image, 1)
We can see that all the vertical aspects of the image have been smudged. This is highly noticeable in the electric poles. Though helpful in some settings, this is clearly not helpful in this here.
Though we will stick to masking the Fourier Transformation’s vertical line (again remember that when converted back into the original image this smudges the horizontal lines), let us experiment with different degrees of masking.
def fourier_iterator(image, value_list): for i in value_list: fourier_masker_ver(image, i) fourier_iterator(dark_image, [0.001, 1, 100])
We can see that decreasing the value has almost no effect on the original image, however increasing the value seems to darken original image. As there is practically no difference between the smaller value and 1, let us stick to 1 for simplicity.
Finally, let us enact Fourier Transformation adjustment while retaining the colors of the original image.
def fourier_transform_rgb(image): f_size = 25 transformed_channels = [] for i in range(3): rgb_fft = np.fft.fftshift(np.fft.fft2((image[:, :, i]))) rgb_fft[:225, 235:237] = 1 rgb_fft[-225:,235:237] = 1 transformed_channels.append(abs(np.fft.ifft2(rgb_fft))) final_image = np.dstack([transformed_channels[0].astype(int), transformed_channels[1].astype(int), transformed_channels[2].astype(int)]) fig, ax = plt.subplots(1, 2, figsize=(17,12)) ax[0].imshow(image) ax[0].set_title('Original Image', fontsize = f_size) ax[0].set_axis_off() ax[1].imshow(final_image) ax[1].set_title('Transformed Image', fontsize = f_size) ax[1].set_axis_off() fig.tight_layout()
We can see that the horizontal power cables have been greatly reduced while the rest of the image remains mostly intact. This showcases how we can make subtle changes to an image via Fourier Transformation.
In Summary
Fourier Transformation is a powerful tool that can be quite useful for data scientists working with images. In future articles we shall go over how to apply the technique in much more impactful ways. For now, I hope you were able to get a basic grasp of the subject. | [
{
"code": null,
"e": 524,
"s": 172,
"text": "One of the more advanced topics in image processing has to do with the concept of Fourier Transformation. Put very briefly, some images contain systematic noise that users may want to remove. If such noise is regular enough, employing Fourier Transformation adjustments may aid in image processing. In this article we shall see exactly how to do this."
},
{
"code": null,
"e": 538,
"s": 524,
"text": "Let us begin."
},
{
"code": null,
"e": 599,
"s": 538,
"text": "As always, start by importing the required Python libraries."
},
{
"code": null,
"e": 826,
"s": 599,
"text": "import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imread, imshowfrom skimage.color import rgb2hsv, rgb2gray, rgb2yuvfrom skimage import color, exposure, transformfrom skimage.exposure import equalize_hist"
},
{
"code": null,
"e": 884,
"s": 826,
"text": "First let us load the image we will use for this article."
},
{
"code": null,
"e": 929,
"s": 884,
"text": "dark_image = imread('against_the_light.png')"
},
{
"code": null,
"e": 1175,
"s": 929,
"text": "The image we will be using is the one above. It as image of a street taken when the sun was facing directly at the camera. For this simple exercise we shall try to find a way to eliminate (or least drastically reduce) the powerlines in the back."
},
{
"code": null,
"e": 1228,
"s": 1175,
"text": "As a start, let us convert our image into greyscale."
},
{
"code": null,
"e": 1352,
"s": 1228,
"text": "dark_image_grey = rgb2gray(dark_image)plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(dark_image_grey, cmap='gray');"
},
{
"code": null,
"e": 1430,
"s": 1352,
"text": "Excellent, from here we can now easily use the fft function found in Skimage."
},
{
"code": null,
"e": 1608,
"s": 1430,
"text": "dark_image_grey_fourier = np.fft.fftshift(np.fft.fft2(dark_image_grey))plt.figure(num=None, figsize=(8, 6), dpi=80)plt.imshow(np.log(abs(dark_image_grey_fourier)), cmap='gray');"
},
{
"code": null,
"e": 1814,
"s": 1608,
"text": "In the image we can see two very clear distortions. The white vertical and horizontal lines refer to the sharp horizontal and vertical elements of the image. Let us see what happens if we mask one of them."
},
{
"code": null,
"e": 2527,
"s": 1814,
"text": "def fourier_masker_ver(image, i): f_size = 15 dark_image_grey_fourier = np.fft.fftshift(np.fft.fft2(rgb2gray(image))) dark_image_grey_fourier[:225, 235:240] = i dark_image_grey_fourier[-225:,235:240] = i fig, ax = plt.subplots(1,3,figsize=(15,15)) ax[0].imshow(np.log(abs(dark_image_grey_fourier)), cmap='gray') ax[0].set_title('Masked Fourier', fontsize = f_size) ax[1].imshow(rgb2gray(image), cmap = 'gray') ax[1].set_title('Greyscale Image', fontsize = f_size); ax[2].imshow(abs(np.fft.ifft2(dark_image_grey_fourier)), cmap='gray') ax[2].set_title('Transformed Greyscale Image', fontsize = f_size); fourier_masker(dark_image, 1)"
},
{
"code": null,
"e": 2708,
"s": 2527,
"text": "We can see that the horizontal power cables have significantly reduced in size. As an interesting experiment, let us see what would happen if we masked the horizontal line instead."
},
{
"code": null,
"e": 3421,
"s": 2708,
"text": "def fourier_masker_hor(image, i): f_size = 15 dark_image_grey_fourier = np.fft.fftshift(np.fft.fft2(rgb2gray(image))) dark_image_grey_fourier[235:240, :230] = i dark_image_grey_fourier[235:240,-230:] = i fig, ax = plt.subplots(1,3,figsize=(15,15)) ax[0].imshow(np.log(abs(dark_image_grey_fourier)), cmap='gray') ax[0].set_title('Masked Fourier', fontsize = f_size) ax[1].imshow(rgb2gray(image), cmap = 'gray') ax[1].set_title('Greyscale Image', fontsize = f_size); ax[2].imshow(abs(np.fft.ifft2(dark_image_grey_fourier)), cmap='gray') ax[2].set_title('Transformed Greyscale Image', fontsize = f_size);fourier_masker_hor(dark_image, 1)"
},
{
"code": null,
"e": 3618,
"s": 3421,
"text": "We can see that all the vertical aspects of the image have been smudged. This is highly noticeable in the electric poles. Though helpful in some settings, this is clearly not helpful in this here."
},
{
"code": null,
"e": 3847,
"s": 3618,
"text": "Though we will stick to masking the Fourier Transformation’s vertical line (again remember that when converted back into the original image this smudges the horizontal lines), let us experiment with different degrees of masking."
},
{
"code": null,
"e": 3994,
"s": 3847,
"text": "def fourier_iterator(image, value_list): for i in value_list: fourier_masker_ver(image, i) fourier_iterator(dark_image, [0.001, 1, 100])"
},
{
"code": null,
"e": 4241,
"s": 3994,
"text": "We can see that decreasing the value has almost no effect on the original image, however increasing the value seems to darken original image. As there is practically no difference between the smaller value and 1, let us stick to 1 for simplicity."
},
{
"code": null,
"e": 4347,
"s": 4241,
"text": "Finally, let us enact Fourier Transformation adjustment while retaining the colors of the original image."
},
{
"code": null,
"e": 5142,
"s": 4347,
"text": "def fourier_transform_rgb(image): f_size = 25 transformed_channels = [] for i in range(3): rgb_fft = np.fft.fftshift(np.fft.fft2((image[:, :, i]))) rgb_fft[:225, 235:237] = 1 rgb_fft[-225:,235:237] = 1 transformed_channels.append(abs(np.fft.ifft2(rgb_fft))) final_image = np.dstack([transformed_channels[0].astype(int), transformed_channels[1].astype(int), transformed_channels[2].astype(int)]) fig, ax = plt.subplots(1, 2, figsize=(17,12)) ax[0].imshow(image) ax[0].set_title('Original Image', fontsize = f_size) ax[0].set_axis_off() ax[1].imshow(final_image) ax[1].set_title('Transformed Image', fontsize = f_size) ax[1].set_axis_off() fig.tight_layout()"
},
{
"code": null,
"e": 5349,
"s": 5142,
"text": "We can see that the horizontal power cables have been greatly reduced while the rest of the image remains mostly intact. This showcases how we can make subtle changes to an image via Fourier Transformation."
},
{
"code": null,
"e": 5360,
"s": 5349,
"text": "In Summary"
}
]
|
How to send HTML email using Android App? | This example demonstrates about How to send HTML email using Android App.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp">
<Button
android:onClick="sendHtmlEmail"
android:text="Send HTML Email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendHtmlEmail(View view) {
String mailId = "[email protected]";
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", mailId, null));
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject text here");
emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml("<p><b>Some Content</b></p>" + "http://www.google.com" + "<small><p>More content</p></small>"));
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "This example demonstrates about How to send HTML email using Android App."
},
{
"code": null,
"e": 1265,
"s": 1136,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1330,
"s": 1265,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1748,
"s": 1330,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\">\n <Button\n android:onClick=\"sendHtmlEmail\"\n android:text=\"Send HTML Email\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1805,
"s": 1748,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2737,
"s": 1805,
"text": "package app.com.sample;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.text.Html;\nimport android.view.View;\nimport androidx.appcompat.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n public void sendHtmlEmail(View view) {\n String mailId = \"[email protected]\";\n Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(\"mailto\", mailId, null));\n emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, \"Subject text here\");\n emailIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(\"<p><b>Some Content</b></p>\" + \"http://www.google.com\" + \"<small><p>More content</p></small>\"));\n startActivity(Intent.createChooser(emailIntent, \"Send email...\"));\n }\n}"
},
{
"code": null,
"e": 2792,
"s": 2737,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3462,
"s": 2792,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3809,
"s": 3462,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3850,
"s": 3809,
"text": "Click here to download the project code."
}
]
|
Path Traversal Attack and Prevention - GeeksforGeeks | 07 Feb, 2018
A path traversal attack allows attackers to access directories that they should not be accessing, like config files or any other files/directories that may contains server’s data not intended for public.
Using a path traversal attack (also known as directory traversal), an attacker can access data stored outside the web root folder (typically /var/www/). By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files.
Let’s assume we have a website running on
http://www.mywebsite.com.
Let’s also suppose that the web server is vulnerable to path traversal attack. This allows an attacker to use special character sequences, like ../, which in Unix directories points to its parent directory, to traverse up the directory chain and access files outside of /var/www or config files like this.
A typical example of vulnerable application in PHP code is:
<?php$template = 'red.php';if (isset($_COOKIE['TEMPLATE'])) $template = $_COOKIE['TEMPLATE'];include ("/home/users/phpdemo/templates/" . $template);?>
Using the same ../ technique, an attacker can escape out of the directory containing the PDFs and access anything they want on the system.
http://www.mywebsite.com/?template= ../../../../../../../../../etc/passwd
PreventionA possible algorithm for preventing directory traversal would be to:
Giving appropriate permissions to directories and files. A PHP file typically runs as www-data user on Linux. We should not allow this user to access system files. But this doesn’t prevent this user from accessing web-application specific config files.
Process URI requests that do not result in a file request, e.g., executing a hook into user code, before continuing below.
When a URI request for a file/directory is to be made, build a full path to the file/directory if it exists, and normalize all characters (e.g., %20 converted to spaces).
It is assumed that a ‘Document Root’ fully qualified, normalized, path is known, and this string has a length N. Assume that no files outside this directory can be served.
Ensure that the first N characters of the fully qualified path to the requested file is exactly the same as the ‘Document Root’.
Using a hard-coded predefined file extension to suffix the path does not limit the scope of the attack to files of that file extension.
Sourceshttps://en.wikipedia.org/wiki/Directory_traversal_attackhttp://projects.webappsec.org/w/page/13246952/Path%20Traversalhttps://www.owasp.org/index.php/Path_Traversal
This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
secure-coding
Advanced Computer Subject
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Top 10 Front End Developer Skills That You Need in 2022
Socket Programming in C/C++
DSA Sheet by Love Babbar
Must Do Coding Questions for Product Based Companies | [
{
"code": null,
"e": 23837,
"s": 23809,
"text": "\n07 Feb, 2018"
},
{
"code": null,
"e": 24041,
"s": 23837,
"text": "A path traversal attack allows attackers to access directories that they should not be accessing, like config files or any other files/directories that may contains server’s data not intended for public."
},
{
"code": null,
"e": 24491,
"s": 24041,
"text": "Using a path traversal attack (also known as directory traversal), an attacker can access data stored outside the web root folder (typically /var/www/). By manipulating variables that reference files with “dot-dot-slash (../)” sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files."
},
{
"code": null,
"e": 24533,
"s": 24491,
"text": "Let’s assume we have a website running on"
},
{
"code": null,
"e": 24560,
"s": 24533,
"text": " http://www.mywebsite.com."
},
{
"code": null,
"e": 24866,
"s": 24560,
"text": "Let’s also suppose that the web server is vulnerable to path traversal attack. This allows an attacker to use special character sequences, like ../, which in Unix directories points to its parent directory, to traverse up the directory chain and access files outside of /var/www or config files like this."
},
{
"code": null,
"e": 24926,
"s": 24866,
"text": "A typical example of vulnerable application in PHP code is:"
},
{
"code": "<?php$template = 'red.php';if (isset($_COOKIE['TEMPLATE'])) $template = $_COOKIE['TEMPLATE'];include (\"/home/users/phpdemo/templates/\" . $template);?>",
"e": 25079,
"s": 24926,
"text": null
},
{
"code": null,
"e": 25218,
"s": 25079,
"text": "Using the same ../ technique, an attacker can escape out of the directory containing the PDFs and access anything they want on the system."
},
{
"code": null,
"e": 25292,
"s": 25218,
"text": "http://www.mywebsite.com/?template= ../../../../../../../../../etc/passwd"
},
{
"code": null,
"e": 25371,
"s": 25292,
"text": "PreventionA possible algorithm for preventing directory traversal would be to:"
},
{
"code": null,
"e": 25624,
"s": 25371,
"text": "Giving appropriate permissions to directories and files. A PHP file typically runs as www-data user on Linux. We should not allow this user to access system files. But this doesn’t prevent this user from accessing web-application specific config files."
},
{
"code": null,
"e": 25747,
"s": 25624,
"text": "Process URI requests that do not result in a file request, e.g., executing a hook into user code, before continuing below."
},
{
"code": null,
"e": 25918,
"s": 25747,
"text": "When a URI request for a file/directory is to be made, build a full path to the file/directory if it exists, and normalize all characters (e.g., %20 converted to spaces)."
},
{
"code": null,
"e": 26090,
"s": 25918,
"text": "It is assumed that a ‘Document Root’ fully qualified, normalized, path is known, and this string has a length N. Assume that no files outside this directory can be served."
},
{
"code": null,
"e": 26219,
"s": 26090,
"text": "Ensure that the first N characters of the fully qualified path to the requested file is exactly the same as the ‘Document Root’."
},
{
"code": null,
"e": 26355,
"s": 26219,
"text": "Using a hard-coded predefined file extension to suffix the path does not limit the scope of the attack to files of that file extension."
},
{
"code": null,
"e": 26527,
"s": 26355,
"text": "Sourceshttps://en.wikipedia.org/wiki/Directory_traversal_attackhttp://projects.webappsec.org/w/page/13246952/Path%20Traversalhttps://www.owasp.org/index.php/Path_Traversal"
},
{
"code": null,
"e": 26827,
"s": 26527,
"text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 26952,
"s": 26827,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 26966,
"s": 26952,
"text": "secure-coding"
},
{
"code": null,
"e": 26992,
"s": 26966,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 26998,
"s": 26992,
"text": "GBlog"
},
{
"code": null,
"e": 27096,
"s": 26998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27105,
"s": 27096,
"text": "Comments"
},
{
"code": null,
"e": 27118,
"s": 27105,
"text": "Old Comments"
},
{
"code": null,
"e": 27162,
"s": 27118,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27203,
"s": 27162,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27221,
"s": 27203,
"text": "OpenCV - Overview"
},
{
"code": null,
"e": 27248,
"s": 27221,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27311,
"s": 27248,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 27385,
"s": 27311,
"text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..."
},
{
"code": null,
"e": 27441,
"s": 27385,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 27469,
"s": 27441,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27494,
"s": 27469,
"text": "DSA Sheet by Love Babbar"
}
]
|
Text Generation With GPT-2 in Python | Towards Data Science | Language generation is one of those natural language tasks that can really produce an incredible feeling of awe at how far the fields of machine learning and artificial intelligence have come.
GPT-1, 2, and 3 are OpenAI’s top language models — well known for their ability to produce incredibly natural, coherent, and genuinely interesting language.
In this article, we will take a small snippet of text and learn how to feed that into a pre-trained GPT-2 model using PyTorch and Transformers to produce high-quality language generation in just eight lines of code. We cover:
> PyTorch and Transformers - Data> Building the Model - Initialization - Tokenization - Generation - Decoding> Results
If you prefer video, I’ve covered everything in this short video tutorial here:
We need both PyTorch and Transformers libraries installed to build our text generation model.
The setup instructions for PyTorch vary depending on your system, CUDA version (if any), and Python release. Fortunately, PyTorch has made a very easy to use guide here.
Next up is HuggingFace’s Transformers library. All this takes is a simple pip install transformers.
We need to feed into our model some text that our model will read and then generate more text from. I’ve taken the snippet above from Winston Churchill’s Wikipedia page — but feel free to use anything you like!
Once we have both frameworks installed, we can import what we need and initialize our tokenizer and model like so:
The tokenizer is used to translate between human-readable text and numeric indices. These indices are then mapped to word embeddings (numerical representations of words) by an embedding layer within the model.
All we need to do to tokenizer our input text is call the tokenizer.encode method like so:
Because we are using PyTorch, we add return_tensor='pt', if using TensorFlow, we would use return_tensor='tf'.
Now that we have our tokenization input text, we can begin generating text with GPT-2! All we do is call the model.generate method:
Here we set the maximum number of tokens to generate as 200. We also add do_sample=True to stop the model from just picking the most likely word at every step, which ends up looking like this:
He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, he was a very conservative figure, but he was also a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure
The top_k and temperature arguments can be used to modify our outputs' coherence/randomness — we will cover these at the end.
Our generate step outputs an array of tokens rather than words. To convert these tokens into words, we need to .decode them. This is easy to do:
All we need to add is skip_special_tokens=True to avoid decoding special tokens that are used by the model, such as the end of sequence token <|endoftext|>.
At this point, all we need to do is print our output!
We can get some great results with very little code. Here are a few examples that should give you a better understanding of the impact of each argument in the .generate method.
outputs = model.generate( inputs, max_length=200, do_sample=True)tokenizer.decode(outputs[0], skip_special_tokens=True)[Out]: "He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, these cabinet officers were part of the National Security Council, then headed by Lord Chamberlain's secretary Arthur Hargreaves. A number of them became key cabinet secretaries, including Lord Hargreaves in 1948, Lord Butler as Justice Minister in 1949 and Lord Codds as justice minister until his death in 1975. After being replaced by Lord Hargreaves in 1955, there was speculation that the next general election would see Chamberlain and Howe try and avoid a hard line policy..."
We can add more randomness with temperature — the default value is 1, a high value like 5 will produce a pretty nonsensical output:
outputs = model.generate( inputs, max_length=200, do_sample=True, temperature=5)tokenizer.decode(outputs[0], skip_special_tokens=True)[Out]: "He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, his foreign secretaries generally assumed other duties during cabinet so his job fell less and smaller - sometimes twice his overall stature so long a day seemed manageable after he became Chief Arctic Advisor: Mr Wilson led one reshover where we've also done another three, despite taking responsibility over appointments including Prime (for both) his time here since 1901)[31],[38-4]. (These last had fewer staff as many than he is responsible..."
Turning the temperature down below 1 will produce more linear but less creative outputs.
We can also add the top_k parameter — which limits the sample tokens to a given number of the most probable tokens. This results in text that tends to stick to the same topic (or set of words) for a longer period of time.
outputs = model.generate( inputs, max_length=200, do_sample=True, top_k=50)tokenizer.decode(outputs[0], skip_special_tokens=True)[Out]: "He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, however, the two men had to choose between their public business and politcal career, to the exclusion of all the other political options. To the shock of many, Chamberlain, who was not just a keen public servant but a man of his word, became the first Australian prime minister to be sacked by a Labour minister in a five-year term..."
That is all for this tutorial on language generation with GPT-2 in Python. We have put together a model that can produce reasonable, believable, and interesting text in hardly any time at all.
In just eight lines of code, we have:
Imported all the frameworks we need
Initialized a GPT-2 tokenizer and model
Defined our input text
Tokenized it
Generated new text from our original input
Decoded the generated outputs back into human-readable text
It really is incredible how easy this can be when using the PyTorch and Transformers frameworks.
I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too.
Thanks for reading!
🤖 NLP With Transformers Course | [
{
"code": null,
"e": 365,
"s": 172,
"text": "Language generation is one of those natural language tasks that can really produce an incredible feeling of awe at how far the fields of machine learning and artificial intelligence have come."
},
{
"code": null,
"e": 522,
"s": 365,
"text": "GPT-1, 2, and 3 are OpenAI’s top language models — well known for their ability to produce incredibly natural, coherent, and genuinely interesting language."
},
{
"code": null,
"e": 748,
"s": 522,
"text": "In this article, we will take a small snippet of text and learn how to feed that into a pre-trained GPT-2 model using PyTorch and Transformers to produce high-quality language generation in just eight lines of code. We cover:"
},
{
"code": null,
"e": 872,
"s": 748,
"text": "> PyTorch and Transformers - Data> Building the Model - Initialization - Tokenization - Generation - Decoding> Results"
},
{
"code": null,
"e": 952,
"s": 872,
"text": "If you prefer video, I’ve covered everything in this short video tutorial here:"
},
{
"code": null,
"e": 1046,
"s": 952,
"text": "We need both PyTorch and Transformers libraries installed to build our text generation model."
},
{
"code": null,
"e": 1216,
"s": 1046,
"text": "The setup instructions for PyTorch vary depending on your system, CUDA version (if any), and Python release. Fortunately, PyTorch has made a very easy to use guide here."
},
{
"code": null,
"e": 1316,
"s": 1216,
"text": "Next up is HuggingFace’s Transformers library. All this takes is a simple pip install transformers."
},
{
"code": null,
"e": 1527,
"s": 1316,
"text": "We need to feed into our model some text that our model will read and then generate more text from. I’ve taken the snippet above from Winston Churchill’s Wikipedia page — but feel free to use anything you like!"
},
{
"code": null,
"e": 1642,
"s": 1527,
"text": "Once we have both frameworks installed, we can import what we need and initialize our tokenizer and model like so:"
},
{
"code": null,
"e": 1852,
"s": 1642,
"text": "The tokenizer is used to translate between human-readable text and numeric indices. These indices are then mapped to word embeddings (numerical representations of words) by an embedding layer within the model."
},
{
"code": null,
"e": 1943,
"s": 1852,
"text": "All we need to do to tokenizer our input text is call the tokenizer.encode method like so:"
},
{
"code": null,
"e": 2054,
"s": 1943,
"text": "Because we are using PyTorch, we add return_tensor='pt', if using TensorFlow, we would use return_tensor='tf'."
},
{
"code": null,
"e": 2186,
"s": 2054,
"text": "Now that we have our tokenization input text, we can begin generating text with GPT-2! All we do is call the model.generate method:"
},
{
"code": null,
"e": 2379,
"s": 2186,
"text": "Here we set the maximum number of tokens to generate as 200. We also add do_sample=True to stop the model from just picking the most likely word at every step, which ends up looking like this:"
},
{
"code": null,
"e": 3127,
"s": 2379,
"text": "He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, he was a very conservative figure, but he was also a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure in the sense that he was a very conservative figure"
},
{
"code": null,
"e": 3253,
"s": 3127,
"text": "The top_k and temperature arguments can be used to modify our outputs' coherence/randomness — we will cover these at the end."
},
{
"code": null,
"e": 3398,
"s": 3253,
"text": "Our generate step outputs an array of tokens rather than words. To convert these tokens into words, we need to .decode them. This is easy to do:"
},
{
"code": null,
"e": 3555,
"s": 3398,
"text": "All we need to add is skip_special_tokens=True to avoid decoding special tokens that are used by the model, such as the end of sequence token <|endoftext|>."
},
{
"code": null,
"e": 3609,
"s": 3555,
"text": "At this point, all we need to do is print our output!"
},
{
"code": null,
"e": 3786,
"s": 3609,
"text": "We can get some great results with very little code. Here are a few examples that should give you a better understanding of the impact of each argument in the .generate method."
},
{
"code": null,
"e": 4706,
"s": 3786,
"text": "outputs = model.generate( inputs, max_length=200, do_sample=True)tokenizer.decode(outputs[0], skip_special_tokens=True)[Out]: \"He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, these cabinet officers were part of the National Security Council, then headed by Lord Chamberlain's secretary Arthur Hargreaves. A number of them became key cabinet secretaries, including Lord Hargreaves in 1948, Lord Butler as Justice Minister in 1949 and Lord Codds as justice minister until his death in 1975. After being replaced by Lord Hargreaves in 1955, there was speculation that the next general election would see Chamberlain and Howe try and avoid a hard line policy...\""
},
{
"code": null,
"e": 4838,
"s": 4706,
"text": "We can add more randomness with temperature — the default value is 1, a high value like 5 will produce a pretty nonsensical output:"
},
{
"code": null,
"e": 5740,
"s": 4838,
"text": "outputs = model.generate( inputs, max_length=200, do_sample=True, temperature=5)tokenizer.decode(outputs[0], skip_special_tokens=True)[Out]: \"He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, his foreign secretaries generally assumed other duties during cabinet so his job fell less and smaller - sometimes twice his overall stature so long a day seemed manageable after he became Chief Arctic Advisor: Mr Wilson led one reshover where we've also done another three, despite taking responsibility over appointments including Prime (for both) his time here since 1901)[31],[38-4]. (These last had fewer staff as many than he is responsible...\""
},
{
"code": null,
"e": 5829,
"s": 5740,
"text": "Turning the temperature down below 1 will produce more linear but less creative outputs."
},
{
"code": null,
"e": 6051,
"s": 5829,
"text": "We can also add the top_k parameter — which limits the sample tokens to a given number of the most probable tokens. This results in text that tends to stick to the same topic (or set of words) for a longer period of time."
},
{
"code": null,
"e": 6834,
"s": 6051,
"text": "outputs = model.generate( inputs, max_length=200, do_sample=True, top_k=50)tokenizer.decode(outputs[0], skip_special_tokens=True)[Out]: \"He began his premiership by forming a five-man war cabinet which included Chamerlain as Lord President of the Council, Labour leader Clement Attlee as Lord Privy Seal (later as Deputy Prime Minister), Halifax as Foreign Secretary and Labour's Arthur Greenwood as a minister without portfolio. In practice, however, the two men had to choose between their public business and politcal career, to the exclusion of all the other political options. To the shock of many, Chamberlain, who was not just a keen public servant but a man of his word, became the first Australian prime minister to be sacked by a Labour minister in a five-year term...\""
},
{
"code": null,
"e": 7027,
"s": 6834,
"text": "That is all for this tutorial on language generation with GPT-2 in Python. We have put together a model that can produce reasonable, believable, and interesting text in hardly any time at all."
},
{
"code": null,
"e": 7065,
"s": 7027,
"text": "In just eight lines of code, we have:"
},
{
"code": null,
"e": 7101,
"s": 7065,
"text": "Imported all the frameworks we need"
},
{
"code": null,
"e": 7141,
"s": 7101,
"text": "Initialized a GPT-2 tokenizer and model"
},
{
"code": null,
"e": 7164,
"s": 7141,
"text": "Defined our input text"
},
{
"code": null,
"e": 7177,
"s": 7164,
"text": "Tokenized it"
},
{
"code": null,
"e": 7220,
"s": 7177,
"text": "Generated new text from our original input"
},
{
"code": null,
"e": 7280,
"s": 7220,
"text": "Decoded the generated outputs back into human-readable text"
},
{
"code": null,
"e": 7377,
"s": 7280,
"text": "It really is incredible how easy this can be when using the PyTorch and Transformers frameworks."
},
{
"code": null,
"e": 7548,
"s": 7377,
"text": "I hope you enjoyed this article! If you have any questions, let me know via Twitter or in the comments below. If you’d like more content like this, I post on YouTube too."
},
{
"code": null,
"e": 7568,
"s": 7548,
"text": "Thanks for reading!"
}
]
|
Comparing two Strings lexicographically in Java
| We can compare two strings lexicographically using following ways in Java.
Using String.compareTo(String) method. It compares in a case-sensitive manner.
Using String.compareTo(String) method. It compares in a case-sensitive manner.
Using String.compareToIgnoreCase(String) method. It compares in case insensitive manner.
Using String.compareToIgnoreCase(String) method. It compares in case insensitive manner.
Using String.compareTo(Object) method. It compares in case-sensitive manner.
Using String.compareTo(Object) method. It compares in case-sensitive manner.
These methods return the ASCII difference of first odd characters of compared strings.
Live Demo
public class Tester {
public static void main(String args[]) {
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
}
-32
0
0 | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "We can compare two strings lexicographically using following ways in Java."
},
{
"code": null,
"e": 1216,
"s": 1137,
"text": "Using String.compareTo(String) method. It compares in a case-sensitive manner."
},
{
"code": null,
"e": 1295,
"s": 1216,
"text": "Using String.compareTo(String) method. It compares in a case-sensitive manner."
},
{
"code": null,
"e": 1384,
"s": 1295,
"text": "Using String.compareToIgnoreCase(String) method. It compares in case insensitive manner."
},
{
"code": null,
"e": 1473,
"s": 1384,
"text": "Using String.compareToIgnoreCase(String) method. It compares in case insensitive manner."
},
{
"code": null,
"e": 1550,
"s": 1473,
"text": "Using String.compareTo(Object) method. It compares in case-sensitive manner."
},
{
"code": null,
"e": 1627,
"s": 1550,
"text": "Using String.compareTo(Object) method. It compares in case-sensitive manner."
},
{
"code": null,
"e": 1714,
"s": 1627,
"text": "These methods return the ASCII difference of first odd characters of compared strings."
},
{
"code": null,
"e": 1724,
"s": 1714,
"text": "Live Demo"
},
{
"code": null,
"e": 2090,
"s": 1724,
"text": "public class Tester {\n public static void main(String args[]) {\n String str = \"Hello World\";\n String anotherString = \"hello world\";\n Object objStr = str;\n\n System.out.println( str.compareTo(anotherString) );\n System.out.println( str.compareToIgnoreCase(anotherString) );\n System.out.println( str.compareTo(objStr.toString()));\n }\n}"
},
{
"code": null,
"e": 2098,
"s": 2090,
"text": "-32\n0\n0"
}
]
|
Version Control with Git: Get Started in Less Than 15 Minutes | by CR Ferreira | Towards Data Science | Do you often hear about Git (or maybe GitHub) but have no idea what that means, what it is good for, or how it works? You’ve come to the right place.
In this tutorial, you will learn how to use the most basic Git commands — the ones that you will need to know most of the time when working with Git. More specifically, here you’ll learn how to create a Git repository for your project and how to use it to document all future changes in that project. And completing this tutorial should take less than fifteen minutes of your time, assuming that you won’t have any problems with the installation process (which I hope most people won’t). So let’s get right into it.
In a nutshell, Git is an open-source Version Control System that allows you to keep track of your project changes over time. For instance, with Git you can easily check what was the state of each file in the project at a given time, and even revert it to that state if you want to. It also makes it much easier to manage projects in which multiple people are working simultaneously, each one on their own computers.
Git is not the only Version Control System available (other examples: SVN, CVS, Mercurial), but it’s the most used one nowadays. If you are a software developer, web designer, data scientist, or work on basically any other kind of project involving text files, learning how to use Git will surely be a very valuable skill for you.
In this tutorial, we’ll be running Git commands from the command-line terminal (also known as command prompt in Windows), so it can be helpful if you already have some experience with using the terminal. But don’t worry if you have never used it before — you will still be able to follow this tutorial.
First, let’s open a command-line terminal on your computer. Here are some quick ways to do it depending on your operating system:
Windows: press [⊞ Win]+[R], then type cmd and press enter.
Linux: press [Ctrl]+[Alt]+[T].
MacOS: press [Command]+[Space], then type terminal and press enter.
We’ll start by checking if you already have Git installed on your computer — and if it isn’t, we’ll install it. Type git --version on the terminal and press enter. If Git is installed, you’ll see the currently installed version, as in the screenshot below. If you already have Git, you may skip directly to the next section, “Setting up your data”.
If you get something like git: command not found, then you will need to install Git. On MacOS, running git --version may already prompt some installation instructions, and you will just need to follow them. If that’s not your case, follow the instructions below, depending on your operating system:
Windows: install Git for Windows.
Linux: run sudo apt-get install git on the terminal.
MacOS: install Git for Mac.
After installation, you need to configure your name and e-mail — they will be used to identify you in your “commits” (I’ll explain what they are later). Do it by running these two commands in the terminal with your personal data:
git config --global user.name "Your Name"git config --global user.email "[email protected]"
That’s it. Now you are ready to start using Git!
While Git is mostly used by programmers, it can actually be used for any project with one or more computer files. In this tutorial, you will use Git to manage a project containing two simple text files: one with a shopping list and another with a to-do list. The commands you’ll use to manage this project are exactly the same as what you would use for a programming project.
Let’s start by creating the project directory and two text files in it. Create a directory named my_lists somewhere in your hard drive and create two text files inside it, with the following content:
shopping_list.txt:
- Toilet paper (10 rolls) - Beer (12 bottles)- Food
to-do_list.txt:
- Meet friends- Go shopping - Learn Git
This will be our project’s initial state.
Using the terminal, navigate to my_lists, the directory you’ve just created. You can do that with the command cd. If you don’t know how to do navigate using the terminal, here are some instructions: On Windows / On Linux or MacOS. After navigating to my_lists, if you run ls (on Linux/MacOS) or dir (on Windows), you should be able to see the two files you created.
Now, run git init to make your project directory officially a Git repository. After that, you can run git status from inside that directory at any moment to check what’s happening within it. If you do it now, you will see that your repository has “no commits yet” and that the two files are marked as “untracked”:
To make those files start being tracked by Git, you need to “add” them to the repository. You will use the command git add for that. Any of these options will do the trick:
Run git add shopping_list.txt and then git add to-do_list.txt to add each file at a time; or
run git add shopping_list.txt to-do_list.txt to add both files with a single command; or
run either git add . or git add -A to add all files in the current directory at once.
After adding the files, run git status again and you should see something like this:
Now the two files are in what is called the “staging area”. This means that those files will be included in the next commit you make.
In Git, a commit is a snapshot of the project state at a given time. Think of it as a version of the project that will be stored forever, such that in the future it will be easy for you to see what has changed since then, and you’ll even be able to revert the project back to that state if you want. Every time you make important changes in your project you should create a new commit, so that your work gets registered in the project’s history.
After adding the two files to the staging area, you can create your first commit with the command git commit -m "Your commit message" . Be sure to always write a meaningful commit message describing what has changed, because that message will be seen by anyone checking the project history.
After committing, run git log. This will show your commit history. At this point, you should only have one commit in the log, like this:
Note: you can also run the command git commit without the -m option — this will open a text editor that will ask you to input a commit message. But be careful, because depending on your system this may open a command-line text editor like vim, which can be hard to exit if you don’t know how to use it. You can also change the default text editor with the command git config --global core.editor <editor> .
After creating a Git repository for your project, the next step is to use it to document future changes. So let’s get back to our example: suppose that you’ve just found out about a major virus outbreak happening in your city and that forced you to modify your shopping and to-do lists, as shown below:
shopping_list.txt:
- Toilet paper (100 rolls)- Beer (120 bottles)- Food- Hand sanitizer
to-do_list.txt:
- Go shopping - Wash hands- Learn Git
As before, you can check the repository’s current state with the command git status. This will show that Git has detected changes in both files:
But you can also have more details on what has changed since your last commit with git diff. This will show all that has changed in all files, line-by-line:
Usually, unchanged lines are printed white, while new lines are green, and deleted lines are red. Note that lines that have been modified actually show up as if the old version had been deleted and a new line had been added.
To create a new commit with those changes, the process is the same as what you did to create the first commit: you’ll first use git add and then git commit.
While you could create a single commit for the changes in the two files, let’s create one commit for each file. First, run git add shopping_list.txt to add this file to the staging area. After that, you can check which changes have been added to the staging area with git diff --staged. This command will show exactly which changes will be committed if you run git commit now.
If everything is as expected, now create a new commit with those staged changes by running git commit, just like you did when creating your first commit. Again, make sure to include a meaningful commit message. After that, as an exercise, you can create a third commit with the changes in the file list.txt.
If you’ve done everything correctly, you now have three commits in your repository. You can check that with git log, and you should see something like this:
That’s it. Now you know how to create a Git repository for your project and how to make new commits for all your future changes. In general, most of the time you work with Git you will be using these few commands that you’ve just learned.
Of course, there’s a lot more to Git than that — the goal of this tutorial was only to get you started with the basic workflow described above. Here is a list of a few other things you can do with Git (including links with further details):
You can see which changes were introduced by a specific commit with git show.
You can undo all your uncommitted changes with git reset (be careful with this one).
You can revert all changes introduced by a specific commit with git revert.
You can temporary “stash” your changes with git stash.
You can revert your project to an older state with git checkout.
You can manage multiple features being implemented at the same time with Git branches.
You can share your project and/or collaborate with other people using a remote Git platform like GitHub or GitLab.
In general, you can find very helpful advice on how to use Git in online forums like StackOverflow. So if you have no idea how to do something with Git, you can usually learn a lot by simply searching about that online.
Git: A fast and easy guide to version control, by Christian Leonardo.
Beginning Git and GitHub: A Comprehensive Guide to Version Control, Project Management, and Teamwork for the New Developer, by Mariot Tsitoara.
For a couple of other useful commands, check 10 Git Commands You Should Know.
If you want to learn how to use GitHub, check Introduction to GitHub for Data Scientists.
medium.com
towardsdatascience.com
levelup.gitconnected.com
Disclosure: This post contains one or more links from the Amazon Services LLC Associates Program. As an affiliate, I get commissions for purchases made through those links, at no extra cost to the customer. | [
{
"code": null,
"e": 322,
"s": 172,
"text": "Do you often hear about Git (or maybe GitHub) but have no idea what that means, what it is good for, or how it works? You’ve come to the right place."
},
{
"code": null,
"e": 838,
"s": 322,
"text": "In this tutorial, you will learn how to use the most basic Git commands — the ones that you will need to know most of the time when working with Git. More specifically, here you’ll learn how to create a Git repository for your project and how to use it to document all future changes in that project. And completing this tutorial should take less than fifteen minutes of your time, assuming that you won’t have any problems with the installation process (which I hope most people won’t). So let’s get right into it."
},
{
"code": null,
"e": 1254,
"s": 838,
"text": "In a nutshell, Git is an open-source Version Control System that allows you to keep track of your project changes over time. For instance, with Git you can easily check what was the state of each file in the project at a given time, and even revert it to that state if you want to. It also makes it much easier to manage projects in which multiple people are working simultaneously, each one on their own computers."
},
{
"code": null,
"e": 1585,
"s": 1254,
"text": "Git is not the only Version Control System available (other examples: SVN, CVS, Mercurial), but it’s the most used one nowadays. If you are a software developer, web designer, data scientist, or work on basically any other kind of project involving text files, learning how to use Git will surely be a very valuable skill for you."
},
{
"code": null,
"e": 1888,
"s": 1585,
"text": "In this tutorial, we’ll be running Git commands from the command-line terminal (also known as command prompt in Windows), so it can be helpful if you already have some experience with using the terminal. But don’t worry if you have never used it before — you will still be able to follow this tutorial."
},
{
"code": null,
"e": 2018,
"s": 1888,
"text": "First, let’s open a command-line terminal on your computer. Here are some quick ways to do it depending on your operating system:"
},
{
"code": null,
"e": 2077,
"s": 2018,
"text": "Windows: press [⊞ Win]+[R], then type cmd and press enter."
},
{
"code": null,
"e": 2108,
"s": 2077,
"text": "Linux: press [Ctrl]+[Alt]+[T]."
},
{
"code": null,
"e": 2176,
"s": 2108,
"text": "MacOS: press [Command]+[Space], then type terminal and press enter."
},
{
"code": null,
"e": 2525,
"s": 2176,
"text": "We’ll start by checking if you already have Git installed on your computer — and if it isn’t, we’ll install it. Type git --version on the terminal and press enter. If Git is installed, you’ll see the currently installed version, as in the screenshot below. If you already have Git, you may skip directly to the next section, “Setting up your data”."
},
{
"code": null,
"e": 2824,
"s": 2525,
"text": "If you get something like git: command not found, then you will need to install Git. On MacOS, running git --version may already prompt some installation instructions, and you will just need to follow them. If that’s not your case, follow the instructions below, depending on your operating system:"
},
{
"code": null,
"e": 2858,
"s": 2824,
"text": "Windows: install Git for Windows."
},
{
"code": null,
"e": 2911,
"s": 2858,
"text": "Linux: run sudo apt-get install git on the terminal."
},
{
"code": null,
"e": 2939,
"s": 2911,
"text": "MacOS: install Git for Mac."
},
{
"code": null,
"e": 3169,
"s": 2939,
"text": "After installation, you need to configure your name and e-mail — they will be used to identify you in your “commits” (I’ll explain what they are later). Do it by running these two commands in the terminal with your personal data:"
},
{
"code": null,
"e": 3258,
"s": 3169,
"text": "git config --global user.name \"Your Name\"git config --global user.email \"[email protected]\""
},
{
"code": null,
"e": 3307,
"s": 3258,
"text": "That’s it. Now you are ready to start using Git!"
},
{
"code": null,
"e": 3683,
"s": 3307,
"text": "While Git is mostly used by programmers, it can actually be used for any project with one or more computer files. In this tutorial, you will use Git to manage a project containing two simple text files: one with a shopping list and another with a to-do list. The commands you’ll use to manage this project are exactly the same as what you would use for a programming project."
},
{
"code": null,
"e": 3883,
"s": 3683,
"text": "Let’s start by creating the project directory and two text files in it. Create a directory named my_lists somewhere in your hard drive and create two text files inside it, with the following content:"
},
{
"code": null,
"e": 3902,
"s": 3883,
"text": "shopping_list.txt:"
},
{
"code": null,
"e": 3954,
"s": 3902,
"text": "- Toilet paper (10 rolls) - Beer (12 bottles)- Food"
},
{
"code": null,
"e": 3970,
"s": 3954,
"text": "to-do_list.txt:"
},
{
"code": null,
"e": 4010,
"s": 3970,
"text": "- Meet friends- Go shopping - Learn Git"
},
{
"code": null,
"e": 4052,
"s": 4010,
"text": "This will be our project’s initial state."
},
{
"code": null,
"e": 4418,
"s": 4052,
"text": "Using the terminal, navigate to my_lists, the directory you’ve just created. You can do that with the command cd. If you don’t know how to do navigate using the terminal, here are some instructions: On Windows / On Linux or MacOS. After navigating to my_lists, if you run ls (on Linux/MacOS) or dir (on Windows), you should be able to see the two files you created."
},
{
"code": null,
"e": 4732,
"s": 4418,
"text": "Now, run git init to make your project directory officially a Git repository. After that, you can run git status from inside that directory at any moment to check what’s happening within it. If you do it now, you will see that your repository has “no commits yet” and that the two files are marked as “untracked”:"
},
{
"code": null,
"e": 4905,
"s": 4732,
"text": "To make those files start being tracked by Git, you need to “add” them to the repository. You will use the command git add for that. Any of these options will do the trick:"
},
{
"code": null,
"e": 4998,
"s": 4905,
"text": "Run git add shopping_list.txt and then git add to-do_list.txt to add each file at a time; or"
},
{
"code": null,
"e": 5087,
"s": 4998,
"text": "run git add shopping_list.txt to-do_list.txt to add both files with a single command; or"
},
{
"code": null,
"e": 5173,
"s": 5087,
"text": "run either git add . or git add -A to add all files in the current directory at once."
},
{
"code": null,
"e": 5258,
"s": 5173,
"text": "After adding the files, run git status again and you should see something like this:"
},
{
"code": null,
"e": 5392,
"s": 5258,
"text": "Now the two files are in what is called the “staging area”. This means that those files will be included in the next commit you make."
},
{
"code": null,
"e": 5838,
"s": 5392,
"text": "In Git, a commit is a snapshot of the project state at a given time. Think of it as a version of the project that will be stored forever, such that in the future it will be easy for you to see what has changed since then, and you’ll even be able to revert the project back to that state if you want. Every time you make important changes in your project you should create a new commit, so that your work gets registered in the project’s history."
},
{
"code": null,
"e": 6129,
"s": 5838,
"text": "After adding the two files to the staging area, you can create your first commit with the command git commit -m \"Your commit message\" . Be sure to always write a meaningful commit message describing what has changed, because that message will be seen by anyone checking the project history."
},
{
"code": null,
"e": 6266,
"s": 6129,
"text": "After committing, run git log. This will show your commit history. At this point, you should only have one commit in the log, like this:"
},
{
"code": null,
"e": 6673,
"s": 6266,
"text": "Note: you can also run the command git commit without the -m option — this will open a text editor that will ask you to input a commit message. But be careful, because depending on your system this may open a command-line text editor like vim, which can be hard to exit if you don’t know how to use it. You can also change the default text editor with the command git config --global core.editor <editor> ."
},
{
"code": null,
"e": 6976,
"s": 6673,
"text": "After creating a Git repository for your project, the next step is to use it to document future changes. So let’s get back to our example: suppose that you’ve just found out about a major virus outbreak happening in your city and that forced you to modify your shopping and to-do lists, as shown below:"
},
{
"code": null,
"e": 6995,
"s": 6976,
"text": "shopping_list.txt:"
},
{
"code": null,
"e": 7064,
"s": 6995,
"text": "- Toilet paper (100 rolls)- Beer (120 bottles)- Food- Hand sanitizer"
},
{
"code": null,
"e": 7080,
"s": 7064,
"text": "to-do_list.txt:"
},
{
"code": null,
"e": 7118,
"s": 7080,
"text": "- Go shopping - Wash hands- Learn Git"
},
{
"code": null,
"e": 7263,
"s": 7118,
"text": "As before, you can check the repository’s current state with the command git status. This will show that Git has detected changes in both files:"
},
{
"code": null,
"e": 7420,
"s": 7263,
"text": "But you can also have more details on what has changed since your last commit with git diff. This will show all that has changed in all files, line-by-line:"
},
{
"code": null,
"e": 7645,
"s": 7420,
"text": "Usually, unchanged lines are printed white, while new lines are green, and deleted lines are red. Note that lines that have been modified actually show up as if the old version had been deleted and a new line had been added."
},
{
"code": null,
"e": 7802,
"s": 7645,
"text": "To create a new commit with those changes, the process is the same as what you did to create the first commit: you’ll first use git add and then git commit."
},
{
"code": null,
"e": 8179,
"s": 7802,
"text": "While you could create a single commit for the changes in the two files, let’s create one commit for each file. First, run git add shopping_list.txt to add this file to the staging area. After that, you can check which changes have been added to the staging area with git diff --staged. This command will show exactly which changes will be committed if you run git commit now."
},
{
"code": null,
"e": 8487,
"s": 8179,
"text": "If everything is as expected, now create a new commit with those staged changes by running git commit, just like you did when creating your first commit. Again, make sure to include a meaningful commit message. After that, as an exercise, you can create a third commit with the changes in the file list.txt."
},
{
"code": null,
"e": 8644,
"s": 8487,
"text": "If you’ve done everything correctly, you now have three commits in your repository. You can check that with git log, and you should see something like this:"
},
{
"code": null,
"e": 8883,
"s": 8644,
"text": "That’s it. Now you know how to create a Git repository for your project and how to make new commits for all your future changes. In general, most of the time you work with Git you will be using these few commands that you’ve just learned."
},
{
"code": null,
"e": 9124,
"s": 8883,
"text": "Of course, there’s a lot more to Git than that — the goal of this tutorial was only to get you started with the basic workflow described above. Here is a list of a few other things you can do with Git (including links with further details):"
},
{
"code": null,
"e": 9202,
"s": 9124,
"text": "You can see which changes were introduced by a specific commit with git show."
},
{
"code": null,
"e": 9287,
"s": 9202,
"text": "You can undo all your uncommitted changes with git reset (be careful with this one)."
},
{
"code": null,
"e": 9363,
"s": 9287,
"text": "You can revert all changes introduced by a specific commit with git revert."
},
{
"code": null,
"e": 9418,
"s": 9363,
"text": "You can temporary “stash” your changes with git stash."
},
{
"code": null,
"e": 9483,
"s": 9418,
"text": "You can revert your project to an older state with git checkout."
},
{
"code": null,
"e": 9570,
"s": 9483,
"text": "You can manage multiple features being implemented at the same time with Git branches."
},
{
"code": null,
"e": 9685,
"s": 9570,
"text": "You can share your project and/or collaborate with other people using a remote Git platform like GitHub or GitLab."
},
{
"code": null,
"e": 9905,
"s": 9685,
"text": "In general, you can find very helpful advice on how to use Git in online forums like StackOverflow. So if you have no idea how to do something with Git, you can usually learn a lot by simply searching about that online."
},
{
"code": null,
"e": 9975,
"s": 9905,
"text": "Git: A fast and easy guide to version control, by Christian Leonardo."
},
{
"code": null,
"e": 10119,
"s": 9975,
"text": "Beginning Git and GitHub: A Comprehensive Guide to Version Control, Project Management, and Teamwork for the New Developer, by Mariot Tsitoara."
},
{
"code": null,
"e": 10197,
"s": 10119,
"text": "For a couple of other useful commands, check 10 Git Commands You Should Know."
},
{
"code": null,
"e": 10287,
"s": 10197,
"text": "If you want to learn how to use GitHub, check Introduction to GitHub for Data Scientists."
},
{
"code": null,
"e": 10298,
"s": 10287,
"text": "medium.com"
},
{
"code": null,
"e": 10321,
"s": 10298,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10346,
"s": 10321,
"text": "levelup.gitconnected.com"
}
]
|
How to pass a PHP array to a JavaScript function? | PHP array can be passed to a JavaScript function using json_encode with the below lines of code −
<script>
var var_name= <?php echo json_encode($php_variable); ?>;
</script>
If an object needs to be parsed from JSON like string (required in AJAX request), the below lines of code can be used −
var my_data = "<JSON-String>";
var my_var = JSON.parse(my_data);
Let us see an example −
<?php
// Create a PHP array
$sample_array = array(
0 => "Hello",
1 => "there",
)
?>
<script>
// Access the elements of the array
var passed_array = <?php echo json_encode($sample_array); ?>;
// Display the elements inside the array
for(var i = 0; i < passed_array.length; i++){
document.write(passed_array[i]);
}
</script>
This will produce the following output −
Hellothere | [
{
"code": null,
"e": 1160,
"s": 1062,
"text": "PHP array can be passed to a JavaScript function using json_encode with the below lines of code −"
},
{
"code": null,
"e": 1239,
"s": 1160,
"text": "<script>\n var var_name= <?php echo json_encode($php_variable); ?>;\n</script>"
},
{
"code": null,
"e": 1359,
"s": 1239,
"text": "If an object needs to be parsed from JSON like string (required in AJAX request), the below lines of code can be used −"
},
{
"code": null,
"e": 1424,
"s": 1359,
"text": "var my_data = \"<JSON-String>\";\nvar my_var = JSON.parse(my_data);"
},
{
"code": null,
"e": 1448,
"s": 1424,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1813,
"s": 1448,
"text": "<?php\n // Create a PHP array\n $sample_array = array(\n 0 => \"Hello\",\n 1 => \"there\",\n )\n?>\n<script>\n // Access the elements of the array\n var passed_array = <?php echo json_encode($sample_array); ?>;\n // Display the elements inside the array\n for(var i = 0; i < passed_array.length; i++){\n document.write(passed_array[i]);\n }\n</script>"
},
{
"code": null,
"e": 1854,
"s": 1813,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1865,
"s": 1854,
"text": "Hellothere"
}
]
|
Bag recognition with Android and TensorFlow using Image classification | by Sumit Mukhija | Towards Data Science | Recently while I was traveling to North-Eastern parts of India, I had to wait for a substantial time for my bag to show up on the airport’s baggage carousel. The area surrounding the carousel was packed with fellow commuters. It was hard to tell my bag apart from the other bags as roughly half the bags looked similar. I had to physically inspect half a dozen bags to ensure that none of them was mine.
I thought someone would have built something to address this problem. I began to look for an existing solution, but I couldn’t find anything. I stumbled upon some of the blogs that demonstrated custom object detection using TensorFlow. I later discovered this incredibly useful resource, based on which I started working towards the solution.
The first thing that I needed was data. I could have clicked a few pictures of my bag, but I decided to capture videos with all the sides and edges of the subject. I extracted individual frames from the videos and handpicked the visually discrete frames. I converted the selected frames to grayscale images. I used ffmpeg. On a command line or terminal, type,
ffmpeg -i video.mp4 -qscale:v 2 image_%03d.jpg
The video.mp4 is the video of my bag and the output images are prefixed by image_. I then needed pictures that were not of my bag. I found a useful Google Chrome extension, named Fatkun. The extension empowers me to download bulk images. I searched for bags on Google Images and downloaded a bunch of those images. Just like the photographs of my bag, I converted the later downloaded pictures to grayscale.
I executed a Python script to convert images to grayscale. The Python script below has a function rescale that takes a directory and converts all the images in that directory to grayscale. The script has one dependency, PIL.
As I was orchestrating my data, there was no risk of an imbalanced data set. I had an equal number of images for my bag and not my bag.
Once I had the images, I downloaded Tensorflow-for-Poets from here. You would need to have TensorFlow installed on your computer. Also, you would need to download PILLOW. You could do both by typing in the commands below.
pip install --upgrade "tensorflow==1.7.*"pip install PILLOW
In the root directory of Tensorflow-for-poets, I executed,
python3 -m scripts.retrain --bottleneck_dir=tf_files/bottlenecks --how_many_training_steps=500 --model_dir=tf_files/models/ --summaries_dir=tf_files/training_summaries/mobilenet_v2_1.4_224 --output_graph=tf_files/retrained_graph_bags.pb --output_labels=tf_files/retrained_labels.txt --architecture="mobilenet_0.50_224" --image_dir=/Users/sumit/Desktop/carousel/Baggage-Carousel/Labs/data/
The scripts.retrain takes a directory as an input. In my case it was the last part of the command.
image_dir=/Users/sumit/Desktop/carousel/Baggage-Carousel/Labs/data/
The folder looks like this:
The folder named bag holds grayscaled images of my bag. The other folder contains grayscaled pictures of all the other bags that I could get my hands on. The ‘architecture’ argument is the model that I wanted to retrain. I’d encourage everyone to play around with the models. The list of models can be found on here.
The ‘retrained_labels’ is a text file that gets generated and bears the name of the two folders. The two folders behave like two classes. Also, ‘retrained_graph_bags.pb’ is the outcome of the process. Both the files could be found in:
tensorflow-for-poets-2/tf_files
The command should be executed from the root directory of tensorflow-for-poets. When the command is executed, it will initiate the learning process.
Up next, I had to convert the produced graph to a tflite. Tflite or TensorFlowLite is used to deploy machine learning models to mobile devices. The conversion was done by executing the following command
toco — graph_def_file=tf_files/retrained_graph_bags.pb — output_file=tf_files/bagdroid_graph.tflite — output_format=TFLITE — input_shape=1,224,224,3 — input_array=input — output_array=final_result — inference_type=FLOAT — input_data_type=FLOAT
The command above takes the ‘retrained_graph_bags.pb’ as an input and produces a mobile friendly tflite file, named ‘bagdroid_graph.tflite’.
The Android application needed just a few changes. Apart from the cosmetic changes,
I had to copy ‘retrained_labels.txt’ and ‘bagdroid_graph.tflite’ to the assets folder of the application.In ImageClassifier.java, I had to point MODEL_PATH and LABEL_PATH to the correct values.I had to add audio and haptic feedback on detection.
I had to copy ‘retrained_labels.txt’ and ‘bagdroid_graph.tflite’ to the assets folder of the application.
In ImageClassifier.java, I had to point MODEL_PATH and LABEL_PATH to the correct values.
I had to add audio and haptic feedback on detection.
The application on completion was supposed to look better and be able to detect the bag it was trained to detect.
In the end, the application was able to detect my bag, give me audio and haptic feedback.
A pretty obvious problem is that if two bags are identical, the application would identify both the bags. This problem can be mitigated by using NFC chips.
But, the actual problem is that the application often flags random things as my bag. I would love to hear what could I do to minimise the false positives. | [
{
"code": null,
"e": 575,
"s": 171,
"text": "Recently while I was traveling to North-Eastern parts of India, I had to wait for a substantial time for my bag to show up on the airport’s baggage carousel. The area surrounding the carousel was packed with fellow commuters. It was hard to tell my bag apart from the other bags as roughly half the bags looked similar. I had to physically inspect half a dozen bags to ensure that none of them was mine."
},
{
"code": null,
"e": 918,
"s": 575,
"text": "I thought someone would have built something to address this problem. I began to look for an existing solution, but I couldn’t find anything. I stumbled upon some of the blogs that demonstrated custom object detection using TensorFlow. I later discovered this incredibly useful resource, based on which I started working towards the solution."
},
{
"code": null,
"e": 1278,
"s": 918,
"text": "The first thing that I needed was data. I could have clicked a few pictures of my bag, but I decided to capture videos with all the sides and edges of the subject. I extracted individual frames from the videos and handpicked the visually discrete frames. I converted the selected frames to grayscale images. I used ffmpeg. On a command line or terminal, type,"
},
{
"code": null,
"e": 1325,
"s": 1278,
"text": "ffmpeg -i video.mp4 -qscale:v 2 image_%03d.jpg"
},
{
"code": null,
"e": 1733,
"s": 1325,
"text": "The video.mp4 is the video of my bag and the output images are prefixed by image_. I then needed pictures that were not of my bag. I found a useful Google Chrome extension, named Fatkun. The extension empowers me to download bulk images. I searched for bags on Google Images and downloaded a bunch of those images. Just like the photographs of my bag, I converted the later downloaded pictures to grayscale."
},
{
"code": null,
"e": 1958,
"s": 1733,
"text": "I executed a Python script to convert images to grayscale. The Python script below has a function rescale that takes a directory and converts all the images in that directory to grayscale. The script has one dependency, PIL."
},
{
"code": null,
"e": 2094,
"s": 1958,
"text": "As I was orchestrating my data, there was no risk of an imbalanced data set. I had an equal number of images for my bag and not my bag."
},
{
"code": null,
"e": 2316,
"s": 2094,
"text": "Once I had the images, I downloaded Tensorflow-for-Poets from here. You would need to have TensorFlow installed on your computer. Also, you would need to download PILLOW. You could do both by typing in the commands below."
},
{
"code": null,
"e": 2377,
"s": 2316,
"text": "pip install --upgrade \"tensorflow==1.7.*\"pip install PILLOW"
},
{
"code": null,
"e": 2436,
"s": 2377,
"text": "In the root directory of Tensorflow-for-poets, I executed,"
},
{
"code": null,
"e": 2825,
"s": 2436,
"text": "python3 -m scripts.retrain --bottleneck_dir=tf_files/bottlenecks --how_many_training_steps=500 --model_dir=tf_files/models/ --summaries_dir=tf_files/training_summaries/mobilenet_v2_1.4_224 --output_graph=tf_files/retrained_graph_bags.pb --output_labels=tf_files/retrained_labels.txt --architecture=\"mobilenet_0.50_224\" --image_dir=/Users/sumit/Desktop/carousel/Baggage-Carousel/Labs/data/"
},
{
"code": null,
"e": 2924,
"s": 2825,
"text": "The scripts.retrain takes a directory as an input. In my case it was the last part of the command."
},
{
"code": null,
"e": 2992,
"s": 2924,
"text": "image_dir=/Users/sumit/Desktop/carousel/Baggage-Carousel/Labs/data/"
},
{
"code": null,
"e": 3020,
"s": 2992,
"text": "The folder looks like this:"
},
{
"code": null,
"e": 3337,
"s": 3020,
"text": "The folder named bag holds grayscaled images of my bag. The other folder contains grayscaled pictures of all the other bags that I could get my hands on. The ‘architecture’ argument is the model that I wanted to retrain. I’d encourage everyone to play around with the models. The list of models can be found on here."
},
{
"code": null,
"e": 3572,
"s": 3337,
"text": "The ‘retrained_labels’ is a text file that gets generated and bears the name of the two folders. The two folders behave like two classes. Also, ‘retrained_graph_bags.pb’ is the outcome of the process. Both the files could be found in:"
},
{
"code": null,
"e": 3604,
"s": 3572,
"text": "tensorflow-for-poets-2/tf_files"
},
{
"code": null,
"e": 3753,
"s": 3604,
"text": "The command should be executed from the root directory of tensorflow-for-poets. When the command is executed, it will initiate the learning process."
},
{
"code": null,
"e": 3956,
"s": 3753,
"text": "Up next, I had to convert the produced graph to a tflite. Tflite or TensorFlowLite is used to deploy machine learning models to mobile devices. The conversion was done by executing the following command"
},
{
"code": null,
"e": 4200,
"s": 3956,
"text": "toco — graph_def_file=tf_files/retrained_graph_bags.pb — output_file=tf_files/bagdroid_graph.tflite — output_format=TFLITE — input_shape=1,224,224,3 — input_array=input — output_array=final_result — inference_type=FLOAT — input_data_type=FLOAT"
},
{
"code": null,
"e": 4341,
"s": 4200,
"text": "The command above takes the ‘retrained_graph_bags.pb’ as an input and produces a mobile friendly tflite file, named ‘bagdroid_graph.tflite’."
},
{
"code": null,
"e": 4425,
"s": 4341,
"text": "The Android application needed just a few changes. Apart from the cosmetic changes,"
},
{
"code": null,
"e": 4671,
"s": 4425,
"text": "I had to copy ‘retrained_labels.txt’ and ‘bagdroid_graph.tflite’ to the assets folder of the application.In ImageClassifier.java, I had to point MODEL_PATH and LABEL_PATH to the correct values.I had to add audio and haptic feedback on detection."
},
{
"code": null,
"e": 4777,
"s": 4671,
"text": "I had to copy ‘retrained_labels.txt’ and ‘bagdroid_graph.tflite’ to the assets folder of the application."
},
{
"code": null,
"e": 4866,
"s": 4777,
"text": "In ImageClassifier.java, I had to point MODEL_PATH and LABEL_PATH to the correct values."
},
{
"code": null,
"e": 4919,
"s": 4866,
"text": "I had to add audio and haptic feedback on detection."
},
{
"code": null,
"e": 5033,
"s": 4919,
"text": "The application on completion was supposed to look better and be able to detect the bag it was trained to detect."
},
{
"code": null,
"e": 5123,
"s": 5033,
"text": "In the end, the application was able to detect my bag, give me audio and haptic feedback."
},
{
"code": null,
"e": 5279,
"s": 5123,
"text": "A pretty obvious problem is that if two bags are identical, the application would identify both the bags. This problem can be mitigated by using NFC chips."
}
]
|
How to connect Databricks to your Azure Data Lake | by René Bremer | Towards Data Science | TLTR: Clone this git project, set params and run 0_script.sh to deploy 1 ALDSgen2 hub and N Databricks spokes
A data lake is a centralized repository of data that allows enterprises to create business value from data. Azure Databricks is a popular tool to analyze data and build data pipelines. In this blog, it is discussed how Azure Databricks can be connected to an ADLSgen2 storage account in a secure and scalable way. In this, the following is key:
Defense in depth: ADLSgen2 contains sensitive data and shall be secured using private endpoints and Azure AD (disabling access keys). Databricks can only access ADLSgen2 using private link and Azure AD
Access control: Business units typically have their own Databricks workspace. Multiple workspaces shall be granted access to ADLSgen2 File Systems using Role Based Access Control (RBAC)
Hub/spoke architecture: Only one hub network can access the ADLSgen2 account using private link. Databricks spoke networks peer to the hub network to simplify networking
See also picture below:
In the remaining of this blogpost, the project will be explained in more detail. In the next chapter, the project will be deployed.
In the remainder of this blog, the project is deployed using the following steps:
2.1 Prerequisites
2.2 Create 1 ADLSgen2 account with hub network
2.3 Create N Databricks workspaces with spoke networks
2.4 Connect Databricks with ADLSgen2 account using private link
2.5 Mount storage account with Databricks
The following resources are required in this tutorial:
Azure Account
Azure DevOps or Ubuntu terminal to run shell scripts
Azure CLI
Finally, clone the project below or add the repository in your Azure DevOps project.
git clone https://github.com/rebremer/blog-databrickshubspoke-git
This repository contains 5 scripts in which 0_script.sh triggers the other 4 scripts where the deployment is done. It also contains a params_template.sh file. The variables value in this file need to be substituted with your variables and renamed to params.sh. You are then ready to run the scripts. The 4 scripts are discussed in the remaining of this blog.
In script 1_deploy_resources_1_hub.sh the following steps are executed:
Create an ADLSgen2 account with hierarchical namespace enabled. This allows to create folders and to do fine grained access control
Create a VNET and add a private endpoint to the storage account
Create a private dns zone using the private endpoint as zone
In script 2_deploy_resources_N_spokes.sh the following steps are executed:
Create N Databricks workspaces. Workspaces are deployed in their own VNET and possibly in different subscriptions. Databricks is deployed with clusters only have a private IP.
For each Databricks workspace, create a service principal. Grant service principal access rights to its own File System in the Storage account
In script 3_configure_network_N_spokes.sh the following steps are executed:
Create a peering for each Databricks spoke VNET to the hub VNET of the storage account
Vice versa, create a peering from the hub VNET to each Databricks spoke VNET
Add all Databricks VNETs to the private dns zone such that private endpoint of the storage account can be used in Databricks notebooks
In script 4_mount_storage_N_spokes.sh the following steps are executed:
For each Databricks workspace, add the mount notebooks to workspace using the Databricks REST API
For each Databricks workspace, store the credentials of the service principals in a Databricks backed secret scope
Create a cluster and run the notebook on the cluster. Notebook will fetch the service principal credentials from the storage account and mount to its own File System in the storage account using the private endpoint of the storaged, see also screenshort below
A data lake is a centralized repository of data that allows enterprises to create business value from data. Azure Databricks is a popular tool to analyze data and build data pipelines. In this blog, it is discussed how Azure Databricks can be connected to an ADLSgen2 storage account using defense in depth, Azure AD access control and hub/spoke architecture, see also picture below. | [
{
"code": null,
"e": 281,
"s": 171,
"text": "TLTR: Clone this git project, set params and run 0_script.sh to deploy 1 ALDSgen2 hub and N Databricks spokes"
},
{
"code": null,
"e": 626,
"s": 281,
"text": "A data lake is a centralized repository of data that allows enterprises to create business value from data. Azure Databricks is a popular tool to analyze data and build data pipelines. In this blog, it is discussed how Azure Databricks can be connected to an ADLSgen2 storage account in a secure and scalable way. In this, the following is key:"
},
{
"code": null,
"e": 828,
"s": 626,
"text": "Defense in depth: ADLSgen2 contains sensitive data and shall be secured using private endpoints and Azure AD (disabling access keys). Databricks can only access ADLSgen2 using private link and Azure AD"
},
{
"code": null,
"e": 1014,
"s": 828,
"text": "Access control: Business units typically have their own Databricks workspace. Multiple workspaces shall be granted access to ADLSgen2 File Systems using Role Based Access Control (RBAC)"
},
{
"code": null,
"e": 1184,
"s": 1014,
"text": "Hub/spoke architecture: Only one hub network can access the ADLSgen2 account using private link. Databricks spoke networks peer to the hub network to simplify networking"
},
{
"code": null,
"e": 1208,
"s": 1184,
"text": "See also picture below:"
},
{
"code": null,
"e": 1340,
"s": 1208,
"text": "In the remaining of this blogpost, the project will be explained in more detail. In the next chapter, the project will be deployed."
},
{
"code": null,
"e": 1422,
"s": 1340,
"text": "In the remainder of this blog, the project is deployed using the following steps:"
},
{
"code": null,
"e": 1440,
"s": 1422,
"text": "2.1 Prerequisites"
},
{
"code": null,
"e": 1487,
"s": 1440,
"text": "2.2 Create 1 ADLSgen2 account with hub network"
},
{
"code": null,
"e": 1542,
"s": 1487,
"text": "2.3 Create N Databricks workspaces with spoke networks"
},
{
"code": null,
"e": 1606,
"s": 1542,
"text": "2.4 Connect Databricks with ADLSgen2 account using private link"
},
{
"code": null,
"e": 1648,
"s": 1606,
"text": "2.5 Mount storage account with Databricks"
},
{
"code": null,
"e": 1703,
"s": 1648,
"text": "The following resources are required in this tutorial:"
},
{
"code": null,
"e": 1717,
"s": 1703,
"text": "Azure Account"
},
{
"code": null,
"e": 1770,
"s": 1717,
"text": "Azure DevOps or Ubuntu terminal to run shell scripts"
},
{
"code": null,
"e": 1780,
"s": 1770,
"text": "Azure CLI"
},
{
"code": null,
"e": 1865,
"s": 1780,
"text": "Finally, clone the project below or add the repository in your Azure DevOps project."
},
{
"code": null,
"e": 1931,
"s": 1865,
"text": "git clone https://github.com/rebremer/blog-databrickshubspoke-git"
},
{
"code": null,
"e": 2290,
"s": 1931,
"text": "This repository contains 5 scripts in which 0_script.sh triggers the other 4 scripts where the deployment is done. It also contains a params_template.sh file. The variables value in this file need to be substituted with your variables and renamed to params.sh. You are then ready to run the scripts. The 4 scripts are discussed in the remaining of this blog."
},
{
"code": null,
"e": 2362,
"s": 2290,
"text": "In script 1_deploy_resources_1_hub.sh the following steps are executed:"
},
{
"code": null,
"e": 2494,
"s": 2362,
"text": "Create an ADLSgen2 account with hierarchical namespace enabled. This allows to create folders and to do fine grained access control"
},
{
"code": null,
"e": 2558,
"s": 2494,
"text": "Create a VNET and add a private endpoint to the storage account"
},
{
"code": null,
"e": 2619,
"s": 2558,
"text": "Create a private dns zone using the private endpoint as zone"
},
{
"code": null,
"e": 2694,
"s": 2619,
"text": "In script 2_deploy_resources_N_spokes.sh the following steps are executed:"
},
{
"code": null,
"e": 2870,
"s": 2694,
"text": "Create N Databricks workspaces. Workspaces are deployed in their own VNET and possibly in different subscriptions. Databricks is deployed with clusters only have a private IP."
},
{
"code": null,
"e": 3013,
"s": 2870,
"text": "For each Databricks workspace, create a service principal. Grant service principal access rights to its own File System in the Storage account"
},
{
"code": null,
"e": 3089,
"s": 3013,
"text": "In script 3_configure_network_N_spokes.sh the following steps are executed:"
},
{
"code": null,
"e": 3176,
"s": 3089,
"text": "Create a peering for each Databricks spoke VNET to the hub VNET of the storage account"
},
{
"code": null,
"e": 3253,
"s": 3176,
"text": "Vice versa, create a peering from the hub VNET to each Databricks spoke VNET"
},
{
"code": null,
"e": 3388,
"s": 3253,
"text": "Add all Databricks VNETs to the private dns zone such that private endpoint of the storage account can be used in Databricks notebooks"
},
{
"code": null,
"e": 3460,
"s": 3388,
"text": "In script 4_mount_storage_N_spokes.sh the following steps are executed:"
},
{
"code": null,
"e": 3558,
"s": 3460,
"text": "For each Databricks workspace, add the mount notebooks to workspace using the Databricks REST API"
},
{
"code": null,
"e": 3673,
"s": 3558,
"text": "For each Databricks workspace, store the credentials of the service principals in a Databricks backed secret scope"
},
{
"code": null,
"e": 3933,
"s": 3673,
"text": "Create a cluster and run the notebook on the cluster. Notebook will fetch the service principal credentials from the storage account and mount to its own File System in the storage account using the private endpoint of the storaged, see also screenshort below"
}
]
|
Generate Random Long type numbers in Java | In order to generate Random long type numbers in Java, we use the nextLong() method of the java.util.Random class. This returns the next random long value from the random generator sequence.
Declaration − The java.util.Random.nextLong() method is declared as follows −
public long nextLong()
Let us see a program to generate random long type numbers in Java −
Live Demo
import java.util.Random;
public class Example {
public static void main(String[] args) {
Random rd = new Random(); // creating Random object
System.out.println(rd.nextLong()); // displaying a random long value
}
}
-4787108556148621714
Note - The output may vary on Online compilers. | [
{
"code": null,
"e": 1253,
"s": 1062,
"text": "In order to generate Random long type numbers in Java, we use the nextLong() method of the java.util.Random class. This returns the next random long value from the random generator sequence."
},
{
"code": null,
"e": 1331,
"s": 1253,
"text": "Declaration − The java.util.Random.nextLong() method is declared as follows −"
},
{
"code": null,
"e": 1354,
"s": 1331,
"text": "public long nextLong()"
},
{
"code": null,
"e": 1422,
"s": 1354,
"text": "Let us see a program to generate random long type numbers in Java −"
},
{
"code": null,
"e": 1433,
"s": 1422,
"text": " Live Demo"
},
{
"code": null,
"e": 1665,
"s": 1433,
"text": "import java.util.Random;\npublic class Example {\n public static void main(String[] args) {\n Random rd = new Random(); // creating Random object\n System.out.println(rd.nextLong()); // displaying a random long value\n }\n}"
},
{
"code": null,
"e": 1686,
"s": 1665,
"text": "-4787108556148621714"
},
{
"code": null,
"e": 1734,
"s": 1686,
"text": "Note - The output may vary on Online compilers."
}
]
|
C library function - iscntrl() | The C library function int iscntrl(int c) checks if the passed character is a control character.
According to standard ASCII character set, control characters are between ASCII codes 0x00 (NUL), 0x1f (US), and 0x7f (DEL). Specific compiler implementations for certain platforms may define additional control characters in the extended character set (above 0x7f).
Following is the declaration for iscntrl() function.
int iscntrl(int c);
c − This is the character to be checked.
c − This is the character to be checked.
This function returns non-zero value if c is a control character, else it returns 0.
The following example shows the usage of iscntrl() function.
#include <stdio.h>
#include <ctype.h>
int main () {
int i = 0, j = 0;
char str1[] = "all \a about \t programming";
char str2[] = "tutorials \n point";
/* Prints string till control character \a */
while( !iscntrl(str1[i]) ) {
putchar(str1[i]);
i++;
}
/* Prints string till control character \n */
while( !iscntrl(str2[j]) ) {
putchar(str2[j]);
j++;
}
return(0);
}
Let us compile and run the above program, to produce the following result −
all tutorials
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": 2104,
"s": 2007,
"text": "The C library function int iscntrl(int c) checks if the passed character is a control character."
},
{
"code": null,
"e": 2370,
"s": 2104,
"text": "According to standard ASCII character set, control characters are between ASCII codes 0x00 (NUL), 0x1f (US), and 0x7f (DEL). Specific compiler implementations for certain platforms may define additional control characters in the extended character set (above 0x7f)."
},
{
"code": null,
"e": 2423,
"s": 2370,
"text": "Following is the declaration for iscntrl() function."
},
{
"code": null,
"e": 2443,
"s": 2423,
"text": "int iscntrl(int c);"
},
{
"code": null,
"e": 2484,
"s": 2443,
"text": "c − This is the character to be checked."
},
{
"code": null,
"e": 2525,
"s": 2484,
"text": "c − This is the character to be checked."
},
{
"code": null,
"e": 2610,
"s": 2525,
"text": "This function returns non-zero value if c is a control character, else it returns 0."
},
{
"code": null,
"e": 2671,
"s": 2610,
"text": "The following example shows the usage of iscntrl() function."
},
{
"code": null,
"e": 3100,
"s": 2671,
"text": "#include <stdio.h>\n#include <ctype.h>\n\nint main () {\n int i = 0, j = 0;\n char str1[] = \"all \\a about \\t programming\";\n char str2[] = \"tutorials \\n point\";\n \n /* Prints string till control character \\a */\n while( !iscntrl(str1[i]) ) {\n putchar(str1[i]);\n i++;\n }\n \n /* Prints string till control character \\n */\n while( !iscntrl(str2[j]) ) {\n putchar(str2[j]);\n j++;\n }\n \n return(0);\n}"
},
{
"code": null,
"e": 3176,
"s": 3100,
"text": "Let us compile and run the above program, to produce the following result −"
},
{
"code": null,
"e": 3192,
"s": 3176,
"text": "all tutorials \n"
},
{
"code": null,
"e": 3225,
"s": 3192,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3240,
"s": 3225,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3275,
"s": 3240,
"text": "\n 12 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3290,
"s": 3275,
"text": " Nishant Malik"
},
{
"code": null,
"e": 3325,
"s": 3290,
"text": "\n 48 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 3339,
"s": 3325,
"text": " Asif Hussain"
},
{
"code": null,
"e": 3372,
"s": 3339,
"text": "\n 12 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3390,
"s": 3372,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 3425,
"s": 3390,
"text": "\n 20 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3444,
"s": 3425,
"text": " Vandana Annavaram"
},
{
"code": null,
"e": 3477,
"s": 3444,
"text": "\n 44 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3489,
"s": 3477,
"text": " Amit Diwan"
},
{
"code": null,
"e": 3496,
"s": 3489,
"text": " Print"
},
{
"code": null,
"e": 3507,
"s": 3496,
"text": " Add Notes"
}
]
|
How to create a Menu using JavaFX? | A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class.
While instantiating, you can pass the title of the menu as a parameter to its constructor. The Menu class contains an observable list that holds the contents of the menu (menu items).
The menu items are represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it.
To create a menu −
Instantiate the Menu class.
Instantiate the Menu class.
Create a required number of menu items by instantiating the MenuItem class.
Create a required number of menu items by instantiating the MenuItem class.
Add the created menu items to the observable list of the menu.
Add the created menu items to the observable list of the menu.
The javafx.scene.control.MenuBar class represents a menu bar that holds all the menus in a UI application.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MenuExample extends Application {
public void start(Stage stage) {
//Creating a menu
Menu fileMenu = new Menu("File");
//Creating menu Items
MenuItem item1 = new MenuItem("Add Files");
MenuItem item2 = new MenuItem("Start Converting");
MenuItem item3 = new MenuItem("Stop Converting");
MenuItem item4 = new MenuItem("Remove File");
MenuItem item5 = new MenuItem("Exit");
//Adding all the menu items to the menu
fileMenu.getItems().addAll(item1, item2, item3, item4, item5);
//Creating a menu bar and adding menu to it.
MenuBar menuBar = new MenuBar(fileMenu);
menuBar.setTranslateX(200);
menuBar.setTranslateY(20);
//Setting the stage
Group root = new Group(menuBar);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Menu Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
} | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class, you can create a menu by instantiating this class."
},
{
"code": null,
"e": 1432,
"s": 1248,
"text": "While instantiating, you can pass the title of the menu as a parameter to its constructor. The Menu class contains an observable list that holds the contents of the menu (menu items)."
},
{
"code": null,
"e": 1624,
"s": 1432,
"text": "The menu items are represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it."
},
{
"code": null,
"e": 1643,
"s": 1624,
"text": "To create a menu −"
},
{
"code": null,
"e": 1671,
"s": 1643,
"text": "Instantiate the Menu class."
},
{
"code": null,
"e": 1699,
"s": 1671,
"text": "Instantiate the Menu class."
},
{
"code": null,
"e": 1775,
"s": 1699,
"text": "Create a required number of menu items by instantiating the MenuItem class."
},
{
"code": null,
"e": 1851,
"s": 1775,
"text": "Create a required number of menu items by instantiating the MenuItem class."
},
{
"code": null,
"e": 1914,
"s": 1851,
"text": "Add the created menu items to the observable list of the menu."
},
{
"code": null,
"e": 1977,
"s": 1914,
"text": "Add the created menu items to the observable list of the menu."
},
{
"code": null,
"e": 2084,
"s": 1977,
"text": "The javafx.scene.control.MenuBar class represents a menu bar that holds all the menus in a UI application."
},
{
"code": null,
"e": 3348,
"s": 2084,
"text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Menu;\nimport javafx.scene.control.MenuBar;\nimport javafx.scene.control.MenuItem;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class MenuExample extends Application {\n public void start(Stage stage) {\n //Creating a menu\n Menu fileMenu = new Menu(\"File\");\n //Creating menu Items\n MenuItem item1 = new MenuItem(\"Add Files\");\n MenuItem item2 = new MenuItem(\"Start Converting\");\n MenuItem item3 = new MenuItem(\"Stop Converting\");\n MenuItem item4 = new MenuItem(\"Remove File\");\n MenuItem item5 = new MenuItem(\"Exit\");\n //Adding all the menu items to the menu\n fileMenu.getItems().addAll(item1, item2, item3, item4, item5);\n //Creating a menu bar and adding menu to it.\n MenuBar menuBar = new MenuBar(fileMenu);\n menuBar.setTranslateX(200);\n menuBar.setTranslateY(20);\n //Setting the stage\n Group root = new Group(menuBar);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Menu Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
]
|
Angular Material - Typography | Angular Material provides various typography CSS classes which can be used to create visual consistency across Angular JS application.
The following table lists down the different classes with their description.
md-display-1
Shows the text with Regular 34px.
md-display-2
Shows the text with Regular 45px.
md-display-3
Shows the text with Regular 56px.
md-display-4
Shows the text with Light 112px.
md-headline
Shows the text with Regular 24px.
md-title
Shows the text with Medium 20px.
md-subhead
Shows the text with Regular 16px.
md-body-1
Shows the text with Regular 14px.
md-body-2
Shows the text with Medium 14px.
md-button
Shows the button with Medium 14px.
md-caption
Shows the text with Regular 12px.
The following example shows the use of typography CSS classes.
am_typography.htm
<html lang = "en">
<head>
<link rel = "stylesheet"
href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
<link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
<script language = "javascript">
angular
.module('firstApplication', ['ngMaterial'])
.controller('typographyController', typographyController);
function typographyController ($scope) {
}
</script>
</head>
<body ng-app = "firstApplication">
<div class = "frameContainer" ng-controller = "typographyController as ctrl"
layout = "column" layout-padding layout-wrap layout-fill
style = "padding-bottom: 32px;" ng-cloak>
<p class = "md-display-4">.md-display-4</p>
<p class = "md-display-3">.md-display-3</p>
<p class = "md-display-2">.md-display-2</p>
<p class = "md-display-1">.md-display-1</p>
<p class = "md-headline">.md-headline</p>
<p class = "md-title">.md-title</p>
<p class = "md-subhead">.md-subhead</p>
<p class = "md-body-1">.md-body-1</p>
<p class = "md-body-2">.md-body-2</p>
<md-button>.md-button</md-button>
<p class = "md-caption">.md-caption</p>
</div>
</body>
</html>
Verify the result.
.md-display-4
.md-display-3
.md-display-2
.md-display-1
.md-headline
.md-title
.md-subhead
.md-body-1
.md-body-2
.md-caption
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2325,
"s": 2190,
"text": "Angular Material provides various typography CSS classes which can be used to create visual consistency across Angular JS application."
},
{
"code": null,
"e": 2402,
"s": 2325,
"text": "The following table lists down the different classes with their description."
},
{
"code": null,
"e": 2415,
"s": 2402,
"text": "md-display-1"
},
{
"code": null,
"e": 2449,
"s": 2415,
"text": "Shows the text with Regular 34px."
},
{
"code": null,
"e": 2462,
"s": 2449,
"text": "md-display-2"
},
{
"code": null,
"e": 2496,
"s": 2462,
"text": "Shows the text with Regular 45px."
},
{
"code": null,
"e": 2509,
"s": 2496,
"text": "md-display-3"
},
{
"code": null,
"e": 2543,
"s": 2509,
"text": "Shows the text with Regular 56px."
},
{
"code": null,
"e": 2556,
"s": 2543,
"text": "md-display-4"
},
{
"code": null,
"e": 2589,
"s": 2556,
"text": "Shows the text with Light 112px."
},
{
"code": null,
"e": 2601,
"s": 2589,
"text": "md-headline"
},
{
"code": null,
"e": 2635,
"s": 2601,
"text": "Shows the text with Regular 24px."
},
{
"code": null,
"e": 2644,
"s": 2635,
"text": "md-title"
},
{
"code": null,
"e": 2677,
"s": 2644,
"text": "Shows the text with Medium 20px."
},
{
"code": null,
"e": 2688,
"s": 2677,
"text": "md-subhead"
},
{
"code": null,
"e": 2722,
"s": 2688,
"text": "Shows the text with Regular 16px."
},
{
"code": null,
"e": 2732,
"s": 2722,
"text": "md-body-1"
},
{
"code": null,
"e": 2766,
"s": 2732,
"text": "Shows the text with Regular 14px."
},
{
"code": null,
"e": 2776,
"s": 2766,
"text": "md-body-2"
},
{
"code": null,
"e": 2809,
"s": 2776,
"text": "Shows the text with Medium 14px."
},
{
"code": null,
"e": 2819,
"s": 2809,
"text": "md-button"
},
{
"code": null,
"e": 2854,
"s": 2819,
"text": "Shows the button with Medium 14px."
},
{
"code": null,
"e": 2865,
"s": 2854,
"text": "md-caption"
},
{
"code": null,
"e": 2899,
"s": 2865,
"text": "Shows the text with Regular 12px."
},
{
"code": null,
"e": 2962,
"s": 2899,
"text": "The following example shows the use of typography CSS classes."
},
{
"code": null,
"e": 2980,
"s": 2962,
"text": "am_typography.htm"
},
{
"code": null,
"e": 4917,
"s": 2980,
"text": "<html lang = \"en\">\n <head>\n <link rel = \"stylesheet\"\n href = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js\"></script>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js\"></script>\n <link rel = \"stylesheet\" href = \"https://fonts.googleapis.com/icon?family=Material+Icons\">\n \n <script language = \"javascript\">\n angular\n .module('firstApplication', ['ngMaterial'])\n .controller('typographyController', typographyController);\n \n function typographyController ($scope) { \n }\t \n </script> \n </head>\n \n <body ng-app = \"firstApplication\"> \n <div class = \"frameContainer\" ng-controller = \"typographyController as ctrl\"\n layout = \"column\" layout-padding layout-wrap layout-fill\n style = \"padding-bottom: 32px;\" ng-cloak>\n <p class = \"md-display-4\">.md-display-4</p>\n <p class = \"md-display-3\">.md-display-3</p>\n <p class = \"md-display-2\">.md-display-2</p>\n <p class = \"md-display-1\">.md-display-1</p>\n <p class = \"md-headline\">.md-headline</p>\n <p class = \"md-title\">.md-title</p>\n <p class = \"md-subhead\">.md-subhead</p>\n <p class = \"md-body-1\">.md-body-1</p>\n <p class = \"md-body-2\">.md-body-2</p>\n <md-button>.md-button</md-button>\n <p class = \"md-caption\">.md-caption</p>\n </div>\n </body>\n</html>"
},
{
"code": null,
"e": 4936,
"s": 4917,
"text": "Verify the result."
},
{
"code": null,
"e": 4950,
"s": 4936,
"text": ".md-display-4"
},
{
"code": null,
"e": 4964,
"s": 4950,
"text": ".md-display-3"
},
{
"code": null,
"e": 4978,
"s": 4964,
"text": ".md-display-2"
},
{
"code": null,
"e": 4992,
"s": 4978,
"text": ".md-display-1"
},
{
"code": null,
"e": 5005,
"s": 4992,
"text": ".md-headline"
},
{
"code": null,
"e": 5015,
"s": 5005,
"text": ".md-title"
},
{
"code": null,
"e": 5027,
"s": 5015,
"text": ".md-subhead"
},
{
"code": null,
"e": 5038,
"s": 5027,
"text": ".md-body-1"
},
{
"code": null,
"e": 5049,
"s": 5038,
"text": ".md-body-2"
},
{
"code": null,
"e": 5061,
"s": 5049,
"text": ".md-caption"
},
{
"code": null,
"e": 5096,
"s": 5061,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5110,
"s": 5096,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5145,
"s": 5110,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5159,
"s": 5145,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5194,
"s": 5159,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 5214,
"s": 5194,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 5249,
"s": 5214,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5266,
"s": 5249,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5299,
"s": 5266,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5311,
"s": 5299,
"text": " Senol Atac"
},
{
"code": null,
"e": 5346,
"s": 5311,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5358,
"s": 5346,
"text": " Senol Atac"
},
{
"code": null,
"e": 5365,
"s": 5358,
"text": " Print"
},
{
"code": null,
"e": 5376,
"s": 5365,
"text": " Add Notes"
}
]
|
OpenCV - Color Maps | In OpenCV, you can apply different color maps to an image using the method applyColorMap() of the class Imgproc. Following is the syntax of this method −
applyColorMap(Mat src, Mat dst, int colormap)
It accepts three 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 − An object of the class Mat representing the destination (output) image.
dst − An object of the class Mat representing the destination (output) image.
colormap − A variable of integer type representing the type of the color map to be applied.
colormap − A variable of integer type representing the type of the color map to be applied.
The following program demonstrates how to apply color map to an image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class ColorMapTest {
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/chap25/color_input.jpg";
Mat src = Imgcodecs.imread(file);
// Creating an empty matrix to store the result
Mat dst = new Mat();
// Applying color map to an image
Imgproc.applyColorMap(src, dst, Imgproc.COLORMAP_HOT);
// Writing the image
Imgcodecs.imwrite("E:/OpenCV/chap25/colormap_hot.jpg", dst);
System.out.println("Image processed");
}
}
Assume that following is the input image color_input.jpg specified in the above program.
On executing the above 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 COLORMAP_HOT demonstrated in the previous example, OpenCV caters various other types of color maps. All these types are represented by predefined static fields (fixed values) of Imgproc class.
You can choose the type of the colormap you need, by passing its respective predefined value to the parameter named colormap of the applyColorMap() method.
Imgproc.applyColorMap(src, dst, Imgproc.COLORMAP_HOT);
Following are the values representing various types of color maps 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": 3158,
"s": 3004,
"text": "In OpenCV, you can apply different color maps to an image using the method applyColorMap() of the class Imgproc. Following is the syntax of this method −"
},
{
"code": null,
"e": 3205,
"s": 3158,
"text": "applyColorMap(Mat src, Mat dst, int colormap)\n"
},
{
"code": null,
"e": 3235,
"s": 3205,
"text": "It accepts three parameters −"
},
{
"code": null,
"e": 3307,
"s": 3235,
"text": "src − An object of the class Mat representing the source (input) image."
},
{
"code": null,
"e": 3379,
"s": 3307,
"text": "src − An object of the class Mat representing the source (input) image."
},
{
"code": null,
"e": 3457,
"s": 3379,
"text": "dst − An object of the class Mat representing the destination (output) image."
},
{
"code": null,
"e": 3535,
"s": 3457,
"text": "dst − An object of the class Mat representing the destination (output) image."
},
{
"code": null,
"e": 3627,
"s": 3535,
"text": "colormap − A variable of integer type representing the type of the color map to be applied."
},
{
"code": null,
"e": 3719,
"s": 3627,
"text": "colormap − A variable of integer type representing the type of the color map to be applied."
},
{
"code": null,
"e": 3790,
"s": 3719,
"text": "The following program demonstrates how to apply color map to an image."
},
{
"code": null,
"e": 4593,
"s": 3790,
"text": "import org.opencv.core.Core;\nimport org.opencv.core.Mat;\n\nimport org.opencv.imgcodecs.Imgcodecs;\nimport org.opencv.imgproc.Imgproc;\n\npublic class ColorMapTest {\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/chap25/color_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 // Applying color map to an image\n Imgproc.applyColorMap(src, dst, Imgproc.COLORMAP_HOT);\n\n // Writing the image\n Imgcodecs.imwrite(\"E:/OpenCV/chap25/colormap_hot.jpg\", dst);\n System.out.println(\"Image processed\");\n }\n}"
},
{
"code": null,
"e": 4682,
"s": 4593,
"text": "Assume that following is the input image color_input.jpg specified in the above program."
},
{
"code": null,
"e": 4750,
"s": 4682,
"text": "On executing the above program, you will get the following output −"
},
{
"code": null,
"e": 4767,
"s": 4750,
"text": "Image Processed\n"
},
{
"code": null,
"e": 4845,
"s": 4767,
"text": "If you open the specified path, you can observe the output image as follows −"
},
{
"code": null,
"e": 5053,
"s": 4845,
"text": "In addition to COLORMAP_HOT demonstrated in the previous example, OpenCV caters various other types of color maps. All these types are represented by predefined static fields (fixed values) of Imgproc class."
},
{
"code": null,
"e": 5209,
"s": 5053,
"text": "You can choose the type of the colormap you need, by passing its respective predefined value to the parameter named colormap of the applyColorMap() method."
},
{
"code": null,
"e": 5265,
"s": 5209,
"text": "Imgproc.applyColorMap(src, dst, Imgproc.COLORMAP_HOT);\n"
},
{
"code": null,
"e": 5361,
"s": 5265,
"text": "Following are the values representing various types of color maps and their respective outputs."
},
{
"code": null,
"e": 5394,
"s": 5361,
"text": "\n 70 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 5411,
"s": 5394,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5444,
"s": 5411,
"text": "\n 41 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5461,
"s": 5444,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5494,
"s": 5461,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5508,
"s": 5494,
"text": " Spotle Learn"
},
{
"code": null,
"e": 5540,
"s": 5508,
"text": "\n 12 Lectures \n 46 mins\n"
},
{
"code": null,
"e": 5557,
"s": 5540,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 5590,
"s": 5557,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5605,
"s": 5590,
"text": " Haithem Gasmi"
},
{
"code": null,
"e": 5640,
"s": 5605,
"text": "\n 67 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 5658,
"s": 5640,
"text": " Gianluca Mottola"
},
{
"code": null,
"e": 5665,
"s": 5658,
"text": " Print"
},
{
"code": null,
"e": 5676,
"s": 5665,
"text": " Add Notes"
}
]
|
How to limit input text length using CSS3? | With HTML, you can easily limit input length. However, with CSS3, it will not be possible, since CSS can’t be used to limit the number of input characters. This will cause a functional restriction.
CSS deals with presentation i.e. how your web page will look. This is done with HTML attribute malength, since it’s for behavior.
Let’s see how to do it in HTML −
You can try to run the following code to limit input text length
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML maxlength attribute</title>
</head>
<body>
<form action="">
Student Name<br><input type="text" name="name" maxlength="20"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html> | [
{
"code": null,
"e": 1260,
"s": 1062,
"text": "With HTML, you can easily limit input length. However, with CSS3, it will not be possible, since CSS can’t be used to limit the number of input characters. This will cause a functional restriction."
},
{
"code": null,
"e": 1390,
"s": 1260,
"text": "CSS deals with presentation i.e. how your web page will look. This is done with HTML attribute malength, since it’s for behavior."
},
{
"code": null,
"e": 1423,
"s": 1390,
"text": "Let’s see how to do it in HTML −"
},
{
"code": null,
"e": 1488,
"s": 1423,
"text": "You can try to run the following code to limit input text length"
},
{
"code": null,
"e": 1498,
"s": 1488,
"text": "Live Demo"
},
{
"code": null,
"e": 1780,
"s": 1498,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML maxlength attribute</title>\n </head>\n <body>\n <form action=\"\">\n Student Name<br><input type=\"text\" name=\"name\" maxlength=\"20\"><br><br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>"
}
]
|
DAX Aggregation - COUNTROWS function | Counts the number of rows in the specified table, or in a table defined by an expression.
COUNTROWS (<table>)
table
The name of the table that contains the rows to be counted, or an expression that returns a table.
Returns a whole number.
This function can be used to count the number of rows in a base table, but more often is used to count the number of rows that result from filtering a table, or applying a context to a table.
= COUNTROWS (CALENDAR (DATE (2016,8,1), DATE (2016,10,31))) returns 92.
= COUNTROWS (Results) returns 34094.
= COUNTROWS (Events) returns 995.
You can use columns containing any type of data, but only blank cells are counted. Cells that have the value zero (0) are not counted, as zero is considered a numeric value and not a blank.
= COUNTBLANK (SalesTarget[SalesTarget])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2091,
"s": 2001,
"text": "Counts the number of rows in the specified table, or in a table defined by an expression."
},
{
"code": null,
"e": 2113,
"s": 2091,
"text": "COUNTROWS (<table>) \n"
},
{
"code": null,
"e": 2119,
"s": 2113,
"text": "table"
},
{
"code": null,
"e": 2218,
"s": 2119,
"text": "The name of the table that contains the rows to be counted, or an expression that returns a table."
},
{
"code": null,
"e": 2242,
"s": 2218,
"text": "Returns a whole number."
},
{
"code": null,
"e": 2434,
"s": 2242,
"text": "This function can be used to count the number of rows in a base table, but more often is used to count the number of rows that result from filtering a table, or applying a context to a table."
},
{
"code": null,
"e": 2580,
"s": 2434,
"text": "= COUNTROWS (CALENDAR (DATE (2016,8,1), DATE (2016,10,31))) returns 92. \n= COUNTROWS (Results) returns 34094. \n= COUNTROWS (Events) returns 995. "
},
{
"code": null,
"e": 2770,
"s": 2580,
"text": "You can use columns containing any type of data, but only blank cells are counted. Cells that have the value zero (0) are not counted, as zero is considered a numeric value and not a blank."
},
{
"code": null,
"e": 2810,
"s": 2770,
"text": "= COUNTBLANK (SalesTarget[SalesTarget])"
},
{
"code": null,
"e": 2845,
"s": 2810,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 2859,
"s": 2845,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 2892,
"s": 2859,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 2906,
"s": 2892,
"text": " Randy Minder"
},
{
"code": null,
"e": 2941,
"s": 2906,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 2955,
"s": 2941,
"text": " Randy Minder"
},
{
"code": null,
"e": 2962,
"s": 2955,
"text": " Print"
},
{
"code": null,
"e": 2973,
"s": 2962,
"text": " Add Notes"
}
]
|
Health Management System using Python - GeeksforGeeks | 18 Jul, 2021
Sometimes we are so busy that we are not even able to care for our body and by caring we mean fitness, food, exercises and much more, and then we think that we need to make our diet plan or exercise plan to maintain our body. So let’s make a Python script to maintain this record for us. In this program, we add our diet and exercises that we need to do, or we can save our daily diet or exercise with date and time to keep records. It also helps us to make another fitness plan.
In this program, user input their diet and exercise, and then we save the input with the date and time, so whenever the user wants they can see their routine. Following operations will be performed under this:
getdate()
selectname()
select_file_action()
select_task()
action()
Approach:
getdate(): Tracks date for data so that log retrieval can make sense
Python3
def getdate(): # to get date and time return datetime.datetime.now()
selectname(): This function lets the user select the person on which the required tasks are to be performed. This function first gives options to choose between two people and takes the input as an integer. This is then returned for further processing.
Python3
def selectname(): name = {1: "Nilesh", 2: "Shanu"} b = {1: "Food", 2: "Exercise"} for key, value in name.items(): # taking input of name print("Press", key, "for", value, "\n", end="") n = int(input("type here..")) if n > 2: print("error select 1 or 2") exit() else: return n
select_file_action(): This function accepts what should be done to the file i.e. either the file should be used to write the data (log) or retrieve the existing data. This again takes integer arguments and returns them.
Python3
def select_file_action(): a = {1: "Log", 2: "Retrieve"} for key, value in a.items(): # taking input of function that user wants to # do (either log or retrieve) print("Press", key, "for", value, "\n", end="") x = int(input("type here..")) if x > 2: print("error select 1 or 2") exit() else: return x
select_task(): This function helps specify data related to what task has to be entered. The choice here given is between food and exercise. This again accepts integer input and returns it for further processing.
Python3
def select_task(): b = {1: "Food", 2: "Exercise"} for key, value in b.items(): # ask user to choose between food and exercise print("Press", key, "for", value, "\n", end="") y = int(input("type here..")) if y > 2: print("error select 1 or 2") exit() else: return y
action(): Performs appropriate task according to the inputs returned by above functions by condition checking.
Python3
def action(n, x, y): # condition no 1 if n == 1 and x == 1 and y == 1: value = input("type here\n") with open("nilesh food.txt", "a") as nileshfood: # printing date and time nileshfood.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition no 2 elif n == 1 and x == 1 and y == 2: value = input("type here\n") # printing date and time with open("nilesh exercise.txt", "a") as nileshexercise: # printing date and time nileshexercise.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition 3 elif n == 2 and x == 1 and y == 1: value = input("type here\n") # printing date and time with open("shanu food.txt", "a") as shanufood: # printing date and time shanufood.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition 4 elif n == 2 and x == 1 and y == 2: value = input("type here\n") # printing date and time with open("shanu exercise.txt", "a") as shanuexercise: # printing date and time shanuexercise.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition 5 elif n == 1 and x == 2 and y == 1: # printing date and time with open("nilesh food.txt", "r") as nileshfood: a = nileshfood.read() print(a) # condition no 6 elif n == 1 and x == 2 and y == 2: # printing date and time with open("nilesh exercise.txt", "r") as nileshexercise: a = nileshexercise.read() print(a) # condition no 7 elif n == 2 and x == 2 and y == 1: # printing date and time with open("shanu food.txt", "r") as shanufood: a = shanufood.read() print(a) # condition no 8 elif n == 2 and x == 2 and y == 2: # printing date and time with open("shanu exercise.txt", "r") as shanuexercise: a = shanuexercise.read() print(a)
Below is a complete implementation.
Python
import datetime def getdate(): # to get date and time return datetime.datetime.now() def selectname(): name = {1: "Nilesh", 2: "Shanu"} b = {1: "Food", 2: "Exercise"} for key, value in name.items(): # taking input of name print("Press", key, "for", value, "\n", end="") n = int(input("type here..")) if n > 2: print("error select 1 or 2") exit() else: return n def select_file_action(): a = {1: "Log", 2: "Retrieve"} for key, value in a.items(): # taking input of function that user wants to # do (either log or retrieve) print("Press", key, "for", value, "\n", end="") x = int(input("type here..")) if x > 2: print("error select 1 or 2") exit() else: return x def select_task(): b = {1: "Food", 2: "Exercise"} for key, value in b.items(): # ask user to choose between food # and exercise print("Press", key, "for", value, "\n", end="") y = int(input("type here..")) if y > 2: print("error select 1 or 2") exit() else: return y def action(n, x, y): # condition no 1 if n == 1 and x == 1 and y == 1: value = input("type here\n") with open("nilesh food.txt", "a") as nileshfood: # printing date and time nileshfood.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition no 2 elif n == 1 and x == 1 and y == 2: value = input("type here\n") # printing date and time with open("nilesh exercise.txt", "a") as nileshexercise: # printing date and time nileshexercise.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition 3 elif n == 2 and x == 1 and y == 1: value = input("type here\n") # printing date and time with open("shanu food.txt", "a") as shanufood: # printing date and time shanufood.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition 4 elif n == 2 and x == 1 and y == 2: value = input("type here\n") # printing date and time with open("shanu exercise.txt", "a") as shanuexercise: # printing date and time shanuexercise.write(str([str(getdate())]) + ": " + value + "\n") print("successfully written") # condition 5 elif n == 1 and x == 2 and y == 1: # printing date and time with open("nilesh food.txt", "r") as nileshfood: a = nileshfood.read() print(a) # condition no 6 elif n == 1 and x == 2 and y == 2: # printing date and time with open("nilesh exercise.txt", "r") as nileshexercise: a = nileshexercise.read() print(a) # condition no 7 elif n == 2 and x == 2 and y == 1: # printing date and time with open("shanu food.txt", "r") as shanufood: a = shanufood.read() print(a) # condition no 8 elif n == 2 and x == 2 and y == 2: # printing date and time with open("shanu exercise.txt", "r") as shanuexercise: a = shanuexercise.read() print(a) n = selectname()x = select_file_action()y = select_task()action(n, x, y)
Output:
school-programming
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24316,
"s": 24288,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 24796,
"s": 24316,
"text": "Sometimes we are so busy that we are not even able to care for our body and by caring we mean fitness, food, exercises and much more, and then we think that we need to make our diet plan or exercise plan to maintain our body. So let’s make a Python script to maintain this record for us. In this program, we add our diet and exercises that we need to do, or we can save our daily diet or exercise with date and time to keep records. It also helps us to make another fitness plan."
},
{
"code": null,
"e": 25006,
"s": 24796,
"text": "In this program, user input their diet and exercise, and then we save the input with the date and time, so whenever the user wants they can see their routine. Following operations will be performed under this:"
},
{
"code": null,
"e": 25016,
"s": 25006,
"text": "getdate()"
},
{
"code": null,
"e": 25029,
"s": 25016,
"text": "selectname()"
},
{
"code": null,
"e": 25050,
"s": 25029,
"text": "select_file_action()"
},
{
"code": null,
"e": 25064,
"s": 25050,
"text": "select_task()"
},
{
"code": null,
"e": 25073,
"s": 25064,
"text": "action()"
},
{
"code": null,
"e": 25083,
"s": 25073,
"text": "Approach:"
},
{
"code": null,
"e": 25152,
"s": 25083,
"text": "getdate(): Tracks date for data so that log retrieval can make sense"
},
{
"code": null,
"e": 25160,
"s": 25152,
"text": "Python3"
},
{
"code": "def getdate(): # to get date and time return datetime.datetime.now()",
"e": 25239,
"s": 25160,
"text": null
},
{
"code": null,
"e": 25492,
"s": 25239,
"text": "selectname(): This function lets the user select the person on which the required tasks are to be performed. This function first gives options to choose between two people and takes the input as an integer. This is then returned for further processing."
},
{
"code": null,
"e": 25500,
"s": 25492,
"text": "Python3"
},
{
"code": "def selectname(): name = {1: \"Nilesh\", 2: \"Shanu\"} b = {1: \"Food\", 2: \"Exercise\"} for key, value in name.items(): # taking input of name print(\"Press\", key, \"for\", value, \"\\n\", end=\"\") n = int(input(\"type here..\")) if n > 2: print(\"error select 1 or 2\") exit() else: return n",
"e": 25839,
"s": 25500,
"text": null
},
{
"code": null,
"e": 26059,
"s": 25839,
"text": "select_file_action(): This function accepts what should be done to the file i.e. either the file should be used to write the data (log) or retrieve the existing data. This again takes integer arguments and returns them."
},
{
"code": null,
"e": 26067,
"s": 26059,
"text": "Python3"
},
{
"code": "def select_file_action(): a = {1: \"Log\", 2: \"Retrieve\"} for key, value in a.items(): # taking input of function that user wants to # do (either log or retrieve) print(\"Press\", key, \"for\", value, \"\\n\", end=\"\") x = int(input(\"type here..\")) if x > 2: print(\"error select 1 or 2\") exit() else: return x",
"e": 26430,
"s": 26067,
"text": null
},
{
"code": null,
"e": 26642,
"s": 26430,
"text": "select_task(): This function helps specify data related to what task has to be entered. The choice here given is between food and exercise. This again accepts integer input and returns it for further processing."
},
{
"code": null,
"e": 26650,
"s": 26642,
"text": "Python3"
},
{
"code": "def select_task(): b = {1: \"Food\", 2: \"Exercise\"} for key, value in b.items(): # ask user to choose between food and exercise print(\"Press\", key, \"for\", value, \"\\n\", end=\"\") y = int(input(\"type here..\")) if y > 2: print(\"error select 1 or 2\") exit() else: return y",
"e": 26973,
"s": 26650,
"text": null
},
{
"code": null,
"e": 27084,
"s": 26973,
"text": "action(): Performs appropriate task according to the inputs returned by above functions by condition checking."
},
{
"code": null,
"e": 27092,
"s": 27084,
"text": "Python3"
},
{
"code": "def action(n, x, y): # condition no 1 if n == 1 and x == 1 and y == 1: value = input(\"type here\\n\") with open(\"nilesh food.txt\", \"a\") as nileshfood: # printing date and time nileshfood.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition no 2 elif n == 1 and x == 1 and y == 2: value = input(\"type here\\n\") # printing date and time with open(\"nilesh exercise.txt\", \"a\") as nileshexercise: # printing date and time nileshexercise.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition 3 elif n == 2 and x == 1 and y == 1: value = input(\"type here\\n\") # printing date and time with open(\"shanu food.txt\", \"a\") as shanufood: # printing date and time shanufood.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition 4 elif n == 2 and x == 1 and y == 2: value = input(\"type here\\n\") # printing date and time with open(\"shanu exercise.txt\", \"a\") as shanuexercise: # printing date and time shanuexercise.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition 5 elif n == 1 and x == 2 and y == 1: # printing date and time with open(\"nilesh food.txt\", \"r\") as nileshfood: a = nileshfood.read() print(a) # condition no 6 elif n == 1 and x == 2 and y == 2: # printing date and time with open(\"nilesh exercise.txt\", \"r\") as nileshexercise: a = nileshexercise.read() print(a) # condition no 7 elif n == 2 and x == 2 and y == 1: # printing date and time with open(\"shanu food.txt\", \"r\") as shanufood: a = shanufood.read() print(a) # condition no 8 elif n == 2 and x == 2 and y == 2: # printing date and time with open(\"shanu exercise.txt\", \"r\") as shanuexercise: a = shanuexercise.read() print(a)",
"e": 29300,
"s": 27092,
"text": null
},
{
"code": null,
"e": 29336,
"s": 29300,
"text": "Below is a complete implementation."
},
{
"code": null,
"e": 29343,
"s": 29336,
"text": "Python"
},
{
"code": "import datetime def getdate(): # to get date and time return datetime.datetime.now() def selectname(): name = {1: \"Nilesh\", 2: \"Shanu\"} b = {1: \"Food\", 2: \"Exercise\"} for key, value in name.items(): # taking input of name print(\"Press\", key, \"for\", value, \"\\n\", end=\"\") n = int(input(\"type here..\")) if n > 2: print(\"error select 1 or 2\") exit() else: return n def select_file_action(): a = {1: \"Log\", 2: \"Retrieve\"} for key, value in a.items(): # taking input of function that user wants to # do (either log or retrieve) print(\"Press\", key, \"for\", value, \"\\n\", end=\"\") x = int(input(\"type here..\")) if x > 2: print(\"error select 1 or 2\") exit() else: return x def select_task(): b = {1: \"Food\", 2: \"Exercise\"} for key, value in b.items(): # ask user to choose between food # and exercise print(\"Press\", key, \"for\", value, \"\\n\", end=\"\") y = int(input(\"type here..\")) if y > 2: print(\"error select 1 or 2\") exit() else: return y def action(n, x, y): # condition no 1 if n == 1 and x == 1 and y == 1: value = input(\"type here\\n\") with open(\"nilesh food.txt\", \"a\") as nileshfood: # printing date and time nileshfood.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition no 2 elif n == 1 and x == 1 and y == 2: value = input(\"type here\\n\") # printing date and time with open(\"nilesh exercise.txt\", \"a\") as nileshexercise: # printing date and time nileshexercise.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition 3 elif n == 2 and x == 1 and y == 1: value = input(\"type here\\n\") # printing date and time with open(\"shanu food.txt\", \"a\") as shanufood: # printing date and time shanufood.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition 4 elif n == 2 and x == 1 and y == 2: value = input(\"type here\\n\") # printing date and time with open(\"shanu exercise.txt\", \"a\") as shanuexercise: # printing date and time shanuexercise.write(str([str(getdate())]) + \": \" + value + \"\\n\") print(\"successfully written\") # condition 5 elif n == 1 and x == 2 and y == 1: # printing date and time with open(\"nilesh food.txt\", \"r\") as nileshfood: a = nileshfood.read() print(a) # condition no 6 elif n == 1 and x == 2 and y == 2: # printing date and time with open(\"nilesh exercise.txt\", \"r\") as nileshexercise: a = nileshexercise.read() print(a) # condition no 7 elif n == 2 and x == 2 and y == 1: # printing date and time with open(\"shanu food.txt\", \"r\") as shanufood: a = shanufood.read() print(a) # condition no 8 elif n == 2 and x == 2 and y == 2: # printing date and time with open(\"shanu exercise.txt\", \"r\") as shanuexercise: a = shanuexercise.read() print(a) n = selectname()x = select_file_action()y = select_task()action(n, x, y)",
"e": 32790,
"s": 29343,
"text": null
},
{
"code": null,
"e": 32798,
"s": 32790,
"text": "Output:"
},
{
"code": null,
"e": 32817,
"s": 32798,
"text": "school-programming"
},
{
"code": null,
"e": 32824,
"s": 32817,
"text": "Python"
},
{
"code": null,
"e": 32922,
"s": 32824,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32954,
"s": 32922,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32996,
"s": 32954,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 33052,
"s": 32996,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 33094,
"s": 33052,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 33125,
"s": 33094,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 33180,
"s": 33125,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 33202,
"s": 33180,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 33241,
"s": 33202,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 33270,
"s": 33241,
"text": "Create a directory in Python"
}
]
|
Bash Scripting - Bash Echo Command - GeeksforGeeks | 22 Nov, 2021
In this article, we are going to see the echo command. The Echo command is a built-in command feature for Unix / Linux which is generally used to display the text or message on the screen.
Syntax :
$ echo [option]
For Example :
$ echo Geeks For Geeks
Output :
Geeks For Geeks
Output
-n: It does not print the trailing newline.
-E: It is the default option that disables the implementation of escape sequences.
-e: It is used to enable interpretation of backslash escapes
There are some escape sequences performing different operations such as:
Example 1 :
$ echo -e "Geeks \bFor \bGeeks"
Output:
GeeksForGeeks
Output
Example 2 :
$ echo -e "Geeks\nFor\nGeeks"
Output :
Geeks
For
Geeks
Output
Example 3 :
$ echo -e "Geeks\tFor\tGeeks"
Output :
Geeks For Geeks
Output
Example 4 :
$ echo -e "Geeks\\For\\Geeks"
Output :
Geeks\For\Geeks
Output
Example 5 :
$ echo -e "Geeks\rFor Geeks"
Output :
For Geeks
Output
Example 6 :
$ echo -e "Geeks\v For\v Geeks"
Output :
Geeks For Geeks
Output
Example 7 :
$ echo -n "Geeks For Geeks"
Output :
Geeks For Geeks
Output
You can find all the commands related to echo by writing the following command.
$ /bin/echo --help
Output :
Output
We create a text file named ” userInput.sh ” and write the following code inside the file.
#!/bin/sh
echo "Enter Your Name : "
read name #It take input from user
echo "Hello, $name. Welcome to GeeksForGeeks"
Now run the ” userInput.sh ” with the help of the below code:
$ chmod +x ./userInput.sh
$ ./userInput.sh
Output :
Output
Bash-Script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
Conditional Statements | Shell Script
Tail command in Linux with examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
tee command in Linux with examples | [
{
"code": null,
"e": 24100,
"s": 24072,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 24289,
"s": 24100,
"text": "In this article, we are going to see the echo command. The Echo command is a built-in command feature for Unix / Linux which is generally used to display the text or message on the screen."
},
{
"code": null,
"e": 24298,
"s": 24289,
"text": "Syntax :"
},
{
"code": null,
"e": 24314,
"s": 24298,
"text": "$ echo [option]"
},
{
"code": null,
"e": 24328,
"s": 24314,
"text": "For Example :"
},
{
"code": null,
"e": 24351,
"s": 24328,
"text": "$ echo Geeks For Geeks"
},
{
"code": null,
"e": 24360,
"s": 24351,
"text": "Output :"
},
{
"code": null,
"e": 24376,
"s": 24360,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 24383,
"s": 24376,
"text": "Output"
},
{
"code": null,
"e": 24427,
"s": 24383,
"text": "-n: It does not print the trailing newline."
},
{
"code": null,
"e": 24510,
"s": 24427,
"text": "-E: It is the default option that disables the implementation of escape sequences."
},
{
"code": null,
"e": 24571,
"s": 24510,
"text": "-e: It is used to enable interpretation of backslash escapes"
},
{
"code": null,
"e": 24644,
"s": 24571,
"text": "There are some escape sequences performing different operations such as:"
},
{
"code": null,
"e": 24656,
"s": 24644,
"text": "Example 1 :"
},
{
"code": null,
"e": 24688,
"s": 24656,
"text": "$ echo -e \"Geeks \\bFor \\bGeeks\""
},
{
"code": null,
"e": 24696,
"s": 24688,
"text": "Output:"
},
{
"code": null,
"e": 24710,
"s": 24696,
"text": "GeeksForGeeks"
},
{
"code": null,
"e": 24717,
"s": 24710,
"text": "Output"
},
{
"code": null,
"e": 24729,
"s": 24717,
"text": "Example 2 :"
},
{
"code": null,
"e": 24759,
"s": 24729,
"text": "$ echo -e \"Geeks\\nFor\\nGeeks\""
},
{
"code": null,
"e": 24768,
"s": 24759,
"text": "Output :"
},
{
"code": null,
"e": 24786,
"s": 24768,
"text": "Geeks\nFor \nGeeks"
},
{
"code": null,
"e": 24793,
"s": 24786,
"text": "Output"
},
{
"code": null,
"e": 24805,
"s": 24793,
"text": "Example 3 :"
},
{
"code": null,
"e": 24835,
"s": 24805,
"text": "$ echo -e \"Geeks\\tFor\\tGeeks\""
},
{
"code": null,
"e": 24844,
"s": 24835,
"text": "Output :"
},
{
"code": null,
"e": 24866,
"s": 24844,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 24873,
"s": 24866,
"text": "Output"
},
{
"code": null,
"e": 24885,
"s": 24873,
"text": "Example 4 :"
},
{
"code": null,
"e": 24917,
"s": 24885,
"text": "$ echo -e \"Geeks\\\\For\\\\Geeks\" "
},
{
"code": null,
"e": 24927,
"s": 24917,
"text": "Output : "
},
{
"code": null,
"e": 24943,
"s": 24927,
"text": "Geeks\\For\\Geeks"
},
{
"code": null,
"e": 24950,
"s": 24943,
"text": "Output"
},
{
"code": null,
"e": 24962,
"s": 24950,
"text": "Example 5 :"
},
{
"code": null,
"e": 24991,
"s": 24962,
"text": "$ echo -e \"Geeks\\rFor Geeks\""
},
{
"code": null,
"e": 25001,
"s": 24991,
"text": "Output : "
},
{
"code": null,
"e": 25011,
"s": 25001,
"text": "For Geeks"
},
{
"code": null,
"e": 25018,
"s": 25011,
"text": "Output"
},
{
"code": null,
"e": 25030,
"s": 25018,
"text": "Example 6 :"
},
{
"code": null,
"e": 25062,
"s": 25030,
"text": "$ echo -e \"Geeks\\v For\\v Geeks\""
},
{
"code": null,
"e": 25071,
"s": 25062,
"text": "Output :"
},
{
"code": null,
"e": 25087,
"s": 25071,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 25094,
"s": 25087,
"text": "Output"
},
{
"code": null,
"e": 25106,
"s": 25094,
"text": "Example 7 :"
},
{
"code": null,
"e": 25134,
"s": 25106,
"text": "$ echo -n \"Geeks For Geeks\""
},
{
"code": null,
"e": 25143,
"s": 25134,
"text": "Output :"
},
{
"code": null,
"e": 25159,
"s": 25143,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 25166,
"s": 25159,
"text": "Output"
},
{
"code": null,
"e": 25246,
"s": 25166,
"text": "You can find all the commands related to echo by writing the following command."
},
{
"code": null,
"e": 25265,
"s": 25246,
"text": "$ /bin/echo --help"
},
{
"code": null,
"e": 25275,
"s": 25265,
"text": "Output : "
},
{
"code": null,
"e": 25282,
"s": 25275,
"text": "Output"
},
{
"code": null,
"e": 25374,
"s": 25282,
"text": "We create a text file named ” userInput.sh ” and write the following code inside the file. "
},
{
"code": null,
"e": 25500,
"s": 25374,
"text": "#!/bin/sh \n\necho \"Enter Your Name : \"\n\nread name #It take input from user\n\necho \"Hello, $name. Welcome to GeeksForGeeks\""
},
{
"code": null,
"e": 25562,
"s": 25500,
"text": "Now run the ” userInput.sh ” with the help of the below code:"
},
{
"code": null,
"e": 25605,
"s": 25562,
"text": "$ chmod +x ./userInput.sh\n$ ./userInput.sh"
},
{
"code": null,
"e": 25614,
"s": 25605,
"text": "Output :"
},
{
"code": null,
"e": 25621,
"s": 25614,
"text": "Output"
},
{
"code": null,
"e": 25633,
"s": 25621,
"text": "Bash-Script"
},
{
"code": null,
"e": 25640,
"s": 25633,
"text": "Picked"
},
{
"code": null,
"e": 25651,
"s": 25640,
"text": "Linux-Unix"
},
{
"code": null,
"e": 25749,
"s": 25651,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25787,
"s": 25749,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 25822,
"s": 25787,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 25857,
"s": 25822,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 25893,
"s": 25857,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 25931,
"s": 25893,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 25969,
"s": 25931,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26005,
"s": 25969,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 26049,
"s": 26005,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 26085,
"s": 26049,
"text": "echo command in Linux with Examples"
}
]
|
C# Linq Last() Method | Get the last element from a sequence using the Linq Last() method.
The following is our array.
int[] val = { 10, 20, 30, 40 };
Now, get the last element.
val.AsQueryable().Last();
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
class Demo {
static void Main() {
int[] val = { 10, 20, 30, 40 };
// getting last element
int last_num = val.AsQueryable().Last();
Console.WriteLine("Last element: "+last_num);
}
}
Last element: 40 | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "Get the last element from a sequence using the Linq Last() method."
},
{
"code": null,
"e": 1157,
"s": 1129,
"text": "The following is our array."
},
{
"code": null,
"e": 1189,
"s": 1157,
"text": "int[] val = { 10, 20, 30, 40 };"
},
{
"code": null,
"e": 1216,
"s": 1189,
"text": "Now, get the last element."
},
{
"code": null,
"e": 1242,
"s": 1216,
"text": "val.AsQueryable().Last();"
},
{
"code": null,
"e": 1253,
"s": 1242,
"text": " Live Demo"
},
{
"code": null,
"e": 1531,
"s": 1253,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nclass Demo {\n static void Main() {\n int[] val = { 10, 20, 30, 40 };\n // getting last element\n int last_num = val.AsQueryable().Last();\n Console.WriteLine(\"Last element: \"+last_num);\n }\n}"
},
{
"code": null,
"e": 1548,
"s": 1531,
"text": "Last element: 40"
}
]
|
JSTL - fn:indexOf() Function | The fn:indexOf() function returns the index within a string of a specified substring.
The fn:indexOf() function has the following syntax −
int indexOf(java.lang.String, java.lang.String)
Following is the example to explain the functionality of the fn:indexOf() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var = "string1" value = "This is first String."/>
<c:set var = "string2" value = "This <abc>is second String.</abc>"/>
<p>Index (1) : ${fn:indexOf(string1, "first")}</p>
<p>Index (2) : ${fn:indexOf(string2, "second")}</p>
</body>
</html>
You will receive the following result −
Index (1) : 8
Index (2) : 13
108 Lectures
11 hours
Chaand Sheikh
517 Lectures
57 hours
Chaand Sheikh
41 Lectures
4.5 hours
Karthikeya T
42 Lectures
5.5 hours
TELCOMA Global
15 Lectures
3 hours
TELCOMA Global
44 Lectures
15 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2325,
"s": 2239,
"text": "The fn:indexOf() function returns the index within a string of a specified substring."
},
{
"code": null,
"e": 2378,
"s": 2325,
"text": "The fn:indexOf() function has the following syntax −"
},
{
"code": null,
"e": 2427,
"s": 2378,
"text": "int indexOf(java.lang.String, java.lang.String)\n"
},
{
"code": null,
"e": 2512,
"s": 2427,
"text": "Following is the example to explain the functionality of the fn:indexOf() function −"
},
{
"code": null,
"e": 3011,
"s": 2512,
"text": "<%@ taglib uri = \"http://java.sun.com/jsp/jstl/core\" prefix = \"c\" %>\n<%@ taglib uri = \"http://java.sun.com/jsp/jstl/functions\" prefix = \"fn\" %>\n\n<html>\n <head>\n <title>Using JSTL Functions</title>\n </head>\n\n <body>\n <c:set var = \"string1\" value = \"This is first String.\"/>\n <c:set var = \"string2\" value = \"This <abc>is second String.</abc>\"/>\n <p>Index (1) : ${fn:indexOf(string1, \"first\")}</p>\n <p>Index (2) : ${fn:indexOf(string2, \"second\")}</p>\n\n </body>\n</html>"
},
{
"code": null,
"e": 3051,
"s": 3011,
"text": "You will receive the following result −"
},
{
"code": null,
"e": 3081,
"s": 3051,
"text": "Index (1) : 8\nIndex (2) : 13\n"
},
{
"code": null,
"e": 3116,
"s": 3081,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3131,
"s": 3116,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3166,
"s": 3131,
"text": "\n 517 Lectures \n 57 hours \n"
},
{
"code": null,
"e": 3181,
"s": 3166,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 3216,
"s": 3181,
"text": "\n 41 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3230,
"s": 3216,
"text": " Karthikeya T"
},
{
"code": null,
"e": 3265,
"s": 3230,
"text": "\n 42 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3281,
"s": 3265,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3314,
"s": 3281,
"text": "\n 15 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3330,
"s": 3314,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 3364,
"s": 3330,
"text": "\n 44 Lectures \n 15 hours \n"
},
{
"code": null,
"e": 3372,
"s": 3364,
"text": " Uplatz"
},
{
"code": null,
"e": 3379,
"s": 3372,
"text": " Print"
},
{
"code": null,
"e": 3390,
"s": 3379,
"text": " Add Notes"
}
]
|
Javascript search for an object key in a set | The Set class in JavaScript provides a has method to search elements in a given set object. In case you want to search for a object in a set, you need to provide the reference to that object. Identical objects with different memory addresses are not considered equal. This method can be used as follows −
let mySet = new Set();
let myObj = {name: "John"}
mySet.add(1);
mySet.add(3);
mySet.add("a");
mySet.add(myObj);
console.log(mySet)
console.log(mySet.has(myObj))
// Considered as a new object
console.log(mySet.has({name: "John"}))
Set { 1, 2, 3, 'a' }
true
false | [
{
"code": null,
"e": 1367,
"s": 1062,
"text": "The Set class in JavaScript provides a has method to search elements in a given set object. In case you want to search for a object in a set, you need to provide the reference to that object. Identical objects with different memory addresses are not considered equal. This method can be used as follows −"
},
{
"code": null,
"e": 1597,
"s": 1367,
"text": "let mySet = new Set();\nlet myObj = {name: \"John\"}\nmySet.add(1);\nmySet.add(3);\nmySet.add(\"a\");\nmySet.add(myObj);\nconsole.log(mySet)\nconsole.log(mySet.has(myObj))\n// Considered as a new object\nconsole.log(mySet.has({name: \"John\"}))"
},
{
"code": null,
"e": 1629,
"s": 1597,
"text": "Set { 1, 2, 3, 'a' }\ntrue\nfalse"
}
]
|
How to train your Neural Networks in parallel with Keras and Apache Spark | by Niloy Purkait | Towards Data Science | Github Link to project
As a Data scientist, you have surely come across water-cooler discussions where the words ‘Apache Spark’ are thrown out, usually followed by others like ‘computational clusters’, ‘JVM’... and sometimes ‘ did you try restarting the kernel again?’. You know, just the standard industry jargon. Ideally, you might at-least have an idea that Spark has something to do with scaling your data science projects. Or, you may specifically know the sheer firepower that SystemML packs, through some first hand experience with managing a deluge of data and generating any actionable insights therefrom. So lets dive right in!
In most real world machine learning candidate-scenarios, the data itself is being generated in real time from IoT sensors, or multimedia platforms, and is stored in an appropriate format using cloud solutions ranging from HDFS, ObjectStore, NoSQL or SQL databases. For many use cases, running your analytics workflow on the limited resources provided by the local node (on which your Java Virtual Machine runs your iPython notebook), will probably not cut it. A speedy, robust and reliable machine learning workflow can take advantage of large compute clusters, without laboriously editing your code and adapting it for parallel processing. How you ask? Well that’s the secret sauce of the famous Hadoop Distributed File System, which lets you retrieve the combined storage capacity of all disks as one large virtual file system.
What HDFS essentially does is divide your data in equal size chunks and distribute them over the physical disks, while creating a virtual view on top of those chunks so that it can be treated as a single large file spanning the whole cluster. A major advantage of the technology comes from the concept of data locality. Since HDFS keeps track of the whereabouts of individual chunks of the file, computations may be performed in parallel using CPU’s or GPUs residing on the same physical worker node. Some of you at this point may ask, profoundly so, ‘Why do this?’ Well, the simple answer to this can be demonstrated by a little pop quiz:
You have a nice computing cluster, populated with 256 nodes, 8 CPU’s per node, 16 CPU cores per CPU and 4 hyper-threads per core. What is the maximum possible number of concurrently running parallel threads?
The answer to this is of course, <insert drum-roll here> : 131 072 simultaneously running parallel threads, each doing part of your work! (= 256 nodes * 8 CPU’s per node * 16 CPU cores per CPU * 4 hyper-threads per core). Hence in this manner, Apache spark provides a open-source distributed general-purpose cluster-computing framework which allows you to manipulate your data and perform computations in parallel.
The primary data abstraction in the ApacheSpark is the venerable Resilient Distributed Dataset (RDD). This is a distributed immutable collection or list data, which may be written with string or double values, and may be forged using various data storage solutions , ranging from open source MongoDB databases, to more exclusive SQL and NoSQL solutions. You may even create RDDs from your local file system. After its creation, a RDD resides distributed in the main memory of the different worker nodes. Finally, you will find that RDDs are quite lazy. That means that your data is read from the underlying storage system only if it is really needed to perform a certain computation. By default, any transformations you apply to your data-frame (such as dropping variables, or normalising your features) are not instantly executed. Instead, your choices are remembered and only computed when an action requires a result to be returned to the driver program.Turns out that this is not a bad idea at all, and saves quite a bit of computational firepower for the real heavy-lifting to come.
Countless data scientists, analysts, and general business intelligence users rely on interactive SQL queries for exploring data. Thankfully, Spark is well aware of this, and comes with Spark module for structured data processing, called Spark SQL. It provides that programming abstraction we all hold so dearly to, being DataFrames. Spark SQL may also act as distributed SQL query engine, and enables unmodified Hadoop Hive queries to run up to 100x faster on existing deployments and data. It also provides powerful integration with the rest of the Spark ecosystem (e.g., integrating SQL query processing with machine learning).
Machine learning has quickly emerged as a critical piece in mining Big Data for actionable insights. Built on top of Spark, MLlib is a scalable machine learning library that delivers both high-quality algorithms and “blazing” speed, if they do say do themselves (up to 100x faster than MapReduce). The library is usable in Java, Scala, and Python as part of Spark applications, so that you can include it in complete workflows.
The great thing about it is that Apache SystemML provides an optimal workplace for machine learning using big-to-huge data, as not only does it provide means to use extensively customised algorithms, but also lets you use some great pre-implemented algorithms (like Gradient Boosted trees, K-Nearest Neighbours, just to name a few). Better yet, it interfaces with a variety of prominent deep learning frameworks like Keras and Caffe, as we will see later.
Finally, many applications these days need the ability to process and analyse not only batch data, but also streams of new data in real-time. Running on top of Spark, Spark Streaming enables powerful interactive and analytical applications across both streaming and historical data, while inheriting Spark’s ease of use and fault tolerance characteristics. It readily integrates with a wide variety of popular data sources, including HDFS, Flume, Kafka, and Twitter.
Some may claim that naming only 3 features here does not do Apache Spark justice. Operational features such as the tungsten accelerator and the syntax execution tree are also quite remarkable, and equally benefit the data scientist on the go of today. I could of course belabour you with the details surrounding Apache Spark, the Hadoop distributed file system and the mllib library. Go for a journey ‘under the hood’, as it were. But Perhaps the next article. For the purpose of this article, it suffices for us to understand that Apache Spark’s SystemML can run in an embeddable, standalone, and in cluster mode, supports various APIs in Scala, Python, and Java, and is ideal for scaling deep learning models. How you ask?
Enter SystemML,one of the seven wonders of the big data world. This flexible machine learning system is capable of automatically scaling to Spark and Hadoop clusters. In fact, depending on data size, sparsity, computing cluster size as well as memory configuration of your local machine, SystemML will decide whether to compile a single node plan, or a Hadoop or Spark plan. It comes with an R-like functional programming language called Declarative Machine Learning, which lets you implement your preferred machine learning algorithm, or better yet, design a custom one from scratch. SystemML is said to have a cost-less compiler that automatically generates hybrid run-time execution plans, that are composed of single node and distributed operations. It can be run on top of Apache Spark , where it automatically scales your data, line by line, determining whether your code should be run on the driver or an Apache Spark cluster.
There are three different ways to implement a Deep Learning model in SystemML:
Using the DML-bodied NN library: This library allows the user to exploit full flexibility of DML language to implement your neural network.Using the experimental Caffe2DML API: This API allows a model expressed in Caffe’s proto format to be imported into SystemML. This API does not require Caffe to be installed on your SystemML.**Using the experimental Keras2DML API: This API allows a model expressed in Keras’s API to be imported into SystemML. However, this API requires Keras to be installed on your driver.**
Using the DML-bodied NN library: This library allows the user to exploit full flexibility of DML language to implement your neural network.
Using the experimental Caffe2DML API: This API allows a model expressed in Caffe’s proto format to be imported into SystemML. This API does not require Caffe to be installed on your SystemML.
**Using the experimental Keras2DML API: This API allows a model expressed in Keras’s API to be imported into SystemML. However, this API requires Keras to be installed on your driver.**
SystemML developments include additional deep learning with GPU capabilities such as importing and running neural network architectures and pre-trained models for training. The following part of this article will show how to serialise and train a Keras model using the MLContext API. I also encourage you to check out some detailed tutorials published by Apache Spark on how to get started with DML, parallelize algorithms such as autoencoders, and try out some good old image classification.
Now, we will finally train our Keras model using the experimental Keras2DML API. To be able to execute the following code, you will need to make a free tier account on IBM cloud account and log-in to activate Watson studio.
(step-by-step Spark setup on IBM cloud tutorial here, more information on spark with IBM cloud here).
Once you have a Watson studio account with an active Spark plan, you can create a Jupyter notebook on the platform, choose a cloud machine configuration (number of CPUs and RAM) and a Spark plan, and get started!
Watson studio comes with a free spark plan, including 2 Spark workers. While this is enough for demonstration purposes such as now, for real world scenarios it is highly advised to get a paying Spark plan. More Spark workers basically means more threads with which computation may be paralleled, hence less zombie-like waiting in-front of your screen for results. Finally before we get started, I will also note that other alternatives such as Deep Cognition, with equally interesting features and illustrative Medium articles , exist, and are as worthy of exploration.
Ah, MNIST. So iconic, it could be considered the ‘hello world’ of machine learning datasets. In fact, it is even one of the six standard datasets which comes with a Keras install. And rest assured, whatever algorithm you have in mind, ranging from linear classifiers to convolutional neural nets, has been tried and tested on this dataset, sometime in the past 20 years . All for the task of handwritten digit recognition. Something we humans do so effortlessly ourselves(so much so, that having to do it as a job must surely be arduously depressing).
In fact, this task was the ideal candidate for quite a few machine learning genesis projects , due to lack of comprehensively large datasets that existed at the time for...well, anything really. Although that is no more the case, and the Internet is flooding with datasets ranging from avocado prices, to volcanoes on Venus . Today, we honor the MNIST tradition by up-scaling our handwritten digit recognition project. We do this by training our machine learning algorithm on a computational cluster, and potentially decrease our training time dramatically in doing so.
import kerasfrom keras.models import Sequentialfrom keras.layers import Input, Dense, Conv2Dfrom keras.layers import MaxPooling2D, Dropout,Flattenfrom keras import backend as Kfrom keras.models import Modelimport numpy as npimport matplotlib.pyplot as plt
We can now load in the MNIST dataset from Keras, using this simple line of code below.
from keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()# Expect to see a numpy n-dimentional array of (60000, 28, 28)type(X_train), X_train.shape, type(X_train)
Here, we do some reshaping most appropriate for our neural network . We rearrange each 28 X 28 image into one vector of 784 pixel values.
#Flatten each of our 28 X 28 images to a vector of 1, 784X_train = X_train.reshape(-1, 784)X_test = X_test.reshape(-1, 784)#Check shapeX_train.shape, X_test.shape
Then we use Scikit-Learn’s MinMaxScaler to normalise our pixel data, which usually ranges from 0–255. After normalisation, the values will range from 0–1, which greatly improves results.
from sklearn.preprocessing import MinMaxScalerdef scaleData(data): scaler = MinMaxScaler(feature_range=(0, 1)) return scaler.fit_transform(data) X_train = scaleData(X_train)X_test = scaleData(X_test)
Next, we build our network with Keras, defining an appropriate input shape, then stacking some Convolutional, Max Pooling, Dense and dropout layers, as shown below. (Some neural network basics : Do make sure that your last layer has the same number of neurons as your output classes. Since we are predicting handwritten digits, ranging from 0–9, we have a Dense layer of 10 neurons as our last layer here.)
input_shape = (1,28,28) if K.image_data_format() == 'channels_first' else (28,28, 1)keras_model = Sequential()keras_model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape, padding='same'))keras_model.add(MaxPooling2D(pool_size=(2, 2)))keras_model.add(Conv2D(64, (5, 5), activation='relu', padding='same'))keras_model.add(MaxPooling2D(pool_size=(2, 2)))keras_model.add(Flatten())keras_model.add(Dense(512, activation='relu'))keras_model.add(Dropout(0.5))keras_model.add(Dense(10, activation='softmax'))keras_model.summary()
If you see this summary of the Keras model below, your all good so far.
Use the Keras2DML wrapper and feed it our freshly built Keras network. This is done by calling the Keras2DML method and feeding it your spark session, Keras model, its input shape, and the predefined variables. The variable ‘epoch’ denotes the number of times your algorithm iterates over the data. Next, we have ‘batch_size’, which indicates the number of training examples our network will see per learning batch. Finally, ‘samples’ simply encodes the number of samples in our training set. We also ask to be displayed the training results every 10 iterations.
Then we use the fit parameter on our newly defined SystemML model, and pass it the training arrays and labels to initiate our training session.
from systemml.mllearn import Keras2DMLepochs = 5batch_size = 100samples = 60000max_iter = int(epochs*math.ceil(samples/batch_size))sysml_model = Keras2DML(spark, keras_model, input_shape=(1,28,28), weights='weights_dir', batch_size=batch_size, max_iter=max_iter, test_interval=0, display=10)sysml_model.fit(X_train, y_train)
Now, you should see something like this appear on your screen:
6. Time to score! We do this by simply calling the score parameter on our trained SystemML model, like so:
sysml_model.score(X_test, y_test)
Wait for the spark job to execute, and then, voila! you should see your accuracy on the test set appear. As you can see below, we have achieved one of 98.76, not too bad.
Note that we were able to deploy a Keras model through SystemML’s Keras2DML wrapper, which essentially serialises your model to a Caffe model, then converts that model to a declarative machine learning script. The same Keras model would otherwise be bound by the resources of a single JVM, had you chosen to train it with Keras, without significantly adapting your code for parallel processing. Neat, no? You can now train your neural networks on local GPUs , or use a cloud machine like we did on Watson studio.
While it always feels nice to pack some local firepower in terms of processing, nothing beats the cloud. You can really scale up your projects, and choose appropriate machine configurations and spark plans at a fraction of the cost of hardware alternatives. This is ideal for dealing with different environments and use cases which highly variant demands, ranging from small scale data visualisation, to big data projects requiring real time analytics of petabytes of data. Maybe your just trying to analyse a copious amount of IoT data from your distributed warehouse network, like Wallmart. Or maybe your peaking into subatomic depths, trying to determine the fabric of our cosmos, like the CERN. In any of these widely varying use cases could benefit from migrating their computations to the cloud, and very likely have done so.
Ihope that you found this article informative and enjoyable. I for one truly enjoyed researching the contents of this post and composing the relevant code. Here is a link to my repository with the full code, as well as a version of the script without using SystemML. If you have any questions or feedback relating to the content covered , or the source code provided, please let me know in the comments. Until next time!
1. Getting started with Spark: https://databricks.com/product/getting-started-guide-2
2. SystemML webpage: http://systemml.apache.org/
3. Spark ML context Programming guide: https://systemml.apache.org/docs/0.15.0/spark-mlcontext-programming-guide
4. Keras2DML guide: https://systemml.apache.org/docs/1.0.0/beginners-guide-keras2dml
5. Keras: https://keras.io/
6. Github repository for code: https://gist.github.com/NiloyPurkait/1c6c44f329f2255f5de2b0d498c3f238 | [
{
"code": null,
"e": 195,
"s": 172,
"text": "Github Link to project"
},
{
"code": null,
"e": 810,
"s": 195,
"text": "As a Data scientist, you have surely come across water-cooler discussions where the words ‘Apache Spark’ are thrown out, usually followed by others like ‘computational clusters’, ‘JVM’... and sometimes ‘ did you try restarting the kernel again?’. You know, just the standard industry jargon. Ideally, you might at-least have an idea that Spark has something to do with scaling your data science projects. Or, you may specifically know the sheer firepower that SystemML packs, through some first hand experience with managing a deluge of data and generating any actionable insights therefrom. So lets dive right in!"
},
{
"code": null,
"e": 1640,
"s": 810,
"text": "In most real world machine learning candidate-scenarios, the data itself is being generated in real time from IoT sensors, or multimedia platforms, and is stored in an appropriate format using cloud solutions ranging from HDFS, ObjectStore, NoSQL or SQL databases. For many use cases, running your analytics workflow on the limited resources provided by the local node (on which your Java Virtual Machine runs your iPython notebook), will probably not cut it. A speedy, robust and reliable machine learning workflow can take advantage of large compute clusters, without laboriously editing your code and adapting it for parallel processing. How you ask? Well that’s the secret sauce of the famous Hadoop Distributed File System, which lets you retrieve the combined storage capacity of all disks as one large virtual file system."
},
{
"code": null,
"e": 2280,
"s": 1640,
"text": "What HDFS essentially does is divide your data in equal size chunks and distribute them over the physical disks, while creating a virtual view on top of those chunks so that it can be treated as a single large file spanning the whole cluster. A major advantage of the technology comes from the concept of data locality. Since HDFS keeps track of the whereabouts of individual chunks of the file, computations may be performed in parallel using CPU’s or GPUs residing on the same physical worker node. Some of you at this point may ask, profoundly so, ‘Why do this?’ Well, the simple answer to this can be demonstrated by a little pop quiz:"
},
{
"code": null,
"e": 2488,
"s": 2280,
"text": "You have a nice computing cluster, populated with 256 nodes, 8 CPU’s per node, 16 CPU cores per CPU and 4 hyper-threads per core. What is the maximum possible number of concurrently running parallel threads?"
},
{
"code": null,
"e": 2903,
"s": 2488,
"text": "The answer to this is of course, <insert drum-roll here> : 131 072 simultaneously running parallel threads, each doing part of your work! (= 256 nodes * 8 CPU’s per node * 16 CPU cores per CPU * 4 hyper-threads per core). Hence in this manner, Apache spark provides a open-source distributed general-purpose cluster-computing framework which allows you to manipulate your data and perform computations in parallel."
},
{
"code": null,
"e": 3991,
"s": 2903,
"text": "The primary data abstraction in the ApacheSpark is the venerable Resilient Distributed Dataset (RDD). This is a distributed immutable collection or list data, which may be written with string or double values, and may be forged using various data storage solutions , ranging from open source MongoDB databases, to more exclusive SQL and NoSQL solutions. You may even create RDDs from your local file system. After its creation, a RDD resides distributed in the main memory of the different worker nodes. Finally, you will find that RDDs are quite lazy. That means that your data is read from the underlying storage system only if it is really needed to perform a certain computation. By default, any transformations you apply to your data-frame (such as dropping variables, or normalising your features) are not instantly executed. Instead, your choices are remembered and only computed when an action requires a result to be returned to the driver program.Turns out that this is not a bad idea at all, and saves quite a bit of computational firepower for the real heavy-lifting to come."
},
{
"code": null,
"e": 4621,
"s": 3991,
"text": "Countless data scientists, analysts, and general business intelligence users rely on interactive SQL queries for exploring data. Thankfully, Spark is well aware of this, and comes with Spark module for structured data processing, called Spark SQL. It provides that programming abstraction we all hold so dearly to, being DataFrames. Spark SQL may also act as distributed SQL query engine, and enables unmodified Hadoop Hive queries to run up to 100x faster on existing deployments and data. It also provides powerful integration with the rest of the Spark ecosystem (e.g., integrating SQL query processing with machine learning)."
},
{
"code": null,
"e": 5049,
"s": 4621,
"text": "Machine learning has quickly emerged as a critical piece in mining Big Data for actionable insights. Built on top of Spark, MLlib is a scalable machine learning library that delivers both high-quality algorithms and “blazing” speed, if they do say do themselves (up to 100x faster than MapReduce). The library is usable in Java, Scala, and Python as part of Spark applications, so that you can include it in complete workflows."
},
{
"code": null,
"e": 5505,
"s": 5049,
"text": "The great thing about it is that Apache SystemML provides an optimal workplace for machine learning using big-to-huge data, as not only does it provide means to use extensively customised algorithms, but also lets you use some great pre-implemented algorithms (like Gradient Boosted trees, K-Nearest Neighbours, just to name a few). Better yet, it interfaces with a variety of prominent deep learning frameworks like Keras and Caffe, as we will see later."
},
{
"code": null,
"e": 5972,
"s": 5505,
"text": "Finally, many applications these days need the ability to process and analyse not only batch data, but also streams of new data in real-time. Running on top of Spark, Spark Streaming enables powerful interactive and analytical applications across both streaming and historical data, while inheriting Spark’s ease of use and fault tolerance characteristics. It readily integrates with a wide variety of popular data sources, including HDFS, Flume, Kafka, and Twitter."
},
{
"code": null,
"e": 6697,
"s": 5972,
"text": "Some may claim that naming only 3 features here does not do Apache Spark justice. Operational features such as the tungsten accelerator and the syntax execution tree are also quite remarkable, and equally benefit the data scientist on the go of today. I could of course belabour you with the details surrounding Apache Spark, the Hadoop distributed file system and the mllib library. Go for a journey ‘under the hood’, as it were. But Perhaps the next article. For the purpose of this article, it suffices for us to understand that Apache Spark’s SystemML can run in an embeddable, standalone, and in cluster mode, supports various APIs in Scala, Python, and Java, and is ideal for scaling deep learning models. How you ask?"
},
{
"code": null,
"e": 7631,
"s": 6697,
"text": "Enter SystemML,one of the seven wonders of the big data world. This flexible machine learning system is capable of automatically scaling to Spark and Hadoop clusters. In fact, depending on data size, sparsity, computing cluster size as well as memory configuration of your local machine, SystemML will decide whether to compile a single node plan, or a Hadoop or Spark plan. It comes with an R-like functional programming language called Declarative Machine Learning, which lets you implement your preferred machine learning algorithm, or better yet, design a custom one from scratch. SystemML is said to have a cost-less compiler that automatically generates hybrid run-time execution plans, that are composed of single node and distributed operations. It can be run on top of Apache Spark , where it automatically scales your data, line by line, determining whether your code should be run on the driver or an Apache Spark cluster."
},
{
"code": null,
"e": 7710,
"s": 7631,
"text": "There are three different ways to implement a Deep Learning model in SystemML:"
},
{
"code": null,
"e": 8226,
"s": 7710,
"text": "Using the DML-bodied NN library: This library allows the user to exploit full flexibility of DML language to implement your neural network.Using the experimental Caffe2DML API: This API allows a model expressed in Caffe’s proto format to be imported into SystemML. This API does not require Caffe to be installed on your SystemML.**Using the experimental Keras2DML API: This API allows a model expressed in Keras’s API to be imported into SystemML. However, this API requires Keras to be installed on your driver.**"
},
{
"code": null,
"e": 8366,
"s": 8226,
"text": "Using the DML-bodied NN library: This library allows the user to exploit full flexibility of DML language to implement your neural network."
},
{
"code": null,
"e": 8558,
"s": 8366,
"text": "Using the experimental Caffe2DML API: This API allows a model expressed in Caffe’s proto format to be imported into SystemML. This API does not require Caffe to be installed on your SystemML."
},
{
"code": null,
"e": 8744,
"s": 8558,
"text": "**Using the experimental Keras2DML API: This API allows a model expressed in Keras’s API to be imported into SystemML. However, this API requires Keras to be installed on your driver.**"
},
{
"code": null,
"e": 9237,
"s": 8744,
"text": "SystemML developments include additional deep learning with GPU capabilities such as importing and running neural network architectures and pre-trained models for training. The following part of this article will show how to serialise and train a Keras model using the MLContext API. I also encourage you to check out some detailed tutorials published by Apache Spark on how to get started with DML, parallelize algorithms such as autoencoders, and try out some good old image classification."
},
{
"code": null,
"e": 9461,
"s": 9237,
"text": "Now, we will finally train our Keras model using the experimental Keras2DML API. To be able to execute the following code, you will need to make a free tier account on IBM cloud account and log-in to activate Watson studio."
},
{
"code": null,
"e": 9563,
"s": 9461,
"text": "(step-by-step Spark setup on IBM cloud tutorial here, more information on spark with IBM cloud here)."
},
{
"code": null,
"e": 9776,
"s": 9563,
"text": "Once you have a Watson studio account with an active Spark plan, you can create a Jupyter notebook on the platform, choose a cloud machine configuration (number of CPUs and RAM) and a Spark plan, and get started!"
},
{
"code": null,
"e": 10346,
"s": 9776,
"text": "Watson studio comes with a free spark plan, including 2 Spark workers. While this is enough for demonstration purposes such as now, for real world scenarios it is highly advised to get a paying Spark plan. More Spark workers basically means more threads with which computation may be paralleled, hence less zombie-like waiting in-front of your screen for results. Finally before we get started, I will also note that other alternatives such as Deep Cognition, with equally interesting features and illustrative Medium articles , exist, and are as worthy of exploration."
},
{
"code": null,
"e": 10898,
"s": 10346,
"text": "Ah, MNIST. So iconic, it could be considered the ‘hello world’ of machine learning datasets. In fact, it is even one of the six standard datasets which comes with a Keras install. And rest assured, whatever algorithm you have in mind, ranging from linear classifiers to convolutional neural nets, has been tried and tested on this dataset, sometime in the past 20 years . All for the task of handwritten digit recognition. Something we humans do so effortlessly ourselves(so much so, that having to do it as a job must surely be arduously depressing)."
},
{
"code": null,
"e": 11468,
"s": 10898,
"text": "In fact, this task was the ideal candidate for quite a few machine learning genesis projects , due to lack of comprehensively large datasets that existed at the time for...well, anything really. Although that is no more the case, and the Internet is flooding with datasets ranging from avocado prices, to volcanoes on Venus . Today, we honor the MNIST tradition by up-scaling our handwritten digit recognition project. We do this by training our machine learning algorithm on a computational cluster, and potentially decrease our training time dramatically in doing so."
},
{
"code": null,
"e": 11724,
"s": 11468,
"text": "import kerasfrom keras.models import Sequentialfrom keras.layers import Input, Dense, Conv2Dfrom keras.layers import MaxPooling2D, Dropout,Flattenfrom keras import backend as Kfrom keras.models import Modelimport numpy as npimport matplotlib.pyplot as plt"
},
{
"code": null,
"e": 11811,
"s": 11724,
"text": "We can now load in the MNIST dataset from Keras, using this simple line of code below."
},
{
"code": null,
"e": 12005,
"s": 11811,
"text": "from keras.datasets import mnist(X_train, y_train), (X_test, y_test) = mnist.load_data()# Expect to see a numpy n-dimentional array of (60000, 28, 28)type(X_train), X_train.shape, type(X_train)"
},
{
"code": null,
"e": 12143,
"s": 12005,
"text": "Here, we do some reshaping most appropriate for our neural network . We rearrange each 28 X 28 image into one vector of 784 pixel values."
},
{
"code": null,
"e": 12306,
"s": 12143,
"text": "#Flatten each of our 28 X 28 images to a vector of 1, 784X_train = X_train.reshape(-1, 784)X_test = X_test.reshape(-1, 784)#Check shapeX_train.shape, X_test.shape"
},
{
"code": null,
"e": 12493,
"s": 12306,
"text": "Then we use Scikit-Learn’s MinMaxScaler to normalise our pixel data, which usually ranges from 0–255. After normalisation, the values will range from 0–1, which greatly improves results."
},
{
"code": null,
"e": 12706,
"s": 12493,
"text": "from sklearn.preprocessing import MinMaxScalerdef scaleData(data): scaler = MinMaxScaler(feature_range=(0, 1)) return scaler.fit_transform(data) X_train = scaleData(X_train)X_test = scaleData(X_test)"
},
{
"code": null,
"e": 13113,
"s": 12706,
"text": "Next, we build our network with Keras, defining an appropriate input shape, then stacking some Convolutional, Max Pooling, Dense and dropout layers, as shown below. (Some neural network basics : Do make sure that your last layer has the same number of neurons as your output classes. Since we are predicting handwritten digits, ranging from 0–9, we have a Dense layer of 10 neurons as our last layer here.)"
},
{
"code": null,
"e": 13665,
"s": 13113,
"text": "input_shape = (1,28,28) if K.image_data_format() == 'channels_first' else (28,28, 1)keras_model = Sequential()keras_model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=input_shape, padding='same'))keras_model.add(MaxPooling2D(pool_size=(2, 2)))keras_model.add(Conv2D(64, (5, 5), activation='relu', padding='same'))keras_model.add(MaxPooling2D(pool_size=(2, 2)))keras_model.add(Flatten())keras_model.add(Dense(512, activation='relu'))keras_model.add(Dropout(0.5))keras_model.add(Dense(10, activation='softmax'))keras_model.summary()"
},
{
"code": null,
"e": 13737,
"s": 13665,
"text": "If you see this summary of the Keras model below, your all good so far."
},
{
"code": null,
"e": 14300,
"s": 13737,
"text": "Use the Keras2DML wrapper and feed it our freshly built Keras network. This is done by calling the Keras2DML method and feeding it your spark session, Keras model, its input shape, and the predefined variables. The variable ‘epoch’ denotes the number of times your algorithm iterates over the data. Next, we have ‘batch_size’, which indicates the number of training examples our network will see per learning batch. Finally, ‘samples’ simply encodes the number of samples in our training set. We also ask to be displayed the training results every 10 iterations."
},
{
"code": null,
"e": 14444,
"s": 14300,
"text": "Then we use the fit parameter on our newly defined SystemML model, and pass it the training arrays and labels to initiate our training session."
},
{
"code": null,
"e": 14769,
"s": 14444,
"text": "from systemml.mllearn import Keras2DMLepochs = 5batch_size = 100samples = 60000max_iter = int(epochs*math.ceil(samples/batch_size))sysml_model = Keras2DML(spark, keras_model, input_shape=(1,28,28), weights='weights_dir', batch_size=batch_size, max_iter=max_iter, test_interval=0, display=10)sysml_model.fit(X_train, y_train)"
},
{
"code": null,
"e": 14832,
"s": 14769,
"text": "Now, you should see something like this appear on your screen:"
},
{
"code": null,
"e": 14939,
"s": 14832,
"text": "6. Time to score! We do this by simply calling the score parameter on our trained SystemML model, like so:"
},
{
"code": null,
"e": 14973,
"s": 14939,
"text": "sysml_model.score(X_test, y_test)"
},
{
"code": null,
"e": 15144,
"s": 14973,
"text": "Wait for the spark job to execute, and then, voila! you should see your accuracy on the test set appear. As you can see below, we have achieved one of 98.76, not too bad."
},
{
"code": null,
"e": 15657,
"s": 15144,
"text": "Note that we were able to deploy a Keras model through SystemML’s Keras2DML wrapper, which essentially serialises your model to a Caffe model, then converts that model to a declarative machine learning script. The same Keras model would otherwise be bound by the resources of a single JVM, had you chosen to train it with Keras, without significantly adapting your code for parallel processing. Neat, no? You can now train your neural networks on local GPUs , or use a cloud machine like we did on Watson studio."
},
{
"code": null,
"e": 16489,
"s": 15657,
"text": "While it always feels nice to pack some local firepower in terms of processing, nothing beats the cloud. You can really scale up your projects, and choose appropriate machine configurations and spark plans at a fraction of the cost of hardware alternatives. This is ideal for dealing with different environments and use cases which highly variant demands, ranging from small scale data visualisation, to big data projects requiring real time analytics of petabytes of data. Maybe your just trying to analyse a copious amount of IoT data from your distributed warehouse network, like Wallmart. Or maybe your peaking into subatomic depths, trying to determine the fabric of our cosmos, like the CERN. In any of these widely varying use cases could benefit from migrating their computations to the cloud, and very likely have done so."
},
{
"code": null,
"e": 16910,
"s": 16489,
"text": "Ihope that you found this article informative and enjoyable. I for one truly enjoyed researching the contents of this post and composing the relevant code. Here is a link to my repository with the full code, as well as a version of the script without using SystemML. If you have any questions or feedback relating to the content covered , or the source code provided, please let me know in the comments. Until next time!"
},
{
"code": null,
"e": 16996,
"s": 16910,
"text": "1. Getting started with Spark: https://databricks.com/product/getting-started-guide-2"
},
{
"code": null,
"e": 17045,
"s": 16996,
"text": "2. SystemML webpage: http://systemml.apache.org/"
},
{
"code": null,
"e": 17158,
"s": 17045,
"text": "3. Spark ML context Programming guide: https://systemml.apache.org/docs/0.15.0/spark-mlcontext-programming-guide"
},
{
"code": null,
"e": 17243,
"s": 17158,
"text": "4. Keras2DML guide: https://systemml.apache.org/docs/1.0.0/beginners-guide-keras2dml"
},
{
"code": null,
"e": 17271,
"s": 17243,
"text": "5. Keras: https://keras.io/"
}
]
|
How to work with Mouse Events using OpenCV in C++? | Mouse Events is one of the most useful features of OpenCV. In OpenCV, we can track the mouse pointer's position and track the clicks (right, left and middle-click). OpenCV has a wide application in robotics and computer vision. In robotics and computer vision tracking mouse pointer and clicks are frequently used.
Here we will understand how to track the mouse pointer's location on an image and track the clicks.
The following program demonstrates how to track the location of the mouse pointer and clicks.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
void locator(int event, int x, int y, int flags, void* userdata){ //function to track mouse movement and click//
if (event == EVENT_LBUTTONDOWN){ //when left button clicked//
cout << "Left click has been made, Position:(" << x << "," << y << ")" << endl;
} else if (event == EVENT_RBUTTONDOWN){ //when right button clicked//
cout << "Rightclick has been made, Position:(" << x << "," << y << ")" << endl;
} else if (event == EVENT_MBUTTONDOWN){ //when middle button clicked//
cout << "Middleclick has been made, Position:(" << x << "," << y << ")" << endl;
} else if (event == EVENT_MOUSEMOVE){ //when mouse pointer moves//
cout << "Current mouse position:(" << x << "," << y << ")" << endl;
}
}
int main() {
Mat image = imread("bright.jpg");//loading image in the matrix//
namedWindow("Track");//declaring window to show image//
setMouseCallback("Track", locator, NULL);//Mouse callback function on define window//
imshow("Track", image);//showing image on the window//
waitKey(0);//wait for keystroke//
return 0;
} | [
{
"code": null,
"e": 1377,
"s": 1062,
"text": "Mouse Events is one of the most useful features of OpenCV. In OpenCV, we can track the mouse pointer's position and track the clicks (right, left and middle-click). OpenCV has a wide application in robotics and computer vision. In robotics and computer vision tracking mouse pointer and clicks are frequently used."
},
{
"code": null,
"e": 1477,
"s": 1377,
"text": "Here we will understand how to track the mouse pointer's location on an image and track the clicks."
},
{
"code": null,
"e": 1571,
"s": 1477,
"text": "The following program demonstrates how to track the location of the mouse pointer and clicks."
},
{
"code": null,
"e": 2781,
"s": 1571,
"text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\n#include<opencv2/imgproc/imgproc.hpp>\nusing namespace std;\nusing namespace cv;\nvoid locator(int event, int x, int y, int flags, void* userdata){ //function to track mouse movement and click//\n if (event == EVENT_LBUTTONDOWN){ //when left button clicked//\n cout << \"Left click has been made, Position:(\" << x << \",\" << y << \")\" << endl;\n } else if (event == EVENT_RBUTTONDOWN){ //when right button clicked//\n cout << \"Rightclick has been made, Position:(\" << x << \",\" << y << \")\" << endl;\n } else if (event == EVENT_MBUTTONDOWN){ //when middle button clicked//\n cout << \"Middleclick has been made, Position:(\" << x << \",\" << y << \")\" << endl;\n } else if (event == EVENT_MOUSEMOVE){ //when mouse pointer moves//\n cout << \"Current mouse position:(\" << x << \",\" << y << \")\" << endl;\n }\n}\nint main() {\n Mat image = imread(\"bright.jpg\");//loading image in the matrix//\n namedWindow(\"Track\");//declaring window to show image//\n setMouseCallback(\"Track\", locator, NULL);//Mouse callback function on define window//\n imshow(\"Track\", image);//showing image on the window//\n waitKey(0);//wait for keystroke//\n return 0;\n}"
}
]
|
GATE | GATE-CS-2004 | Question 69 - GeeksforGeeks | 07 Nov, 2019
A 4-stage pipeline has the stage delays as 150, 120, 160 and 140 nanoseconds respectively. Registers that are used between the stages have a delay of 5 nanoseconds each. Assuming constant clocking rate, the total time taken to process 1000 data items on this pipeline will be(A) 120.4 microseconds(B) 160.5 microseconds(C) 165.5 microseconds(D) 590.0 microsecondsAnswer: (C)Explanation:
Delay between each stage is 5 ns.
Total delay for 1st data item = 165*4
= 660
For 1000 data items, first data will take 660 ns to complete and rest
999 data will take max of all the stages that is 160 ns + 5 ns register delay
Total Delay = 660 + 999*165 ns which is equal to 165.5 microsecond.
Quiz of this Question
manikshekhar15
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2007 | Question 64
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE CS 2019 | Question 27 | [
{
"code": null,
"e": 24410,
"s": 24382,
"text": "\n07 Nov, 2019"
},
{
"code": null,
"e": 24797,
"s": 24410,
"text": "A 4-stage pipeline has the stage delays as 150, 120, 160 and 140 nanoseconds respectively. Registers that are used between the stages have a delay of 5 nanoseconds each. Assuming constant clocking rate, the total time taken to process 1000 data items on this pipeline will be(A) 120.4 microseconds(B) 160.5 microseconds(C) 165.5 microseconds(D) 590.0 microsecondsAnswer: (C)Explanation:"
},
{
"code": null,
"e": 25126,
"s": 24797,
"text": "Delay between each stage is 5 ns.\n\nTotal delay for 1st data item = 165*4\n = 660 \nFor 1000 data items, first data will take 660 ns to complete and rest \n999 data will take max of all the stages that is 160 ns + 5 ns register delay\n\nTotal Delay = 660 + 999*165 ns which is equal to 165.5 microsecond. "
},
{
"code": null,
"e": 25148,
"s": 25126,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25163,
"s": 25148,
"text": "manikshekhar15"
},
{
"code": null,
"e": 25176,
"s": 25163,
"text": "GATE-CS-2004"
},
{
"code": null,
"e": 25194,
"s": 25176,
"text": "GATE-GATE-CS-2004"
},
{
"code": null,
"e": 25199,
"s": 25194,
"text": "GATE"
},
{
"code": null,
"e": 25297,
"s": 25199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25306,
"s": 25297,
"text": "Comments"
},
{
"code": null,
"e": 25319,
"s": 25306,
"text": "Old Comments"
},
{
"code": null,
"e": 25353,
"s": 25319,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25386,
"s": 25353,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25428,
"s": 25386,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25462,
"s": 25428,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25504,
"s": 25462,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25546,
"s": 25504,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25580,
"s": 25546,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25614,
"s": 25580,
"text": "GATE | GATE-CS-2007 | Question 64"
},
{
"code": null,
"e": 25656,
"s": 25614,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
}
]
|
Pandas (Python) vs Data.table (R) | by Soner Yıldırım | Towards Data Science | Data science ecosystem is full of highly effective and practical tools and frameworks. New ones are introduced and the existing ones are improved continuously.
Having a variety of selections is a good thing and likely to increase the efficiency in most cases. However, it might also make it hard to decide which one to pick.
In this article, we will compare popular data manipulation libraries in arguably the two most commonly used programming languages in data science domain.
We will see how basic operations are done in Pandas (Python) and Data.table (R). The goal is not to determine if one is superior to or better than the other. I just want to make you familiar with the syntax and show similar or different approaches.
There are many options to use these packages. I’m using R-studio IDE for R and VSCode for Python.
We start with importing the libraries and creating the basic data structures by reading data from a csv file.
In Pandas, we use the read_csv function to create a dataframe from a csv file.
import numpy as npimport pandas as pd #importing pandasinsurance = pd.read_csv("/home/soner/Downloads/datasets/insurance.csv")
In Data.table, the equivalent of the read_csv is the fread function.
> library(data.table) #importing data.table > insurance = fread("/home/soner/Downloads/datasets/insurance.csv")
The head function displays the top n number of rows. The name of the function is same for both packages but the syntax is slightly different.
The default n value is 5 for both so they will display the first 5 rows by default.
We usually check the size of data in terms of the number of rows and columns. Both libraries have intuitive ways of obtaining the size related information.
#Pandasinsurance.shape(1338, 7)#Data.tablenrow(insurance)1338ncol(insurance)7
In some cases, we just need a certain set of columns from a table. Both Pandas and Data.table provides convenient ways for doing this operation.
sub = insurance[['age','sex','charges']]sub.head()
The same operation is done with Data.table as follows:
> sub = insurance[, .(age, sex, charges)]> head(sub)
The rename and setname functions can be used to rename columns in Pandas and Data.table, respectively.
Pandas:
sub.rename(columns={'sex':'gender'}, inplace=True)sub.columnsIndex(['age', 'gender', 'charges'], dtype='object')
Data.table:
> setnames(sub, c("sex"), c("gender"))> names(sub)[1] "age" "gender" "charges"
As we see from the examples, the columns method on dataframe returns a list of columns. Same operation is done with the names function in Data.table library.
We can filter a dataframe or table based on row values. In the following examples, we create a subset that contains customer who are older than 40.
Pandas:
sub_over40 = sub[sub.age > 40]
Data.table:
> sub_over40 <- sub[age > 40] #can also use "<-" instead of "="
One of the most common operations in data analysis is to comparing numerical variables based on different values in a categorical variable.
In Pandas, this kind of transformations and calculations are done with the group by function. For instance, we can calculate the average charge of data points in each category based on the gender and smoker columns.
insurance[['gender','smoker','charges']]\.groupby(['gender','smoker']).mean().round(2)
It is possible to apply multiple aggregate functions. For instance, we may want to see both the number of observations in each group in addition to the average charge value.
insurance[['gender','smoker','charges']]\.groupby(['gender','smoker']).agg(['mean','count'])
In Data.table, the same calculation is done as follows:
> insurance[, .(mean(charges)), by = .(gender, smoker)]
Just like with Pandas, Data.table provides a straightforward way to apply multiple aggregations. Both the number of observations and average charge value are calculated as follows:
> insurance[, .(mean(charges), .N), by = .(gender, smoker)]
We have covered some simple tasks in Pandas and Data.table libraries. Due to the complexity level of operations, the syntax seems quite similar for both libraries. However, as the complexity increases and we do more advance data analysis and manipulation operations, the difference between them become more noticeable.
The best way to learn how to use these libraries is through practice. As you adapt them in your data analysis tasks, you will have some preference for using a particular one in certain tasks.
In general, I think both are more than enough to perform typical data analysis tasks.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 331,
"s": 171,
"text": "Data science ecosystem is full of highly effective and practical tools and frameworks. New ones are introduced and the existing ones are improved continuously."
},
{
"code": null,
"e": 496,
"s": 331,
"text": "Having a variety of selections is a good thing and likely to increase the efficiency in most cases. However, it might also make it hard to decide which one to pick."
},
{
"code": null,
"e": 650,
"s": 496,
"text": "In this article, we will compare popular data manipulation libraries in arguably the two most commonly used programming languages in data science domain."
},
{
"code": null,
"e": 899,
"s": 650,
"text": "We will see how basic operations are done in Pandas (Python) and Data.table (R). The goal is not to determine if one is superior to or better than the other. I just want to make you familiar with the syntax and show similar or different approaches."
},
{
"code": null,
"e": 997,
"s": 899,
"text": "There are many options to use these packages. I’m using R-studio IDE for R and VSCode for Python."
},
{
"code": null,
"e": 1107,
"s": 997,
"text": "We start with importing the libraries and creating the basic data structures by reading data from a csv file."
},
{
"code": null,
"e": 1186,
"s": 1107,
"text": "In Pandas, we use the read_csv function to create a dataframe from a csv file."
},
{
"code": null,
"e": 1313,
"s": 1186,
"text": "import numpy as npimport pandas as pd #importing pandasinsurance = pd.read_csv(\"/home/soner/Downloads/datasets/insurance.csv\")"
},
{
"code": null,
"e": 1382,
"s": 1313,
"text": "In Data.table, the equivalent of the read_csv is the fread function."
},
{
"code": null,
"e": 1494,
"s": 1382,
"text": "> library(data.table) #importing data.table > insurance = fread(\"/home/soner/Downloads/datasets/insurance.csv\")"
},
{
"code": null,
"e": 1636,
"s": 1494,
"text": "The head function displays the top n number of rows. The name of the function is same for both packages but the syntax is slightly different."
},
{
"code": null,
"e": 1720,
"s": 1636,
"text": "The default n value is 5 for both so they will display the first 5 rows by default."
},
{
"code": null,
"e": 1876,
"s": 1720,
"text": "We usually check the size of data in terms of the number of rows and columns. Both libraries have intuitive ways of obtaining the size related information."
},
{
"code": null,
"e": 1954,
"s": 1876,
"text": "#Pandasinsurance.shape(1338, 7)#Data.tablenrow(insurance)1338ncol(insurance)7"
},
{
"code": null,
"e": 2099,
"s": 1954,
"text": "In some cases, we just need a certain set of columns from a table. Both Pandas and Data.table provides convenient ways for doing this operation."
},
{
"code": null,
"e": 2150,
"s": 2099,
"text": "sub = insurance[['age','sex','charges']]sub.head()"
},
{
"code": null,
"e": 2205,
"s": 2150,
"text": "The same operation is done with Data.table as follows:"
},
{
"code": null,
"e": 2258,
"s": 2205,
"text": "> sub = insurance[, .(age, sex, charges)]> head(sub)"
},
{
"code": null,
"e": 2361,
"s": 2258,
"text": "The rename and setname functions can be used to rename columns in Pandas and Data.table, respectively."
},
{
"code": null,
"e": 2369,
"s": 2361,
"text": "Pandas:"
},
{
"code": null,
"e": 2482,
"s": 2369,
"text": "sub.rename(columns={'sex':'gender'}, inplace=True)sub.columnsIndex(['age', 'gender', 'charges'], dtype='object')"
},
{
"code": null,
"e": 2494,
"s": 2482,
"text": "Data.table:"
},
{
"code": null,
"e": 2578,
"s": 2494,
"text": "> setnames(sub, c(\"sex\"), c(\"gender\"))> names(sub)[1] \"age\" \"gender\" \"charges\""
},
{
"code": null,
"e": 2736,
"s": 2578,
"text": "As we see from the examples, the columns method on dataframe returns a list of columns. Same operation is done with the names function in Data.table library."
},
{
"code": null,
"e": 2884,
"s": 2736,
"text": "We can filter a dataframe or table based on row values. In the following examples, we create a subset that contains customer who are older than 40."
},
{
"code": null,
"e": 2892,
"s": 2884,
"text": "Pandas:"
},
{
"code": null,
"e": 2923,
"s": 2892,
"text": "sub_over40 = sub[sub.age > 40]"
},
{
"code": null,
"e": 2935,
"s": 2923,
"text": "Data.table:"
},
{
"code": null,
"e": 2999,
"s": 2935,
"text": "> sub_over40 <- sub[age > 40] #can also use \"<-\" instead of \"=\""
},
{
"code": null,
"e": 3139,
"s": 2999,
"text": "One of the most common operations in data analysis is to comparing numerical variables based on different values in a categorical variable."
},
{
"code": null,
"e": 3355,
"s": 3139,
"text": "In Pandas, this kind of transformations and calculations are done with the group by function. For instance, we can calculate the average charge of data points in each category based on the gender and smoker columns."
},
{
"code": null,
"e": 3442,
"s": 3355,
"text": "insurance[['gender','smoker','charges']]\\.groupby(['gender','smoker']).mean().round(2)"
},
{
"code": null,
"e": 3616,
"s": 3442,
"text": "It is possible to apply multiple aggregate functions. For instance, we may want to see both the number of observations in each group in addition to the average charge value."
},
{
"code": null,
"e": 3709,
"s": 3616,
"text": "insurance[['gender','smoker','charges']]\\.groupby(['gender','smoker']).agg(['mean','count'])"
},
{
"code": null,
"e": 3765,
"s": 3709,
"text": "In Data.table, the same calculation is done as follows:"
},
{
"code": null,
"e": 3821,
"s": 3765,
"text": "> insurance[, .(mean(charges)), by = .(gender, smoker)]"
},
{
"code": null,
"e": 4002,
"s": 3821,
"text": "Just like with Pandas, Data.table provides a straightforward way to apply multiple aggregations. Both the number of observations and average charge value are calculated as follows:"
},
{
"code": null,
"e": 4062,
"s": 4002,
"text": "> insurance[, .(mean(charges), .N), by = .(gender, smoker)]"
},
{
"code": null,
"e": 4381,
"s": 4062,
"text": "We have covered some simple tasks in Pandas and Data.table libraries. Due to the complexity level of operations, the syntax seems quite similar for both libraries. However, as the complexity increases and we do more advance data analysis and manipulation operations, the difference between them become more noticeable."
},
{
"code": null,
"e": 4573,
"s": 4381,
"text": "The best way to learn how to use these libraries is through practice. As you adapt them in your data analysis tasks, you will have some preference for using a particular one in certain tasks."
},
{
"code": null,
"e": 4659,
"s": 4573,
"text": "In general, I think both are more than enough to perform typical data analysis tasks."
}
]
|
Building Image Classification API with Tensorflow and FastAPI | by Aniket Maurya | Towards Data Science | FastAPI is a high-performance asynchronous framework for building APIs in Python.
Video tutorial is also available for this blog
Source code for this blog is available aniketmaurya/tensorflow-fastapi-starter-pack
First, we import FastAPI class and create an object app. This class has useful parameters like we can pass the title and description for Swagger UI.
from fastapi import FastAPIapp = FastAPI(title='Hello world')
We define a function and decorate it with @app.get. This means that our API /index supports the GET method. The function defined here is async, FastAPI automatically takes care of async and without async methods by creating a thread pool for the normal def functions and it uses an async event loop for async functions.
@app.get('/index')async def hello_world(): return "hello world"
We will create an API to classify images, we name it predict/image. We will use Tensorflow for creating the image classification model.
Tutorial for Image Classification with Tensorflow
We create a function load_model, which will return a MobileNet CNN Model with pre-trained weights i.e. it is already trained to classify 1000 unique categories of images.
import tensorflow as tfdef load_model(): model = tf.keras.applications.MobileNetV2(weights="imagenet") print("Model loaded") return modelmodel = load_model()
We define a predict function that will accept an image and returns the predictions. We resize the image to 224x224 and normalize the pixel values to be in [-1, 1].
from tensorflow.keras.applications.imagenet_utils import decode_predictions
decode_predictions is used to decode the class name of the predicted object. Here we will return the top-2 probable class.
def predict(image: Image.Image): image = np.asarray(image.resize((224, 224)))[..., :3] image = np.expand_dims(image, 0) image = image / 127.5 - 1.0 result = decode_predictions(model.predict(image), 2)[0] response = [] for i, res in enumerate(result): resp = {} resp["class"] = res[1] resp["confidence"] = f"{res[2]*100:0.2f} %" response.append(resp) return response
Now we will create an API /predict/image that supports file upload. We will filter the file extension to support only jpg, jpeg, and png format of images.
We will use Pillow to load the uploaded image.
def read_imagefile(file) -> Image.Image: image = Image.open(BytesIO(file)) return [email protected]("/predict/image")async def predict_api(file: UploadFile = File(...)): extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png") if not extension: return "Image must be jpg or png format!" image = read_imagefile(await file.read()) prediction = predict(image) return prediction
import uvicornfrom fastapi import FastAPI, File, UploadFilefrom application.components import predict, read_imagefileapp = FastAPI()@app.post("/predict/image")async def predict_api(file: UploadFile = File(...)): extension = file.filename.split(".")[-1] in ("jpg", "jpeg", "png") if not extension: return "Image must be jpg or png format!" image = read_imagefile(await file.read()) prediction = predict(image) return [email protected]("/api/covid-symptom-check")def check_risk(symptom: Symptom): return symptom_check.get_risk_level(symptom)if __name__ == "__main__": uvicorn.run(app, debug=True)
FastAPI documentation is the best place to learn more about core concepts of the framework.
Hope you liked the article.
Feel free to ask your questions in the comments or reach me out personally
👉 Twitter: https://twitter.com/aniketmaurya
👉 Linkedin: https://linkedin.com/in/aniketmaurya | [
{
"code": null,
"e": 253,
"s": 171,
"text": "FastAPI is a high-performance asynchronous framework for building APIs in Python."
},
{
"code": null,
"e": 300,
"s": 253,
"text": "Video tutorial is also available for this blog"
},
{
"code": null,
"e": 384,
"s": 300,
"text": "Source code for this blog is available aniketmaurya/tensorflow-fastapi-starter-pack"
},
{
"code": null,
"e": 533,
"s": 384,
"text": "First, we import FastAPI class and create an object app. This class has useful parameters like we can pass the title and description for Swagger UI."
},
{
"code": null,
"e": 595,
"s": 533,
"text": "from fastapi import FastAPIapp = FastAPI(title='Hello world')"
},
{
"code": null,
"e": 915,
"s": 595,
"text": "We define a function and decorate it with @app.get. This means that our API /index supports the GET method. The function defined here is async, FastAPI automatically takes care of async and without async methods by creating a thread pool for the normal def functions and it uses an async event loop for async functions."
},
{
"code": null,
"e": 982,
"s": 915,
"text": "@app.get('/index')async def hello_world(): return \"hello world\""
},
{
"code": null,
"e": 1118,
"s": 982,
"text": "We will create an API to classify images, we name it predict/image. We will use Tensorflow for creating the image classification model."
},
{
"code": null,
"e": 1168,
"s": 1118,
"text": "Tutorial for Image Classification with Tensorflow"
},
{
"code": null,
"e": 1339,
"s": 1168,
"text": "We create a function load_model, which will return a MobileNet CNN Model with pre-trained weights i.e. it is already trained to classify 1000 unique categories of images."
},
{
"code": null,
"e": 1506,
"s": 1339,
"text": "import tensorflow as tfdef load_model(): model = tf.keras.applications.MobileNetV2(weights=\"imagenet\") print(\"Model loaded\") return modelmodel = load_model()"
},
{
"code": null,
"e": 1670,
"s": 1506,
"text": "We define a predict function that will accept an image and returns the predictions. We resize the image to 224x224 and normalize the pixel values to be in [-1, 1]."
},
{
"code": null,
"e": 1746,
"s": 1670,
"text": "from tensorflow.keras.applications.imagenet_utils import decode_predictions"
},
{
"code": null,
"e": 1869,
"s": 1746,
"text": "decode_predictions is used to decode the class name of the predicted object. Here we will return the top-2 probable class."
},
{
"code": null,
"e": 2284,
"s": 1869,
"text": "def predict(image: Image.Image): image = np.asarray(image.resize((224, 224)))[..., :3] image = np.expand_dims(image, 0) image = image / 127.5 - 1.0 result = decode_predictions(model.predict(image), 2)[0] response = [] for i, res in enumerate(result): resp = {} resp[\"class\"] = res[1] resp[\"confidence\"] = f\"{res[2]*100:0.2f} %\" response.append(resp) return response"
},
{
"code": null,
"e": 2439,
"s": 2284,
"text": "Now we will create an API /predict/image that supports file upload. We will filter the file extension to support only jpg, jpeg, and png format of images."
},
{
"code": null,
"e": 2486,
"s": 2439,
"text": "We will use Pillow to load the uploaded image."
},
{
"code": null,
"e": 2896,
"s": 2486,
"text": "def read_imagefile(file) -> Image.Image: image = Image.open(BytesIO(file)) return [email protected](\"/predict/image\")async def predict_api(file: UploadFile = File(...)): extension = file.filename.split(\".\")[-1] in (\"jpg\", \"jpeg\", \"png\") if not extension: return \"Image must be jpg or png format!\" image = read_imagefile(await file.read()) prediction = predict(image) return prediction"
},
{
"code": null,
"e": 3521,
"s": 2896,
"text": "import uvicornfrom fastapi import FastAPI, File, UploadFilefrom application.components import predict, read_imagefileapp = FastAPI()@app.post(\"/predict/image\")async def predict_api(file: UploadFile = File(...)): extension = file.filename.split(\".\")[-1] in (\"jpg\", \"jpeg\", \"png\") if not extension: return \"Image must be jpg or png format!\" image = read_imagefile(await file.read()) prediction = predict(image) return [email protected](\"/api/covid-symptom-check\")def check_risk(symptom: Symptom): return symptom_check.get_risk_level(symptom)if __name__ == \"__main__\": uvicorn.run(app, debug=True)"
},
{
"code": null,
"e": 3613,
"s": 3521,
"text": "FastAPI documentation is the best place to learn more about core concepts of the framework."
},
{
"code": null,
"e": 3641,
"s": 3613,
"text": "Hope you liked the article."
},
{
"code": null,
"e": 3716,
"s": 3641,
"text": "Feel free to ask your questions in the comments or reach me out personally"
},
{
"code": null,
"e": 3760,
"s": 3716,
"text": "👉 Twitter: https://twitter.com/aniketmaurya"
}
]
|
ISRO | ISRO CS 2015 | Question 13 - GeeksforGeeks | 03 Apr, 2018
Six files F1, F2, F3, F4, F5 and F6 have 100, 200, 50, 80, 120, 150 records respectively. In what order should they be stored so as to optimize act. Assume each file is accessed with the same frequency(A) F3, F4, F1, F5, F6, F2(B) F2, F6, F5, F1, F4, F3(C) F1, F2, F3, F4, F5, F6(D) Ordering is immaterial as all files are accessed with the same frequency.Answer: (A)Explanation:
This question is based on the Optimal Storage on Tape problem
which uses greedy approach to find the optimal time to retrieve them.
There are n programs of length L that are to be stored on a computer
tape. Associated with each program i is a length Li. So in order to
retrieve these programs most optimally, we need to store them in the
non-decreasing order of length Li.
So, the correct order is F3, F4, F1, F5, F6, F2
Quiz of this QuestionPlease comment below if you find anything wrong in the above post
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2011 | Question 26
ISRO | ISRO CS 2017 - May | Question 21
ISRO | ISRO CS 2013 | Question 54
ISRO | ISRO CS 2011 | Question 13
ISRO | ISRO CS 2008 | Question 1
ISRO | ISRO CS 2013 | Question 4
ISRO | ISRO CS 2016 | Question 49
ISRO | ISRO CS 2018 | Question 10
ISRO | ISRO CS 2016 | Question 41
ISRO | ISRO CS 2018 | Question 17 | [
{
"code": null,
"e": 24468,
"s": 24440,
"text": "\n03 Apr, 2018"
},
{
"code": null,
"e": 24848,
"s": 24468,
"text": "Six files F1, F2, F3, F4, F5 and F6 have 100, 200, 50, 80, 120, 150 records respectively. In what order should they be stored so as to optimize act. Assume each file is accessed with the same frequency(A) F3, F4, F1, F5, F6, F2(B) F2, F6, F5, F1, F4, F3(C) F1, F2, F3, F4, F5, F6(D) Ordering is immaterial as all files are accessed with the same frequency.Answer: (A)Explanation:"
},
{
"code": null,
"e": 25269,
"s": 24848,
"text": "This question is based on the Optimal Storage on Tape problem\nwhich uses greedy approach to find the optimal time to retrieve them.\nThere are n programs of length L that are to be stored on a computer\ntape. Associated with each program i is a length Li. So in order to\nretrieve these programs most optimally, we need to store them in the\nnon-decreasing order of length Li.\nSo, the correct order is F3, F4, F1, F5, F6, F2"
},
{
"code": null,
"e": 25356,
"s": 25269,
"text": "Quiz of this QuestionPlease comment below if you find anything wrong in the above post"
},
{
"code": null,
"e": 25361,
"s": 25356,
"text": "ISRO"
},
{
"code": null,
"e": 25459,
"s": 25361,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25493,
"s": 25459,
"text": "ISRO | ISRO CS 2011 | Question 26"
},
{
"code": null,
"e": 25533,
"s": 25493,
"text": "ISRO | ISRO CS 2017 - May | Question 21"
},
{
"code": null,
"e": 25567,
"s": 25533,
"text": "ISRO | ISRO CS 2013 | Question 54"
},
{
"code": null,
"e": 25601,
"s": 25567,
"text": "ISRO | ISRO CS 2011 | Question 13"
},
{
"code": null,
"e": 25634,
"s": 25601,
"text": "ISRO | ISRO CS 2008 | Question 1"
},
{
"code": null,
"e": 25667,
"s": 25634,
"text": "ISRO | ISRO CS 2013 | Question 4"
},
{
"code": null,
"e": 25701,
"s": 25667,
"text": "ISRO | ISRO CS 2016 | Question 49"
},
{
"code": null,
"e": 25735,
"s": 25701,
"text": "ISRO | ISRO CS 2018 | Question 10"
},
{
"code": null,
"e": 25769,
"s": 25735,
"text": "ISRO | ISRO CS 2016 | Question 41"
}
]
|
Streamlit 101: An in-depth introduction | by Shail Deliwala | Towards Data Science | Streamlit is an awesome new tool that allows engineers to quickly build highly interactive web applications around their data, machine learning models, and pretty much anything.
The best thing about Streamlit is it doesn’t require any knowledge of web development. If you know Python, you’re good to go!
Here’s the full code for this tutorial if you would like to follow along as you progress through the tutorial.
In one sentence: it gives you a blazingly fast, iterative, and interactive development loop.
Split your screen so your code editing tool is in one half and your browser is in the other, edit your code, and see your app updated instantly! My favorite part about Streamlit is how — in a matter of hours—it lets you go from Jupyter Notebook to a sleek web app worthy of presenting to a client.
Installation steps:
$ pip install streamlit$ streamlit hello
Imports:
import pandas as pdimport streamlit as stimport plotly.express as px
To run your Streamlit app:
$ streamlit run app.py
Airbnb does not officially release any of its data. Another group called Inside Airbnb periodically releases Airbnb listings and review data.
@st.cachedef get_data(): url = "http://data.insideairbnb.com/united-states/ny/new-york-city/2019-09-12/visualisations/listings.csv" return pd.read_csv(url)df = get_data()
The st.cache decorator indicates that Streamlit will perform internal magic so that the data will be downloaded only once and cached for future use.
Behind the scenes, Streamlit keeps track of the function name, the code in the function body, and the input arguments we pass in the function call. Upon first invocation, it stores the function’s return value in a local cache. Upon subsequent invocations of the function with the exact same arguments, Streamlit returns the result from the local cache.
The main limitation of Streamlit’s data caching is that it cannot keep track of changes to the data happening outside the function body.
st.title("Streamlit 101: An in-depth introduction")st.markdown("Welcome to this in-depth introduction to [...].")st.header("Customary quote")st.markdown("> I just love to go home, no matter where I am [...]")
The above code renders the following.
st.title is suitable for the main title. For section titles, use st.header or st.subheader.
st.markdown renders any string written using Github-flavored Markdown. It also supports HTML but Streamlit advises against allowing it due to potential user security concerns.
This is the first thing we usually do when starting an exploratory analysis. st.dataframe renders pandas dataframes.
st.dataframe(df.head())
I love how it allows sorting the dataframe upon clicking any column header (notice the little chevron in the host_name header).
There’s a handy little button at the top right to switch to full-screen view. Great for viewing larger data frames without having to scroll too much.
It also supports styled dataframes.
st.code renders single-line as well as multi-line code blocks. There is also an option to specify the programming language.
st.code("""@st.cachedef get_data(): url = "http://data.insideairbnb.com/[...]" return pd.read_csv(url)""", language="python")
Alternatively, using a with st.echo block executes the code within it and also renders it as a code section in the app.
Where are the most expensive Airbnb properties located?
st.map displays locations on a map without having to write a single line of boilerplate code to prepare a map object. The only requirement is that the dataframe must contain columns named lat/latitude or lon/longitude.
Unsurprisingly, Manhattan island has the highest concentration of expensive Airbnbs. Some are scattered over Brooklyn. The heftiest price tag is $10000.
st.deck_gl_chart allows more parameters to create more interesting and customized maps.
Streamlit has a multiselect widget that allows selecting or removing from a list of items. This lets us build a column selector widget for a dataframe.
cols = ["name", "host_name", "neighbourhood", "room_type", "price"]st_ms = st.multiselect("Columns", df.columns.tolist(), default=cols)
The multiselect widget is one of the most powerful and handy tools in Streamlit. One use aside from column selection is to filter a dataframe based on one or more values of a column. Another is to pick subplots for, say, a side-by-side comparison of ROC curves based on predictions of different models.
Which room types are most expensive on average?
st.table displays a static table. However, you cannot sort it by clicking a column header.
st.table(df.groupby("room_type").price.mean().reset_index()\.round(2).sort_values("price", ascending=False)\.assign(avg_price=lambda x: x.pop("price").apply(lambda y: "%.2f" % y)))
Sonder (NYC) is at the top with 387 property listings. Blueground is second with 240 listings. Following are randomly chosen listings from the two rendered as JSON using st.json.
Streamlit renders fully interactive JSON sections with support to collapse/expand objects and arrays, and copy-to-clipboard functionality.
We display a histogram of property prices displayed as a Plotly chart using st.plotly_chart.
We use st.slider to provide a slider that allows selecting a custom range for the histogram. We tuck it away into a sidebar.
values = st.sidebar.slider(“Price range”, float(df.price.min()), 1000., (50., 300.))f = px.histogram(df.query(f”price.between{values}”), x=”price”, nbins=15, title=”Price distribution”)f.update_xaxes(title=”Price”)f.update_yaxes(title=”No. of listings”)st.plotly_chart(f)
The tallest bar corresponds to the $60–79 price range, which has 7229 listings.
Note: For this tutorial, I limited the maximum value of the slider to 1000 so the range selection would be clearly visible.
availability_365 indicates the number of days a property is available throughout the year. We examine summary statistics of availability_365 by neighborhood group.
Using st.radio, we show a list of neighborhood groups to select from. By default, we exclude listings with price ≥ $200 and provide an Include expensive listings checkbox using st.checkbox.
st.write is, sort of, an umbrella function that accepts strings, dataframes, dictionaries, plots, maps, and so on (full list in the documentation). It allows passing in multiple arguments, and its behavior depends on their types.
st.write("Using a radio button restricts selection to only one option at a time.")neighborhood = st.radio("Neighborhood", df.neighbourhood_group.unique())show_exp = st.checkbox("Include expensive listings")
At 169 days, Brooklyn has the lowest average availability. At 226, Staten Island has the highest average availability. If we include expensive listings (price>=$200), the numbers are 171 and 230 respectively.
Note: There are 18431 records with availability_365 0 (zero), which I've ignored.
st.pyplot renders plots built using matplotlib like the one below.
df.query("availability_365>0")\.groupby("neighbourhood_group")\.availability_365.mean()\.plot.bar(rot=0)\.set(title="Average availability by neighborhood group",xlabel="Neighborhood group", ylabel="Avg. availability (in no. of days)")st.pyplot()
We want to view properties with number of reviews falling within a range that we can customize.
In the sidebar, we provide a numeric range selector using st.number_input. If minimum > maximum, we display an error message using st.error.
minimum = st.sidebar.number_input("Minimum", min_value=0)maximum = st.sidebar.number_input("Maximum", min_value=0, value=5)if minimum > maximum: st.error("Please enter a valid range")else: df.query("@minimum<=number_of_reviews<=@maximum")
486 is the highest number of reviews. Two listings have that many reviews. Both are in the East Elmhurst neighborhood and are private rooms with prices $65 and $45. In general, listings with >400 reviews are priced below $100. A few are between $100 and $200, and only one is priced above $200.
Use st.image to show images of cats, puppies, feature importance plots, tagged video frames, and so on.
Now for a bit of fun.
pics = { "Cat": "https://cdn.pixabay.com/photo/2016/09/24/22/20/cat-1692702_960_720.jpg", "Puppy": "https://cdn.pixabay.com/photo/2019/03/15/19/19/puppy-4057786_960_720.jpg", "Sci-fi city": "https://storage.needpix.com/rsynced_images/science-fiction-2971848_1280.jpg"}pic = st.selectbox("Picture choices", list(pics.keys()), 0)st.image(pics[pic], use_column_width=True, caption=pics[pic])
Notice how in the Number of Reviews section above, we wrote df.query("@minimum<=number_of_reviews<=@maximum")on its own line without wrapping it in a call to st.dataframe. This still rendered a dataframe because Streamlit detects a variable or literal on its own line and uses st.write to render it.
We’ve covered interactive widgets, dataframes, tables, images, Markdown, plot rendering, maps, and textual content. Streamlit allows modification of existing elements and showing progress, which we have not covered in this tutorial. For instance, you can add rows to an existing table or add new data to a chart. You can also show a progress bar for long-running processes.
Congratulations, you’re all set to start building your own Streamlit apps.
When you run the app created for this tutorial, do click the Celebrate! button rendered by the code below.
st.markdown("## Party time!")st.write("Yay! You're done with this tutorial of Streamlit. Click below to celebrate.")btn = st.button("Celebrate!")if btn: st.balloons()
My next article will be about my silver medal winning (rank 35 / top 4%) solution to Walmart Shopping Trip Type Classification competition on Kaggle.
Full code of the Streamlit app created for this tutorial: https://github.com/shaildeliwala/experiments/blob/master/streamlit.py
From Adrien Treuille, the co-founder of Streamlit: https://towardsdatascience.com/coding-ml-tools-like-you-code-ml-models-ddba3357eace
Streamlit API documentation: https://streamlit.io/docs/api.html
Streamlit tutorial: https://streamlit.io/docs/tutorial2/
Streamlit demo video: https://youtu.be/B2iAodr0fOo
Airbnb NYC listings data (unofficial): http://data.insideairbnb.com/united-states/ny/new-york-city/2019-09-12/visualisations/listings.csv
Plotly histogram documentation: https://plot.ly/python/histograms/ | [
{
"code": null,
"e": 350,
"s": 172,
"text": "Streamlit is an awesome new tool that allows engineers to quickly build highly interactive web applications around their data, machine learning models, and pretty much anything."
},
{
"code": null,
"e": 476,
"s": 350,
"text": "The best thing about Streamlit is it doesn’t require any knowledge of web development. If you know Python, you’re good to go!"
},
{
"code": null,
"e": 587,
"s": 476,
"text": "Here’s the full code for this tutorial if you would like to follow along as you progress through the tutorial."
},
{
"code": null,
"e": 680,
"s": 587,
"text": "In one sentence: it gives you a blazingly fast, iterative, and interactive development loop."
},
{
"code": null,
"e": 978,
"s": 680,
"text": "Split your screen so your code editing tool is in one half and your browser is in the other, edit your code, and see your app updated instantly! My favorite part about Streamlit is how — in a matter of hours—it lets you go from Jupyter Notebook to a sleek web app worthy of presenting to a client."
},
{
"code": null,
"e": 998,
"s": 978,
"text": "Installation steps:"
},
{
"code": null,
"e": 1039,
"s": 998,
"text": "$ pip install streamlit$ streamlit hello"
},
{
"code": null,
"e": 1048,
"s": 1039,
"text": "Imports:"
},
{
"code": null,
"e": 1117,
"s": 1048,
"text": "import pandas as pdimport streamlit as stimport plotly.express as px"
},
{
"code": null,
"e": 1144,
"s": 1117,
"text": "To run your Streamlit app:"
},
{
"code": null,
"e": 1167,
"s": 1144,
"text": "$ streamlit run app.py"
},
{
"code": null,
"e": 1309,
"s": 1167,
"text": "Airbnb does not officially release any of its data. Another group called Inside Airbnb periodically releases Airbnb listings and review data."
},
{
"code": null,
"e": 1486,
"s": 1309,
"text": "@st.cachedef get_data(): url = \"http://data.insideairbnb.com/united-states/ny/new-york-city/2019-09-12/visualisations/listings.csv\" return pd.read_csv(url)df = get_data()"
},
{
"code": null,
"e": 1635,
"s": 1486,
"text": "The st.cache decorator indicates that Streamlit will perform internal magic so that the data will be downloaded only once and cached for future use."
},
{
"code": null,
"e": 1988,
"s": 1635,
"text": "Behind the scenes, Streamlit keeps track of the function name, the code in the function body, and the input arguments we pass in the function call. Upon first invocation, it stores the function’s return value in a local cache. Upon subsequent invocations of the function with the exact same arguments, Streamlit returns the result from the local cache."
},
{
"code": null,
"e": 2125,
"s": 1988,
"text": "The main limitation of Streamlit’s data caching is that it cannot keep track of changes to the data happening outside the function body."
},
{
"code": null,
"e": 2334,
"s": 2125,
"text": "st.title(\"Streamlit 101: An in-depth introduction\")st.markdown(\"Welcome to this in-depth introduction to [...].\")st.header(\"Customary quote\")st.markdown(\"> I just love to go home, no matter where I am [...]\")"
},
{
"code": null,
"e": 2372,
"s": 2334,
"text": "The above code renders the following."
},
{
"code": null,
"e": 2464,
"s": 2372,
"text": "st.title is suitable for the main title. For section titles, use st.header or st.subheader."
},
{
"code": null,
"e": 2640,
"s": 2464,
"text": "st.markdown renders any string written using Github-flavored Markdown. It also supports HTML but Streamlit advises against allowing it due to potential user security concerns."
},
{
"code": null,
"e": 2757,
"s": 2640,
"text": "This is the first thing we usually do when starting an exploratory analysis. st.dataframe renders pandas dataframes."
},
{
"code": null,
"e": 2781,
"s": 2757,
"text": "st.dataframe(df.head())"
},
{
"code": null,
"e": 2909,
"s": 2781,
"text": "I love how it allows sorting the dataframe upon clicking any column header (notice the little chevron in the host_name header)."
},
{
"code": null,
"e": 3059,
"s": 2909,
"text": "There’s a handy little button at the top right to switch to full-screen view. Great for viewing larger data frames without having to scroll too much."
},
{
"code": null,
"e": 3095,
"s": 3059,
"text": "It also supports styled dataframes."
},
{
"code": null,
"e": 3219,
"s": 3095,
"text": "st.code renders single-line as well as multi-line code blocks. There is also an option to specify the programming language."
},
{
"code": null,
"e": 3351,
"s": 3219,
"text": "st.code(\"\"\"@st.cachedef get_data(): url = \"http://data.insideairbnb.com/[...]\" return pd.read_csv(url)\"\"\", language=\"python\")"
},
{
"code": null,
"e": 3471,
"s": 3351,
"text": "Alternatively, using a with st.echo block executes the code within it and also renders it as a code section in the app."
},
{
"code": null,
"e": 3527,
"s": 3471,
"text": "Where are the most expensive Airbnb properties located?"
},
{
"code": null,
"e": 3746,
"s": 3527,
"text": "st.map displays locations on a map without having to write a single line of boilerplate code to prepare a map object. The only requirement is that the dataframe must contain columns named lat/latitude or lon/longitude."
},
{
"code": null,
"e": 3899,
"s": 3746,
"text": "Unsurprisingly, Manhattan island has the highest concentration of expensive Airbnbs. Some are scattered over Brooklyn. The heftiest price tag is $10000."
},
{
"code": null,
"e": 3987,
"s": 3899,
"text": "st.deck_gl_chart allows more parameters to create more interesting and customized maps."
},
{
"code": null,
"e": 4139,
"s": 3987,
"text": "Streamlit has a multiselect widget that allows selecting or removing from a list of items. This lets us build a column selector widget for a dataframe."
},
{
"code": null,
"e": 4275,
"s": 4139,
"text": "cols = [\"name\", \"host_name\", \"neighbourhood\", \"room_type\", \"price\"]st_ms = st.multiselect(\"Columns\", df.columns.tolist(), default=cols)"
},
{
"code": null,
"e": 4578,
"s": 4275,
"text": "The multiselect widget is one of the most powerful and handy tools in Streamlit. One use aside from column selection is to filter a dataframe based on one or more values of a column. Another is to pick subplots for, say, a side-by-side comparison of ROC curves based on predictions of different models."
},
{
"code": null,
"e": 4626,
"s": 4578,
"text": "Which room types are most expensive on average?"
},
{
"code": null,
"e": 4717,
"s": 4626,
"text": "st.table displays a static table. However, you cannot sort it by clicking a column header."
},
{
"code": null,
"e": 4898,
"s": 4717,
"text": "st.table(df.groupby(\"room_type\").price.mean().reset_index()\\.round(2).sort_values(\"price\", ascending=False)\\.assign(avg_price=lambda x: x.pop(\"price\").apply(lambda y: \"%.2f\" % y)))"
},
{
"code": null,
"e": 5077,
"s": 4898,
"text": "Sonder (NYC) is at the top with 387 property listings. Blueground is second with 240 listings. Following are randomly chosen listings from the two rendered as JSON using st.json."
},
{
"code": null,
"e": 5216,
"s": 5077,
"text": "Streamlit renders fully interactive JSON sections with support to collapse/expand objects and arrays, and copy-to-clipboard functionality."
},
{
"code": null,
"e": 5309,
"s": 5216,
"text": "We display a histogram of property prices displayed as a Plotly chart using st.plotly_chart."
},
{
"code": null,
"e": 5434,
"s": 5309,
"text": "We use st.slider to provide a slider that allows selecting a custom range for the histogram. We tuck it away into a sidebar."
},
{
"code": null,
"e": 5706,
"s": 5434,
"text": "values = st.sidebar.slider(“Price range”, float(df.price.min()), 1000., (50., 300.))f = px.histogram(df.query(f”price.between{values}”), x=”price”, nbins=15, title=”Price distribution”)f.update_xaxes(title=”Price”)f.update_yaxes(title=”No. of listings”)st.plotly_chart(f)"
},
{
"code": null,
"e": 5786,
"s": 5706,
"text": "The tallest bar corresponds to the $60–79 price range, which has 7229 listings."
},
{
"code": null,
"e": 5910,
"s": 5786,
"text": "Note: For this tutorial, I limited the maximum value of the slider to 1000 so the range selection would be clearly visible."
},
{
"code": null,
"e": 6074,
"s": 5910,
"text": "availability_365 indicates the number of days a property is available throughout the year. We examine summary statistics of availability_365 by neighborhood group."
},
{
"code": null,
"e": 6264,
"s": 6074,
"text": "Using st.radio, we show a list of neighborhood groups to select from. By default, we exclude listings with price ≥ $200 and provide an Include expensive listings checkbox using st.checkbox."
},
{
"code": null,
"e": 6494,
"s": 6264,
"text": "st.write is, sort of, an umbrella function that accepts strings, dataframes, dictionaries, plots, maps, and so on (full list in the documentation). It allows passing in multiple arguments, and its behavior depends on their types."
},
{
"code": null,
"e": 6701,
"s": 6494,
"text": "st.write(\"Using a radio button restricts selection to only one option at a time.\")neighborhood = st.radio(\"Neighborhood\", df.neighbourhood_group.unique())show_exp = st.checkbox(\"Include expensive listings\")"
},
{
"code": null,
"e": 6910,
"s": 6701,
"text": "At 169 days, Brooklyn has the lowest average availability. At 226, Staten Island has the highest average availability. If we include expensive listings (price>=$200), the numbers are 171 and 230 respectively."
},
{
"code": null,
"e": 6992,
"s": 6910,
"text": "Note: There are 18431 records with availability_365 0 (zero), which I've ignored."
},
{
"code": null,
"e": 7059,
"s": 6992,
"text": "st.pyplot renders plots built using matplotlib like the one below."
},
{
"code": null,
"e": 7305,
"s": 7059,
"text": "df.query(\"availability_365>0\")\\.groupby(\"neighbourhood_group\")\\.availability_365.mean()\\.plot.bar(rot=0)\\.set(title=\"Average availability by neighborhood group\",xlabel=\"Neighborhood group\", ylabel=\"Avg. availability (in no. of days)\")st.pyplot()"
},
{
"code": null,
"e": 7401,
"s": 7305,
"text": "We want to view properties with number of reviews falling within a range that we can customize."
},
{
"code": null,
"e": 7542,
"s": 7401,
"text": "In the sidebar, we provide a numeric range selector using st.number_input. If minimum > maximum, we display an error message using st.error."
},
{
"code": null,
"e": 7787,
"s": 7542,
"text": "minimum = st.sidebar.number_input(\"Minimum\", min_value=0)maximum = st.sidebar.number_input(\"Maximum\", min_value=0, value=5)if minimum > maximum: st.error(\"Please enter a valid range\")else: df.query(\"@minimum<=number_of_reviews<=@maximum\")"
},
{
"code": null,
"e": 8082,
"s": 7787,
"text": "486 is the highest number of reviews. Two listings have that many reviews. Both are in the East Elmhurst neighborhood and are private rooms with prices $65 and $45. In general, listings with >400 reviews are priced below $100. A few are between $100 and $200, and only one is priced above $200."
},
{
"code": null,
"e": 8186,
"s": 8082,
"text": "Use st.image to show images of cats, puppies, feature importance plots, tagged video frames, and so on."
},
{
"code": null,
"e": 8208,
"s": 8186,
"text": "Now for a bit of fun."
},
{
"code": null,
"e": 8606,
"s": 8208,
"text": "pics = { \"Cat\": \"https://cdn.pixabay.com/photo/2016/09/24/22/20/cat-1692702_960_720.jpg\", \"Puppy\": \"https://cdn.pixabay.com/photo/2019/03/15/19/19/puppy-4057786_960_720.jpg\", \"Sci-fi city\": \"https://storage.needpix.com/rsynced_images/science-fiction-2971848_1280.jpg\"}pic = st.selectbox(\"Picture choices\", list(pics.keys()), 0)st.image(pics[pic], use_column_width=True, caption=pics[pic])"
},
{
"code": null,
"e": 8906,
"s": 8606,
"text": "Notice how in the Number of Reviews section above, we wrote df.query(\"@minimum<=number_of_reviews<=@maximum\")on its own line without wrapping it in a call to st.dataframe. This still rendered a dataframe because Streamlit detects a variable or literal on its own line and uses st.write to render it."
},
{
"code": null,
"e": 9280,
"s": 8906,
"text": "We’ve covered interactive widgets, dataframes, tables, images, Markdown, plot rendering, maps, and textual content. Streamlit allows modification of existing elements and showing progress, which we have not covered in this tutorial. For instance, you can add rows to an existing table or add new data to a chart. You can also show a progress bar for long-running processes."
},
{
"code": null,
"e": 9355,
"s": 9280,
"text": "Congratulations, you’re all set to start building your own Streamlit apps."
},
{
"code": null,
"e": 9462,
"s": 9355,
"text": "When you run the app created for this tutorial, do click the Celebrate! button rendered by the code below."
},
{
"code": null,
"e": 9632,
"s": 9462,
"text": "st.markdown(\"## Party time!\")st.write(\"Yay! You're done with this tutorial of Streamlit. Click below to celebrate.\")btn = st.button(\"Celebrate!\")if btn: st.balloons()"
},
{
"code": null,
"e": 9782,
"s": 9632,
"text": "My next article will be about my silver medal winning (rank 35 / top 4%) solution to Walmart Shopping Trip Type Classification competition on Kaggle."
},
{
"code": null,
"e": 9910,
"s": 9782,
"text": "Full code of the Streamlit app created for this tutorial: https://github.com/shaildeliwala/experiments/blob/master/streamlit.py"
},
{
"code": null,
"e": 10045,
"s": 9910,
"text": "From Adrien Treuille, the co-founder of Streamlit: https://towardsdatascience.com/coding-ml-tools-like-you-code-ml-models-ddba3357eace"
},
{
"code": null,
"e": 10109,
"s": 10045,
"text": "Streamlit API documentation: https://streamlit.io/docs/api.html"
},
{
"code": null,
"e": 10166,
"s": 10109,
"text": "Streamlit tutorial: https://streamlit.io/docs/tutorial2/"
},
{
"code": null,
"e": 10217,
"s": 10166,
"text": "Streamlit demo video: https://youtu.be/B2iAodr0fOo"
},
{
"code": null,
"e": 10355,
"s": 10217,
"text": "Airbnb NYC listings data (unofficial): http://data.insideairbnb.com/united-states/ny/new-york-city/2019-09-12/visualisations/listings.csv"
}
]
|
Java Program to shift array elements to the right | Let us first create an int array −
int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
Now, shift array elements to the right with arraycopy() and placing the elements correctly so that it gets shifted to the right −
System.arraycopy(arr, 0, arr, 1, arr.length - 1);
Live Demo
import java.util.Arrays;
public class Demo {
public static void main(String[] argv) throws Exception {
int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
System.out.println("Initial array...\n"+Arrays.toString(arr));
System.arraycopy(arr, 0, arr, 1, arr.length - 1);
System.out.println("Array after shifting to the right...");
System.out.println(Arrays.toString(arr));
}
}
Initial array...
[10, 20, 30, 40, 50, 60, 70, 80, 90]
Array after shifting to the right...
[10, 10, 20, 30, 40, 50, 60, 70, 80] | [
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Let us first create an int array −"
},
{
"code": null,
"e": 1149,
"s": 1097,
"text": "int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };"
},
{
"code": null,
"e": 1279,
"s": 1149,
"text": "Now, shift array elements to the right with arraycopy() and placing the elements correctly so that it gets shifted to the right −"
},
{
"code": null,
"e": 1329,
"s": 1279,
"text": "System.arraycopy(arr, 0, arr, 1, arr.length - 1);"
},
{
"code": null,
"e": 1340,
"s": 1329,
"text": " Live Demo"
},
{
"code": null,
"e": 1750,
"s": 1340,
"text": "import java.util.Arrays;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n int[] arr = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };\n System.out.println(\"Initial array...\\n\"+Arrays.toString(arr));\n System.arraycopy(arr, 0, arr, 1, arr.length - 1);\n System.out.println(\"Array after shifting to the right...\");\n System.out.println(Arrays.toString(arr));\n }\n}"
},
{
"code": null,
"e": 1878,
"s": 1750,
"text": "Initial array...\n[10, 20, 30, 40, 50, 60, 70, 80, 90]\nArray after shifting to the right...\n[10, 10, 20, 30, 40, 50, 60, 70, 80]"
}
]
|
How to enable app cache for webview in android? | This example demonstrate about How to enable app cache for webview in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity"
android:orientation = "vertical">
<WebView
android:id = "@+id/web_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show tutorialspoint.com.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.setCancelable(false);
WebView web_view = findViewById(R.id.web_view);
web_view.requestFocus();
web_view.getSettings().setLightTouchEnabled(true);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.getSettings().setGeolocationEnabled(true);
web_view.setSoundEffectsEnabled(true);
web_view.getSettings().setAppCacheEnabled(true);
web_view.loadUrl("https://www.tutorialspoint.com/");
web_view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100) {
progressDialog.show();
}
if (progress = = 100) {
progressDialog.dismiss();
}
}
});
}
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
package = "com.example.myapplication">
<uses-permission android:name = "android.permission.INTERNET"/>
<application
android:allowBackup = "true"
android:icon = "@mipmap/ic_launcher"
android:label = "@string/app_name"
android:roundIcon = "@mipmap/ic_launcher_round"
android:supportsRtl = "true"
android:theme = "@style/AppTheme">
<activity android:name = ".MainActivity">
<intent-filter>
<action android:name = "android.intent.action.MAIN" />
<category android:name = "android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "This example demonstrate about How to enable app cache for webview in android."
},
{
"code": null,
"e": 1270,
"s": 1141,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1335,
"s": 1270,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1902,
"s": 1335,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:orientation = \"vertical\">\n <WebView\n android:id = \"@+id/web_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1972,
"s": 1902,
"text": "In the above code, we have taken web view to show tutorialspoint.com."
},
{
"code": null,
"e": 2029,
"s": 1972,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3578,
"s": 2029,
"text": "package com.example.myapplication;\nimport android.app.ProgressDialog;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.webkit.WebChromeClient;\nimport android.webkit.WebSettings;\nimport android.webkit.WebView;\nimport android.widget.EditText;\npublic class MainActivity extends AppCompatActivity {\n @RequiresApi(api = Build.VERSION_CODES.P)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final ProgressDialog progressDialog = new ProgressDialog(this);\n progressDialog.setMessage(\"Loading Data...\");\n progressDialog.setCancelable(false);\n WebView web_view = findViewById(R.id.web_view);\n web_view.requestFocus();\n web_view.getSettings().setLightTouchEnabled(true);\n web_view.getSettings().setJavaScriptEnabled(true);\n web_view.getSettings().setGeolocationEnabled(true);\n web_view.setSoundEffectsEnabled(true);\n web_view.getSettings().setAppCacheEnabled(true);\n web_view.loadUrl(\"https://www.tutorialspoint.com/\");\n web_view.setWebChromeClient(new WebChromeClient() {\n public void onProgressChanged(WebView view, int progress) {\n if (progress < 100) {\n progressDialog.show();\n }\n if (progress = = 100) {\n progressDialog.dismiss();\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3633,
"s": 3578,
"text": "Step 4 − Add the following code to AndroidManifest.xml"
},
{
"code": null,
"e": 4410,
"s": 3633,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4757,
"s": 4410,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 4797,
"s": 4757,
"text": "Click here to download the project code"
}
]
|
Hiding of all overloaded methods in base class in C++ | In C++, we can use the function overloading techniques. But if some base class has one method in overloaded form (different function signature with the same name), and the derived class redefines one of the function which is present inside the base, then all of the overloaded version of that function will be hidden from the derived class.
Let us see one example to get the clear idea.
#include <iostream>
using namespace std;
class MyBaseClass {
public:
void my_function() {
cout << "This is my_function. This is taking no arguments" << endl;
}
void my_function(int x) {
cout << "This is my_function. This is taking one argument x" << endl;
}
};
class MyDerivedClass : public MyBaseClass {
public:
void my_function() {
cout << "This is my_function. From derived class, This is taking no arguments" << endl;
}
};
main() {
MyDerivedClass ob;
ob.my_function(10);
}
[Error] no matching function for call to 'MyDerivedClass::my_function(int)'
[Note] candidate is:
[Note] void MyDerivedClass::my_function()
[Note] candidate expects 0 arguments, 1 provided | [
{
"code": null,
"e": 1403,
"s": 1062,
"text": "In C++, we can use the function overloading techniques. But if some base class has one method in overloaded form (different function signature with the same name), and the derived class redefines one of the function which is present inside the base, then all of the overloaded version of that function will be hidden from the derived class."
},
{
"code": null,
"e": 1449,
"s": 1403,
"text": "Let us see one example to get the clear idea."
},
{
"code": null,
"e": 2001,
"s": 1449,
"text": "#include <iostream>\nusing namespace std;\nclass MyBaseClass {\n public:\n void my_function() {\n cout << \"This is my_function. This is taking no arguments\" << endl;\n }\n void my_function(int x) {\n cout << \"This is my_function. This is taking one argument x\" << endl;\n }\n};\nclass MyDerivedClass : public MyBaseClass {\n public:\n void my_function() {\n cout << \"This is my_function. From derived class, This is taking no arguments\" << endl;\n }\n};\nmain() {\n MyDerivedClass ob;\n ob.my_function(10);\n}"
},
{
"code": null,
"e": 2189,
"s": 2001,
"text": "[Error] no matching function for call to 'MyDerivedClass::my_function(int)'\n[Note] candidate is:\n[Note] void MyDerivedClass::my_function()\n[Note] candidate expects 0 arguments, 1 provided"
}
]
|
map erase() function in C++ STL - GeeksforGeeks | 19 Nov, 2020
map::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range.
Syntax for erasing a key:
map_name.erase(key)
Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container.
Return Value: The function returns 1 if the key element is found in the map else returns 0.
Below program illustrate the above syntax:
C++
// C++ program to illustrate// map::erase(key)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 5, 50 }); // prints the elements cout << "The map before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given keys mp.erase(1); mp.erase(2); // prints the elements cout << "\nThe map after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The map before using erase() is :
KEY ELEMENT
1 40
2 30
3 60
5 50
The map after applying erase() is :
KEY ELEMENT
3 60
5 50
Syntax for removing a position:
map_name.erase(iterator position)
Parameters: The function accepts one mandatory parameter position which specifies the iterator that is the reference to the position of the element to be erased.
Return Value: The function does not return anything.
Below program illustrate the above syntax:
C++
// C++ program to illustrate// map::erase(iteratorposition)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 5, 50 }); // prints the elements cout << "The map before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase given position auto it = mp.find(2); mp.erase(it); auto it1 = mp.find(5); mp.erase(it1); // prints the elements cout << "\nThe map after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The map before using erase() is :
KEY ELEMENT
1 40
2 30
3 60
5 50
The map after applying erase() is :
KEY ELEMENT
1 40
3 60
Syntax for erasing a given range:
map_name.erase(iterator position1, iterator position2)
Parameters: The function accepts two mandatory parameters which are described below:
position1 – specifies the iterator that is the reference to the element from which removal is to be done.
position2 – specifies the iterator that is the reference to the element upto which removal is to be done.
Return Value: The function does not returns anything. It removes all the elements in the given range of iterators.
Program below illustrates the above syntax:
C++
// C++ program to illustrate// map::erase(iteratorposition1, iteratorposition2)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << "The map before using erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } // function to erase in a given range // find() returns the iterator reference to // the position where the element is auto it1 = mp.find(2); auto it2 = mp.find(5); mp.erase(it1, it2); // prints the elements cout << "\nThe map after applying erase() is : \n"; cout << "KEY\tELEMENT\n"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\t' << itr->second << '\n'; } return 0;}
The map before using erase() is :
KEY ELEMENT
1 40
2 30
3 60
5 50
The map after applying erase() is :
KEY ELEMENT
1 40
5 50
papun007
arorakashish0911
CPP-Functions
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
C++ Classes and Objects
Constructors in C++
Socket Programming in C/C++
Operator Overloading in C++
Copy Constructor in C++
rand() and srand() in C/C++
Virtual Function in C++
Templates in C++ with Examples
unordered_map in C++ STL | [
{
"code": null,
"e": 24107,
"s": 24079,
"text": "\n19 Nov, 2020"
},
{
"code": null,
"e": 24289,
"s": 24107,
"text": "map::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range. "
},
{
"code": null,
"e": 24315,
"s": 24289,
"text": "Syntax for erasing a key:"
},
{
"code": null,
"e": 24336,
"s": 24315,
"text": "map_name.erase(key)\n"
},
{
"code": null,
"e": 24457,
"s": 24336,
"text": "Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container. "
},
{
"code": null,
"e": 24550,
"s": 24457,
"text": "Return Value: The function returns 1 if the key element is found in the map else returns 0. "
},
{
"code": null,
"e": 24594,
"s": 24550,
"text": "Below program illustrate the above syntax: "
},
{
"code": null,
"e": 24598,
"s": 24594,
"text": "C++"
},
{
"code": "// C++ program to illustrate// map::erase(key)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 5, 50 }); // prints the elements cout << \"The map before using erase() is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } // function to erase given keys mp.erase(1); mp.erase(2); // prints the elements cout << \"\\nThe map after applying erase() is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}",
"e": 25453,
"s": 24598,
"text": null
},
{
"code": null,
"e": 25608,
"s": 25453,
"text": "The map before using erase() is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n5 50\n\nThe map after applying erase() is : \nKEY ELEMENT\n3 60\n5 50\n\n\n\n"
},
{
"code": null,
"e": 25643,
"s": 25610,
"text": "Syntax for removing a position: "
},
{
"code": null,
"e": 25678,
"s": 25643,
"text": "map_name.erase(iterator position)\n"
},
{
"code": null,
"e": 25841,
"s": 25678,
"text": "Parameters: The function accepts one mandatory parameter position which specifies the iterator that is the reference to the position of the element to be erased. "
},
{
"code": null,
"e": 25895,
"s": 25841,
"text": "Return Value: The function does not return anything. "
},
{
"code": null,
"e": 25939,
"s": 25895,
"text": "Below program illustrate the above syntax: "
},
{
"code": null,
"e": 25943,
"s": 25939,
"text": "C++"
},
{
"code": "// C++ program to illustrate// map::erase(iteratorposition)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 5, 50 }); // prints the elements cout << \"The map before using erase() is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } // function to erase given position auto it = mp.find(2); mp.erase(it); auto it1 = mp.find(5); mp.erase(it1); // prints the elements cout << \"\\nThe map after applying erase() is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}",
"e": 26869,
"s": 25943,
"text": null
},
{
"code": null,
"e": 27024,
"s": 26869,
"text": "The map before using erase() is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n5 50\n\nThe map after applying erase() is : \nKEY ELEMENT\n1 40\n3 60\n\n\n\n"
},
{
"code": null,
"e": 27061,
"s": 27026,
"text": "Syntax for erasing a given range: "
},
{
"code": null,
"e": 27117,
"s": 27061,
"text": "map_name.erase(iterator position1, iterator position2)\n"
},
{
"code": null,
"e": 27203,
"s": 27117,
"text": "Parameters: The function accepts two mandatory parameters which are described below: "
},
{
"code": null,
"e": 27309,
"s": 27203,
"text": "position1 – specifies the iterator that is the reference to the element from which removal is to be done."
},
{
"code": null,
"e": 27415,
"s": 27309,
"text": "position2 – specifies the iterator that is the reference to the element upto which removal is to be done."
},
{
"code": null,
"e": 27530,
"s": 27415,
"text": "Return Value: The function does not returns anything. It removes all the elements in the given range of iterators."
},
{
"code": null,
"e": 27575,
"s": 27530,
"text": "Program below illustrates the above syntax: "
},
{
"code": null,
"e": 27579,
"s": 27575,
"text": "C++"
},
{
"code": "// C++ program to illustrate// map::erase(iteratorposition1, iteratorposition2)#include <bits/stdc++.h>using namespace std; int main(){ // initialize container map<int, int> mp; // insert elements in random order mp.insert({ 2, 30 }); mp.insert({ 1, 40 }); mp.insert({ 3, 60 }); mp.insert({ 2, 20 }); mp.insert({ 5, 50 }); // prints the elements cout << \"The map before using erase() is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } // function to erase in a given range // find() returns the iterator reference to // the position where the element is auto it1 = mp.find(2); auto it2 = mp.find(5); mp.erase(it1, it2); // prints the elements cout << \"\\nThe map after applying erase() is : \\n\"; cout << \"KEY\\tELEMENT\\n\"; for (auto itr = mp.begin(); itr != mp.end(); ++itr) { cout << itr->first << '\\t' << itr->second << '\\n'; } return 0;}",
"e": 28627,
"s": 27579,
"text": null
},
{
"code": null,
"e": 28782,
"s": 28627,
"text": "The map before using erase() is : \nKEY ELEMENT\n1 40\n2 30\n3 60\n5 50\n\nThe map after applying erase() is : \nKEY ELEMENT\n1 40\n5 50\n\n\n\n"
},
{
"code": null,
"e": 28793,
"s": 28784,
"text": "papun007"
},
{
"code": null,
"e": 28810,
"s": 28793,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28824,
"s": 28810,
"text": "CPP-Functions"
},
{
"code": null,
"e": 28832,
"s": 28824,
"text": "cpp-map"
},
{
"code": null,
"e": 28836,
"s": 28832,
"text": "STL"
},
{
"code": null,
"e": 28840,
"s": 28836,
"text": "C++"
},
{
"code": null,
"e": 28844,
"s": 28840,
"text": "STL"
},
{
"code": null,
"e": 28848,
"s": 28844,
"text": "CPP"
},
{
"code": null,
"e": 28946,
"s": 28848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28955,
"s": 28946,
"text": "Comments"
},
{
"code": null,
"e": 28968,
"s": 28955,
"text": "Old Comments"
},
{
"code": null,
"e": 28987,
"s": 28968,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29011,
"s": 28987,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 29031,
"s": 29011,
"text": "Constructors in C++"
},
{
"code": null,
"e": 29059,
"s": 29031,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 29087,
"s": 29059,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 29111,
"s": 29087,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 29139,
"s": 29111,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 29163,
"s": 29139,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 29194,
"s": 29163,
"text": "Templates in C++ with Examples"
}
]
|
Is F1 the appropriate criterion to use? What about F2, F3,..., F beta? | by Barak Or | Towards Data Science | According to many data scientists, the most reliable model performance measure is accuracy. It is not only the definitive model metric, there are many others, too. Periodically, the accuracy might be high, but the false-negative (to be defined in the sequel) is also high. Another key measure is the F-measure common in machine learning these days, for evaluating the model performance. It proportionally combines the precision and recall measures. In this post, we explore different approaches where the imbalance of the two is suggested.
The confusion matrix summarizes the performance of a supervised learning algorithm in ML. It is more beneficial as it provides a more detailed analysis than the common accuracy measure. In the confusion matrix, each row represents the instance in a predicted class and each column represents the instance in an actual class. The simplified confusion matrix contains two rows and two columns, as given above, where:
For further discussion, we have to define two important measures: Precision: the number of TP samples divided by all P samples (true and false), and Recall: the number of TP divided by (TP+FN).
As both measures are of high importance, a need for one measure to combine between the two arises. Hence, the harmonic mean of the precision and the recall, also known as the F1 score, was proposed.
The measure is given by:
The main advantage (and at the same time disadvantage) of the F1 score is that the recall and precision are of the same importance. In many applications, this is not the case and some weight should be applied to break this balance assumption. This balance assumption might be applied, where there is an uneven distribution of the data such as a large amount of positive-negative.
Using the weighted mean, we can easily obtain the measure F2:
In the same way, the F3 score is obtained:
Generalizing the weighted mean approach results in the F beta measure, provided by:
This measure allows us to define how much the recall is important than the precision. Using the F beta measure in the sklearn is very easy, just follow the example:
scikit-learn.org
>>> from sklearn.metrics import fbeta_score>>> y_true = [0, 1, 2, 0, 1, 2]>>> y_pred = [0, 2, 1, 0, 0, 1]>>> fbeta_score(y_true, y_pred, average='macro', beta=0.5)0.23...>>> fbeta_score(y_true, y_pred, average='micro', beta=0.5)0.33...>>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5)0.23...>>> fbeta_score(y_true, y_pred, average=None, beta=0.5)array([0.71..., 0. , 0. ])
In this post, I reviewed the F measures. I hope that the provided data will help those dealing with classification tasks and motivate them to use the F measures along with the accuracy.
Barak Or received the B.Sc. (2016), M.Sc. (2018) degrees in aerospace engineering, and also B.A. in economics and management (2016, Cum Laude) from the Technion, Israel Institute of Technology. He was with Qualcomm (2019–2020), where he mainly dealt with Machine Learning and Signal Processing algorithms. Barak currently studies toward his Ph.D. at the University of Haifa. His research interest includes sensor fusion, navigation, machine learning, and estimation theory.
https://www.researchgate.net/profile/Barak-Or
www.barakor.com
[1] C.J Van Rijsbergen: https://en.wikipedia.org/wiki/C._J._van_Rijsbergen
[2] Matthews Correlation Coefficient is The Best Classification Metric You’ve Never Heard Of | [
{
"code": null,
"e": 711,
"s": 171,
"text": "According to many data scientists, the most reliable model performance measure is accuracy. It is not only the definitive model metric, there are many others, too. Periodically, the accuracy might be high, but the false-negative (to be defined in the sequel) is also high. Another key measure is the F-measure common in machine learning these days, for evaluating the model performance. It proportionally combines the precision and recall measures. In this post, we explore different approaches where the imbalance of the two is suggested."
},
{
"code": null,
"e": 1126,
"s": 711,
"text": "The confusion matrix summarizes the performance of a supervised learning algorithm in ML. It is more beneficial as it provides a more detailed analysis than the common accuracy measure. In the confusion matrix, each row represents the instance in a predicted class and each column represents the instance in an actual class. The simplified confusion matrix contains two rows and two columns, as given above, where:"
},
{
"code": null,
"e": 1320,
"s": 1126,
"text": "For further discussion, we have to define two important measures: Precision: the number of TP samples divided by all P samples (true and false), and Recall: the number of TP divided by (TP+FN)."
},
{
"code": null,
"e": 1519,
"s": 1320,
"text": "As both measures are of high importance, a need for one measure to combine between the two arises. Hence, the harmonic mean of the precision and the recall, also known as the F1 score, was proposed."
},
{
"code": null,
"e": 1544,
"s": 1519,
"text": "The measure is given by:"
},
{
"code": null,
"e": 1924,
"s": 1544,
"text": "The main advantage (and at the same time disadvantage) of the F1 score is that the recall and precision are of the same importance. In many applications, this is not the case and some weight should be applied to break this balance assumption. This balance assumption might be applied, where there is an uneven distribution of the data such as a large amount of positive-negative."
},
{
"code": null,
"e": 1986,
"s": 1924,
"text": "Using the weighted mean, we can easily obtain the measure F2:"
},
{
"code": null,
"e": 2029,
"s": 1986,
"text": "In the same way, the F3 score is obtained:"
},
{
"code": null,
"e": 2113,
"s": 2029,
"text": "Generalizing the weighted mean approach results in the F beta measure, provided by:"
},
{
"code": null,
"e": 2278,
"s": 2113,
"text": "This measure allows us to define how much the recall is important than the precision. Using the F beta measure in the sklearn is very easy, just follow the example:"
},
{
"code": null,
"e": 2295,
"s": 2278,
"text": "scikit-learn.org"
},
{
"code": null,
"e": 2694,
"s": 2295,
"text": ">>> from sklearn.metrics import fbeta_score>>> y_true = [0, 1, 2, 0, 1, 2]>>> y_pred = [0, 2, 1, 0, 0, 1]>>> fbeta_score(y_true, y_pred, average='macro', beta=0.5)0.23...>>> fbeta_score(y_true, y_pred, average='micro', beta=0.5)0.33...>>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5)0.23...>>> fbeta_score(y_true, y_pred, average=None, beta=0.5)array([0.71..., 0. , 0. ])"
},
{
"code": null,
"e": 2880,
"s": 2694,
"text": "In this post, I reviewed the F measures. I hope that the provided data will help those dealing with classification tasks and motivate them to use the F measures along with the accuracy."
},
{
"code": null,
"e": 3354,
"s": 2880,
"text": "Barak Or received the B.Sc. (2016), M.Sc. (2018) degrees in aerospace engineering, and also B.A. in economics and management (2016, Cum Laude) from the Technion, Israel Institute of Technology. He was with Qualcomm (2019–2020), where he mainly dealt with Machine Learning and Signal Processing algorithms. Barak currently studies toward his Ph.D. at the University of Haifa. His research interest includes sensor fusion, navigation, machine learning, and estimation theory."
},
{
"code": null,
"e": 3400,
"s": 3354,
"text": "https://www.researchgate.net/profile/Barak-Or"
},
{
"code": null,
"e": 3416,
"s": 3400,
"text": "www.barakor.com"
},
{
"code": null,
"e": 3491,
"s": 3416,
"text": "[1] C.J Van Rijsbergen: https://en.wikipedia.org/wiki/C._J._van_Rijsbergen"
}
]
|
JavaFX Effects - Blend | In general, blend means mixture of two or more different things or substances. If we apply the blend effect, it will take the pixels of two different inputs. This will be done at the same location and it produces a combined output based on the blend mode.
For example, if we draw two objects the top object covers the bottom one. On applying the blend effect, the pixels of the two objects in the overlap area are combined and displayed based on the input mode.
The class named Blend of the package javafx.scene.effect represents the blend effect, this class contains four properties, which are −
bottomInput − This property is of the type Effect and it represents the bottom input to the blend effect.
bottomInput − This property is of the type Effect and it represents the bottom input to the blend effect.
topInput − This property is of the type Effect and it represents the top input to the blend effect.
topInput − This property is of the type Effect and it represents the top input to the blend effect.
opacity − This property is of double type and it represents the opacity value modulated with the top input.
opacity − This property is of double type and it represents the opacity value modulated with the top input.
mode − This property is of the type BlendMode and it represents the mode used to blend the two inputs together.
mode − This property is of the type BlendMode and it represents the mode used to blend the two inputs together.
Following is an example demonstrating the blend effect. In here, we are drawing a circle filled with BROWN color, on top of it lies a BLUEVIOLET ColorInput.
We have applied the blend effect choosing a multiply mode In the overlap area, the colors of the two objects were multiplied and displayed.
Save this code in a file with the name BlendEffectExample.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.effect.Blend;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ColorInput;
import javafx.scene.paint.Color;
public class BlendEffectExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle();
//Setting the center of the Circle
circle.setCenterX(75.0f);
circle.setCenterY(75.0f);
//Setting radius of the circle
circle.setRadius(30.0f);
//Setting the fill color of the circle
circle.setFill(Color.BROWN);
//Instantiating the blend class
Blend blend = new Blend();
//Preparing the to input object
ColorInput topInput = new ColorInput(35, 30, 75, 40, Color.BLUEVIOLET);
//setting the top input to the blend object
blend.setTopInput(topInput);
//setting the blend mode
blend.setMode(BlendMode.SRC_OVER);
//Applying the blend effect to circle
circle.setEffect(blend);
//Creating a Group object
Group root = new Group(circle);
//Creating a scene object
Scene scene = new Scene(root, 150, 150);
//Setting title to the Stage
stage.setTitle("Blend Example");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Compile and execute the saved java file from the command prompt using the following commands.
javac BlendEffectExample.java
java BlendEffectExample
On executing, the above program generates a JavaFX window as shown below.
ADD
In this mode, the color values of the top and bottom inputs are added and displayed.
MULTIPLY
In this mode, the color values of the top and bottom inputs are multiplied and displayed.
DIFFERENCE
In this mode, among the color values of the top and bottom inputs, the darker one is subtracted from the lighter one and displayed.
RED
In this mode, the red components of the bottom input were replaced by the red components of the top input.
BLUE
In this mode, the blue components of the bottom input were replaced by the blue components of the top input.
GREEN
In this mode, the green components of the bottom input were replaced by the green components of the top input.
EXCLUSION
In this mode, the color components of the two inputs were multiplied and doubled. Then they are subtracted from the sum of the color components of the bottom input. The resultant is then displayed.
COLOR_BURN
In this mode, the inverse of the bottom input color component was divided by the top input color component. Thus, the obtained value is inverted and displayed.
COLOR_DODGE
In this mode, the bottom input color components were divided by the inverse of the top input color components and thus obtained value is inverted and displayed.
LIGHTEN
In this mode, the lighter color component, among the both inputs are displayed.
DARKEN
In this mode, the darker color component, among the top and bottom inputs is displayed.
SCREEN
In this mode, the color components of the top and bottom inputs were inverted, multiplied and thus obtained value is inverted and displayed.
OVERLAY
In this mode, based on the bottom input color, the color components of the two input values were multiplied or screened and the resultant is displayed.
HARD_LIGHT
In this mode, based on the top input color, the color components of the two input values were multiplied or screened and the resultant is displayed.
SOFT_LIGH
In this mode, based on the top input color, the color components of the two input values were softened or lightened and the resultant is displayed.
SRC_ATOP
In this mode, the over lapping area is filled with the color component of the bottom input. While the nonoverlapping area is filled with the color component of the top input.
SRC_OVER
In this mode, the top input is drawn over the bottom input.
33 Lectures
7.5 hours
Syed Raza
64 Lectures
12.5 hours
Emenwa Global, Ejike IfeanyiChukwu
20 Lectures
4 hours
Emenwa Global, Ejike IfeanyiChukwu
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2156,
"s": 1900,
"text": "In general, blend means mixture of two or more different things or substances. If we apply the blend effect, it will take the pixels of two different inputs. This will be done at the same location and it produces a combined output based on the blend mode."
},
{
"code": null,
"e": 2362,
"s": 2156,
"text": "For example, if we draw two objects the top object covers the bottom one. On applying the blend effect, the pixels of the two objects in the overlap area are combined and displayed based on the input mode."
},
{
"code": null,
"e": 2497,
"s": 2362,
"text": "The class named Blend of the package javafx.scene.effect represents the blend effect, this class contains four properties, which are −"
},
{
"code": null,
"e": 2603,
"s": 2497,
"text": "bottomInput − This property is of the type Effect and it represents the bottom input to the blend effect."
},
{
"code": null,
"e": 2709,
"s": 2603,
"text": "bottomInput − This property is of the type Effect and it represents the bottom input to the blend effect."
},
{
"code": null,
"e": 2809,
"s": 2709,
"text": "topInput − This property is of the type Effect and it represents the top input to the blend effect."
},
{
"code": null,
"e": 2909,
"s": 2809,
"text": "topInput − This property is of the type Effect and it represents the top input to the blend effect."
},
{
"code": null,
"e": 3017,
"s": 2909,
"text": "opacity − This property is of double type and it represents the opacity value modulated with the top input."
},
{
"code": null,
"e": 3125,
"s": 3017,
"text": "opacity − This property is of double type and it represents the opacity value modulated with the top input."
},
{
"code": null,
"e": 3237,
"s": 3125,
"text": "mode − This property is of the type BlendMode and it represents the mode used to blend the two inputs together."
},
{
"code": null,
"e": 3349,
"s": 3237,
"text": "mode − This property is of the type BlendMode and it represents the mode used to blend the two inputs together."
},
{
"code": null,
"e": 3506,
"s": 3349,
"text": "Following is an example demonstrating the blend effect. In here, we are drawing a circle filled with BROWN color, on top of it lies a BLUEVIOLET ColorInput."
},
{
"code": null,
"e": 3646,
"s": 3506,
"text": "We have applied the blend effect choosing a multiply mode In the overlap area, the colors of the two objects were multiplied and displayed."
},
{
"code": null,
"e": 3710,
"s": 3646,
"text": "Save this code in a file with the name BlendEffectExample.java."
},
{
"code": null,
"e": 5451,
"s": 3710,
"text": "import javafx.application.Application; \nimport javafx.scene.Group; \nimport javafx.scene.Scene; \nimport javafx.stage.Stage;\nimport javafx.scene.shape.Circle; \nimport javafx.scene.effect.Blend; \nimport javafx.scene.effect.BlendMode; \nimport javafx.scene.effect.ColorInput; \nimport javafx.scene.paint.Color; \n \npublic class BlendEffectExample extends Application { \n @Override \n public void start(Stage stage) { \n //Drawing a Circle \n Circle circle = new Circle(); \n \n //Setting the center of the Circle\n circle.setCenterX(75.0f); \n circle.setCenterY(75.0f); \n \n //Setting radius of the circle \n circle.setRadius(30.0f); \n \n //Setting the fill color of the circle \n circle.setFill(Color.BROWN); \n \n //Instantiating the blend class \n Blend blend = new Blend(); \n \n //Preparing the to input object \n ColorInput topInput = new ColorInput(35, 30, 75, 40, Color.BLUEVIOLET); \n \n //setting the top input to the blend object \n blend.setTopInput(topInput); \n \n //setting the blend mode \n blend.setMode(BlendMode.SRC_OVER); \n \n //Applying the blend effect to circle \n circle.setEffect(blend); \n \n //Creating a Group object \n Group root = new Group(circle); \n \n //Creating a scene object \n Scene scene = new Scene(root, 150, 150); \n \n //Setting title to the Stage \n stage.setTitle(\"Blend Example\"); \n \n //Adding scene to the stage \n stage.setScene(scene); \n \n //Displaying the contents of the stage \n stage.show(); \n } \n public static void main(String args[]){ \n launch(args); \n } \n} "
},
{
"code": null,
"e": 5545,
"s": 5451,
"text": "Compile and execute the saved java file from the command prompt using the following commands."
},
{
"code": null,
"e": 5601,
"s": 5545,
"text": "javac BlendEffectExample.java \njava BlendEffectExample\n"
},
{
"code": null,
"e": 5675,
"s": 5601,
"text": "On executing, the above program generates a JavaFX window as shown below."
},
{
"code": null,
"e": 5679,
"s": 5675,
"text": "ADD"
},
{
"code": null,
"e": 5764,
"s": 5679,
"text": "In this mode, the color values of the top and bottom inputs are added and displayed."
},
{
"code": null,
"e": 5773,
"s": 5764,
"text": "MULTIPLY"
},
{
"code": null,
"e": 5863,
"s": 5773,
"text": "In this mode, the color values of the top and bottom inputs are multiplied and displayed."
},
{
"code": null,
"e": 5874,
"s": 5863,
"text": "DIFFERENCE"
},
{
"code": null,
"e": 6006,
"s": 5874,
"text": "In this mode, among the color values of the top and bottom inputs, the darker one is subtracted from the lighter one and displayed."
},
{
"code": null,
"e": 6010,
"s": 6006,
"text": "RED"
},
{
"code": null,
"e": 6117,
"s": 6010,
"text": "In this mode, the red components of the bottom input were replaced by the red components of the top input."
},
{
"code": null,
"e": 6122,
"s": 6117,
"text": "BLUE"
},
{
"code": null,
"e": 6231,
"s": 6122,
"text": "In this mode, the blue components of the bottom input were replaced by the blue components of the top input."
},
{
"code": null,
"e": 6237,
"s": 6231,
"text": "GREEN"
},
{
"code": null,
"e": 6348,
"s": 6237,
"text": "In this mode, the green components of the bottom input were replaced by the green components of the top input."
},
{
"code": null,
"e": 6358,
"s": 6348,
"text": "EXCLUSION"
},
{
"code": null,
"e": 6556,
"s": 6358,
"text": "In this mode, the color components of the two inputs were multiplied and doubled. Then they are subtracted from the sum of the color components of the bottom input. The resultant is then displayed."
},
{
"code": null,
"e": 6567,
"s": 6556,
"text": "COLOR_BURN"
},
{
"code": null,
"e": 6727,
"s": 6567,
"text": "In this mode, the inverse of the bottom input color component was divided by the top input color component. Thus, the obtained value is inverted and displayed."
},
{
"code": null,
"e": 6739,
"s": 6727,
"text": "COLOR_DODGE"
},
{
"code": null,
"e": 6900,
"s": 6739,
"text": "In this mode, the bottom input color components were divided by the inverse of the top input color components and thus obtained value is inverted and displayed."
},
{
"code": null,
"e": 6908,
"s": 6900,
"text": "LIGHTEN"
},
{
"code": null,
"e": 6988,
"s": 6908,
"text": "In this mode, the lighter color component, among the both inputs are displayed."
},
{
"code": null,
"e": 6995,
"s": 6988,
"text": "DARKEN"
},
{
"code": null,
"e": 7083,
"s": 6995,
"text": "In this mode, the darker color component, among the top and bottom inputs is displayed."
},
{
"code": null,
"e": 7090,
"s": 7083,
"text": "SCREEN"
},
{
"code": null,
"e": 7231,
"s": 7090,
"text": "In this mode, the color components of the top and bottom inputs were inverted, multiplied and thus obtained value is inverted and displayed."
},
{
"code": null,
"e": 7239,
"s": 7231,
"text": "OVERLAY"
},
{
"code": null,
"e": 7391,
"s": 7239,
"text": "In this mode, based on the bottom input color, the color components of the two input values were multiplied or screened and the resultant is displayed."
},
{
"code": null,
"e": 7402,
"s": 7391,
"text": "HARD_LIGHT"
},
{
"code": null,
"e": 7551,
"s": 7402,
"text": "In this mode, based on the top input color, the color components of the two input values were multiplied or screened and the resultant is displayed."
},
{
"code": null,
"e": 7561,
"s": 7551,
"text": "SOFT_LIGH"
},
{
"code": null,
"e": 7709,
"s": 7561,
"text": "In this mode, based on the top input color, the color components of the two input values were softened or lightened and the resultant is displayed."
},
{
"code": null,
"e": 7718,
"s": 7709,
"text": "SRC_ATOP"
},
{
"code": null,
"e": 7893,
"s": 7718,
"text": "In this mode, the over lapping area is filled with the color component of the bottom input. While the nonoverlapping area is filled with the color component of the top input."
},
{
"code": null,
"e": 7902,
"s": 7893,
"text": "SRC_OVER"
},
{
"code": null,
"e": 7962,
"s": 7902,
"text": "In this mode, the top input is drawn over the bottom input."
},
{
"code": null,
"e": 7997,
"s": 7962,
"text": "\n 33 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 8008,
"s": 7997,
"text": " Syed Raza"
},
{
"code": null,
"e": 8044,
"s": 8008,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 8080,
"s": 8044,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8113,
"s": 8080,
"text": "\n 20 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 8149,
"s": 8113,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8156,
"s": 8149,
"text": " Print"
},
{
"code": null,
"e": 8167,
"s": 8156,
"text": " Add Notes"
}
]
|
Delete Dictionary Elements in Python | You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement.
Following is a simple example −
Live Demo
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section. | [
{
"code": null,
"e": 1222,
"s": 1062,
"text": "You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation."
},
{
"code": null,
"e": 1293,
"s": 1222,
"text": "To explicitly remove an entire dictionary, just use the del statement."
},
{
"code": null,
"e": 1325,
"s": 1293,
"text": "Following is a simple example −"
},
{
"code": null,
"e": 1336,
"s": 1325,
"text": " Live Demo"
},
{
"code": null,
"e": 1612,
"s": 1336,
"text": "#!/usr/bin/python\ndict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}\ndel dict['Name']; # remove entry with key 'Name'\ndict.clear(); # remove all entries in dict\ndel dict ; # delete entire dictionary\nprint \"dict['Age']: \", dict['Age']\nprint \"dict['School']: \", dict['School']"
},
{
"code": null,
"e": 1741,
"s": 1612,
"text": "This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more −"
},
{
"code": null,
"e": 1905,
"s": 1741,
"text": "dict['Age']:\nTraceback (most recent call last):\nFile \"test.py\", line 8, in <module>\nprint \"dict['Age']: \", dict['Age'];\nTypeError: 'type' object is unsubscriptable"
},
{
"code": null,
"e": 1961,
"s": 1905,
"text": "Note − del() method is discussed in subsequent section."
}
]
|
How to install pandas using the python package manager? | A package is a bundle of modules, to be installed into a Python environment. And typically, this would include things like third-party libraries and frameworks.
Package Managers are tools that help you manage the dependencies for your project implementation. For python-pip is the package manager provided by default with the rest of the Python standard library and things like the Python interpreter, pip’s main interface is a command-line tool.
pip is written in Python which is used to install and manage software packages. as we know that pip is available by default with python, so we no need to install it again, because it is already installed. And it has a feature to manage full lists of packages and corresponding version numbers
pip installs packages like TensorFlow and NumPy, pandas and sklearn, and many more, along with their dependencies.
To install the pandas package by using pip we have to open the command prompt in our system (assuming, our machine is a windows operating system).
pip install pandas
This command will install the pandas package as well as it will also install all the dependencies of our pandas package.
If you want to install any particular version of the pandas package, we can give the below command −
pip install pandas==1.2.2
In some situations, we need to upgrade the python package manager to get the latest version of packages then we can use the below command in our command prompt.
python -m pip install --upgrade pip
Every time, when you try to install any package, initially pip will check for the package dependencies if they are already installed on the system or not. if not, it will install them. Once all dependencies have been satisfied, it proceeds to install the requested package(s). | [
{
"code": null,
"e": 1223,
"s": 1062,
"text": "A package is a bundle of modules, to be installed into a Python environment. And typically, this would include things like third-party libraries and frameworks."
},
{
"code": null,
"e": 1509,
"s": 1223,
"text": "Package Managers are tools that help you manage the dependencies for your project implementation. For python-pip is the package manager provided by default with the rest of the Python standard library and things like the Python interpreter, pip’s main interface is a command-line tool."
},
{
"code": null,
"e": 1802,
"s": 1509,
"text": "pip is written in Python which is used to install and manage software packages. as we know that pip is available by default with python, so we no need to install it again, because it is already installed. And it has a feature to manage full lists of packages and corresponding version numbers"
},
{
"code": null,
"e": 1917,
"s": 1802,
"text": "pip installs packages like TensorFlow and NumPy, pandas and sklearn, and many more, along with their dependencies."
},
{
"code": null,
"e": 2064,
"s": 1917,
"text": "To install the pandas package by using pip we have to open the command prompt in our system (assuming, our machine is a windows operating system)."
},
{
"code": null,
"e": 2083,
"s": 2064,
"text": "pip install pandas"
},
{
"code": null,
"e": 2204,
"s": 2083,
"text": "This command will install the pandas package as well as it will also install all the dependencies of our pandas package."
},
{
"code": null,
"e": 2305,
"s": 2204,
"text": "If you want to install any particular version of the pandas package, we can give the below command −"
},
{
"code": null,
"e": 2331,
"s": 2305,
"text": "pip install pandas==1.2.2"
},
{
"code": null,
"e": 2492,
"s": 2331,
"text": "In some situations, we need to upgrade the python package manager to get the latest version of packages then we can use the below command in our command prompt."
},
{
"code": null,
"e": 2528,
"s": 2492,
"text": "python -m pip install --upgrade pip"
},
{
"code": null,
"e": 2805,
"s": 2528,
"text": "Every time, when you try to install any package, initially pip will check for the package dependencies if they are already installed on the system or not. if not, it will install them. Once all dependencies have been satisfied, it proceeds to install the requested package(s)."
}
]
|
How can I remove a value from an enum in MySQL? | Use ALTER command to remove a value from an enum in MySQL. Let us first create a table −
mysql> create table DemoTable
(
`Rank` ENUM('LOW','MEDIUM','HIGH')
);
Query OK, 0 rows affected (0.52 sec)
Let us check the description of table.
mysql> DESC DemoTable;
This will produce the following output −
+-------+-----------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------------------------+------+-----+---------+-------+
| Rank | enum('LOW','MEDIUM','HIGH') | YES | | NULL | |
+-------+-----------------------------+------+-----+---------+-------+
1 row in set (0.00 sec)
Following is the query to remove a value from an enum in MySQL.
mysql> alter table DemoTable change `Rank` `Rank` ENUM('LOW','HIGH');
Query OK, 0 rows affected (1.19 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now let us check the description of table once again −
mysql> DESC DemoTable;
This will produce the following output −
+-------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------------+------+-----+---------+-------+
| Rank | enum('LOW','HIGH') | YES | | NULL | |
+-------+--------------------+------+-----+---------+-------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1151,
"s": 1062,
"text": "Use ALTER command to remove a value from an enum in MySQL. Let us first create a table −"
},
{
"code": null,
"e": 1267,
"s": 1151,
"text": "mysql> create table DemoTable\n (\n `Rank` ENUM('LOW','MEDIUM','HIGH')\n );\nQuery OK, 0 rows affected (0.52 sec)"
},
{
"code": null,
"e": 1306,
"s": 1267,
"text": "Let us check the description of table."
},
{
"code": null,
"e": 1329,
"s": 1306,
"text": "mysql> DESC DemoTable;"
},
{
"code": null,
"e": 1370,
"s": 1329,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1749,
"s": 1370,
"text": "+-------+-----------------------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-----------------------------+------+-----+---------+-------+\n| Rank | enum('LOW','MEDIUM','HIGH') | YES | | NULL | |\n+-------+-----------------------------+------+-----+---------+-------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1813,
"s": 1749,
"text": "Following is the query to remove a value from an enum in MySQL."
},
{
"code": null,
"e": 1957,
"s": 1813,
"text": "mysql> alter table DemoTable change `Rank` `Rank` ENUM('LOW','HIGH');\nQuery OK, 0 rows affected (1.19 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2012,
"s": 1957,
"text": "Now let us check the description of table once again −"
},
{
"code": null,
"e": 2035,
"s": 2012,
"text": "mysql> DESC DemoTable;"
},
{
"code": null,
"e": 2076,
"s": 2035,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2395,
"s": 2076,
"text": "+-------+--------------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------------+------+-----+---------+-------+\n| Rank | enum('LOW','HIGH') | YES | | NULL | |\n+-------+--------------------+------+-----+---------+-------+\n1 row in set (0.00 sec)"
}
]
|
Convert a given Decimal number to its BCD representation - GeeksforGeeks | 29 Jul, 2021
Given a decimal number N, the task is to convert N to it’s Binary Coded Decimal(BCD) form.Examples:
Input: N = 12 Output: 0001 0000 Explanation: Considering 4-bit concept: 1 in binary is 0001 and 2 in binary is 0010. So it’s equivalent BCD is 0001 0010.Input: N = 10 Output: 0001 0000 Explanation: Considering 4-bit concept: 1 in binary is 0001 and 0 in binary is 0000. So it’s equivalent BCD is 0001 0000.
Approach:
Reverse the digits of the given number N using the approach discussed in this article and stored the number in Rev.Extract the digits of Rev and print the Binary form of the digit using bitset.Repeat the above steps for each digit in Rev.
Reverse the digits of the given number N using the approach discussed in this article and stored the number in Rev.
Extract the digits of Rev and print the Binary form of the digit using bitset.
Repeat the above steps for each digit in Rev.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to convert Decimal to BCDvoid BCDConversion(int n){ // Base Case if (n == 0) { cout << "0000"; return; } // To store the reverse of n int rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } // Iterate through all digits in rev while (rev > 0) { // Find Binary for each digit // using bitset bitset<4> b(rev % 10); // Print the Binary conversion // for current digit cout << b << ' '; // Divide rev by 10 for next digit rev /= 10; }} // Driver Codeint main(){ // Given Number int N = 12; // Function Call BCDConversion(N); return 0;}
// Java program for the above approachimport java.util.*; class Gfg{ // Function to convert Decimal to BCD public static void BCDConversion(int n) { // Base Case if(n == 0) { System.out.print("0000"); } // To store the reverse of n int rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } // Iterate through all digits in rev while(rev > 0) { // Find Binary for each digit // using bitset String b = Integer.toBinaryString(rev % 10); b = String.format("%04d", Integer.parseInt(b)); // Print the Binary conversion // for current digit System.out.print(b + " "); // Divide rev by 10 for next digit rev /= 10; } } // Driver code public static void main(String []args) { // Given Number int N = 12; // Function Call BCDConversion(N); }} // This code is contributed by avanitrachhadiya2155
# Python3 program for the above approach # Function to convert Decimal to BCDdef BCDConversion(n) : # Base Case if (n == 0) : print("0000") return # To store the reverse of n rev = 0 # Reversing the digits while (n > 0) : rev = rev * 10 + (n % 10) n = n // 10 # Iterate through all digits in rev while (rev > 0) : # Find Binary for each digit # using bitset b = str(rev % 10) # Print the Binary conversion # for current digit print("{0:04b}".format(int(b, 16)), end = " ") # Divide rev by 10 for next digit rev = rev // 10 # Given NumberN = 12 # Function CallBCDConversion(N) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to convert Decimal to BCD static void BCDConversion(int n) { // Base Case if (n == 0) { Console.Write("0000"); return; } // To store the reverse of n int rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } // Iterate through all digits in rev while (rev > 0) { // Find Binary for each digit // using bitset string b = Convert.ToString(rev % 10, 2).PadLeft(4, '0'); // Print the Binary conversion // for current digit Console.Write(b + " "); // Divide rev by 10 for next digit rev /= 10; } } static void Main() { // Given Number int N = 12; // Function Call BCDConversion(N); }} // This code is contributed divyesh072019
<script> //JavaScript for the above approach // Function to convert Decimal to BCD function BCDConversion(n) { // Base Case if (n == 0) { document.write("0000"); return; } // To store the reverse of n let rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n = parseInt(n / 10, 10); } // Iterate through all digits in rev while (rev > 0) { // Find Binary for each digit // using bitset let b = (rev % 10).toString(2); while(b.length != 4) { b = "0" + b; } // Print the Binary conversion // for current digit document.write(b + " "); // Divide rev by 10 for next digit rev = parseInt(rev / 10, 10); } } // Driver Code // Given Number let N = 12; // Function Call BCDConversion(N); </script>
0001 0010
Time Complexity: O(log10 N), where N is the given number.
divyeshrabadiya07
divyesh072019
avanitrachhadiya2155
vaibhavrabadiya3
base-conversion
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Program to find parity
Bit Fields in C
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 24597,
"s": 24569,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 24699,
"s": 24597,
"text": "Given a decimal number N, the task is to convert N to it’s Binary Coded Decimal(BCD) form.Examples: "
},
{
"code": null,
"e": 25008,
"s": 24699,
"text": "Input: N = 12 Output: 0001 0000 Explanation: Considering 4-bit concept: 1 in binary is 0001 and 2 in binary is 0010. So it’s equivalent BCD is 0001 0010.Input: N = 10 Output: 0001 0000 Explanation: Considering 4-bit concept: 1 in binary is 0001 and 0 in binary is 0000. So it’s equivalent BCD is 0001 0000. "
},
{
"code": null,
"e": 25022,
"s": 25010,
"text": "Approach: "
},
{
"code": null,
"e": 25261,
"s": 25022,
"text": "Reverse the digits of the given number N using the approach discussed in this article and stored the number in Rev.Extract the digits of Rev and print the Binary form of the digit using bitset.Repeat the above steps for each digit in Rev."
},
{
"code": null,
"e": 25377,
"s": 25261,
"text": "Reverse the digits of the given number N using the approach discussed in this article and stored the number in Rev."
},
{
"code": null,
"e": 25456,
"s": 25377,
"text": "Extract the digits of Rev and print the Binary form of the digit using bitset."
},
{
"code": null,
"e": 25502,
"s": 25456,
"text": "Repeat the above steps for each digit in Rev."
},
{
"code": null,
"e": 25554,
"s": 25502,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25558,
"s": 25554,
"text": "C++"
},
{
"code": null,
"e": 25563,
"s": 25558,
"text": "Java"
},
{
"code": null,
"e": 25571,
"s": 25563,
"text": "Python3"
},
{
"code": null,
"e": 25574,
"s": 25571,
"text": "C#"
},
{
"code": null,
"e": 25585,
"s": 25574,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to convert Decimal to BCDvoid BCDConversion(int n){ // Base Case if (n == 0) { cout << \"0000\"; return; } // To store the reverse of n int rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } // Iterate through all digits in rev while (rev > 0) { // Find Binary for each digit // using bitset bitset<4> b(rev % 10); // Print the Binary conversion // for current digit cout << b << ' '; // Divide rev by 10 for next digit rev /= 10; }} // Driver Codeint main(){ // Given Number int N = 12; // Function Call BCDConversion(N); return 0;}",
"e": 26386,
"s": 25585,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class Gfg{ // Function to convert Decimal to BCD public static void BCDConversion(int n) { // Base Case if(n == 0) { System.out.print(\"0000\"); } // To store the reverse of n int rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } // Iterate through all digits in rev while(rev > 0) { // Find Binary for each digit // using bitset String b = Integer.toBinaryString(rev % 10); b = String.format(\"%04d\", Integer.parseInt(b)); // Print the Binary conversion // for current digit System.out.print(b + \" \"); // Divide rev by 10 for next digit rev /= 10; } } // Driver code public static void main(String []args) { // Given Number int N = 12; // Function Call BCDConversion(N); }} // This code is contributed by avanitrachhadiya2155",
"e": 27559,
"s": 26386,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to convert Decimal to BCDdef BCDConversion(n) : # Base Case if (n == 0) : print(\"0000\") return # To store the reverse of n rev = 0 # Reversing the digits while (n > 0) : rev = rev * 10 + (n % 10) n = n // 10 # Iterate through all digits in rev while (rev > 0) : # Find Binary for each digit # using bitset b = str(rev % 10) # Print the Binary conversion # for current digit print(\"{0:04b}\".format(int(b, 16)), end = \" \") # Divide rev by 10 for next digit rev = rev // 10 # Given NumberN = 12 # Function CallBCDConversion(N) # This code is contributed by divyeshrabadiya07",
"e": 28306,
"s": 27559,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to convert Decimal to BCD static void BCDConversion(int n) { // Base Case if (n == 0) { Console.Write(\"0000\"); return; } // To store the reverse of n int rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } // Iterate through all digits in rev while (rev > 0) { // Find Binary for each digit // using bitset string b = Convert.ToString(rev % 10, 2).PadLeft(4, '0'); // Print the Binary conversion // for current digit Console.Write(b + \" \"); // Divide rev by 10 for next digit rev /= 10; } } static void Main() { // Given Number int N = 12; // Function Call BCDConversion(N); }} // This code is contributed divyesh072019",
"e": 29353,
"s": 28306,
"text": null
},
{
"code": "<script> //JavaScript for the above approach // Function to convert Decimal to BCD function BCDConversion(n) { // Base Case if (n == 0) { document.write(\"0000\"); return; } // To store the reverse of n let rev = 0; // Reversing the digits while (n > 0) { rev = rev * 10 + (n % 10); n = parseInt(n / 10, 10); } // Iterate through all digits in rev while (rev > 0) { // Find Binary for each digit // using bitset let b = (rev % 10).toString(2); while(b.length != 4) { b = \"0\" + b; } // Print the Binary conversion // for current digit document.write(b + \" \"); // Divide rev by 10 for next digit rev = parseInt(rev / 10, 10); } } // Driver Code // Given Number let N = 12; // Function Call BCDConversion(N); </script>",
"e": 30364,
"s": 29353,
"text": null
},
{
"code": null,
"e": 30374,
"s": 30364,
"text": "0001 0010"
},
{
"code": null,
"e": 30435,
"s": 30376,
"text": "Time Complexity: O(log10 N), where N is the given number. "
},
{
"code": null,
"e": 30453,
"s": 30435,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 30467,
"s": 30453,
"text": "divyesh072019"
},
{
"code": null,
"e": 30488,
"s": 30467,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 30505,
"s": 30488,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 30521,
"s": 30505,
"text": "base-conversion"
},
{
"code": null,
"e": 30531,
"s": 30521,
"text": "Bit Magic"
},
{
"code": null,
"e": 30544,
"s": 30531,
"text": "Mathematical"
},
{
"code": null,
"e": 30557,
"s": 30544,
"text": "Mathematical"
},
{
"code": null,
"e": 30567,
"s": 30557,
"text": "Bit Magic"
},
{
"code": null,
"e": 30665,
"s": 30567,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30674,
"s": 30665,
"text": "Comments"
},
{
"code": null,
"e": 30687,
"s": 30674,
"text": "Old Comments"
},
{
"code": null,
"e": 30733,
"s": 30687,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 30756,
"s": 30733,
"text": "Program to find parity"
},
{
"code": null,
"e": 30772,
"s": 30756,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 30802,
"s": 30772,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 30840,
"s": 30802,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 30870,
"s": 30840,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30930,
"s": 30870,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30945,
"s": 30930,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30988,
"s": 30945,
"text": "Set in C++ Standard Template Library (STL)"
}
]
|
Scraping Tables from PDF Files Using Python | Towards Data Science | Fetching tables from PDF files is no more a difficult task, you can do this using a single line in python.
Installing a tabula-py library.Importing library.Reading a PDF file.Reading a table on a particular page of a PDF file.Reading multiple tables on the same page of a PDF file.Converting PDF files directly to a CSV file.
Installing a tabula-py library.
Importing library.
Reading a PDF file.
Reading a table on a particular page of a PDF file.
Reading multiple tables on the same page of a PDF file.
Converting PDF files directly to a CSV file.
Tabula is one of the useful packages which not only allows you to scrape tables from PDF files but also convert a PDF file directly into a CSV file.
pip install tabula-py
import tabula
lets scrap this PDF into pandas Data Frame.
file1 = "https://nbviewer.jupyter.org/github/kuruvasatya/Scraping-Tables-from-PDF/blob/master/data1.pdf"table = tabula.read_pdf(file1,pages=1)table[0]
Take a look at the output of above code snippet executed in Google Colabs
let say we need to scrap this PDF FILE which contains multiple pages in it.
file2 = "https://nbviewer.jupyter.org/github/kuruvasatya/Reading-Table-Data-From-PDF/blob/master/data.pdf"# To read table in first page of PDF filetable1 = tabula.read_pdf(file2 ,pages=1)# To read tables in secord page of PDF filetable2 = tabula.read_pdf(file2 ,pages=2)print(table1[0])print(table2[0])
let's say we need to scrape these 2 tables which are on the same page of a PDF file.
To read multiple tables we need to add extra parametermultiple_tables = True -> Read multiple tables as independent tablesmultiple_tables = False -> Read multiple tables as single table
file3 = "https://nbviewer.jupyter.org/github/kuruvasatya/Reading-Table-Data-From-PDF/blob/master/data3.pdf"tables = tabula.read_pdf(file3 ,pages=1, multiple_tables=True)print(tables[0])print(tables[1])
tables = tabula.read_pdf(file3 ,pages=1,multiple_tables=False)tables[0]
we can directly convert a PDF file containing tabular data directly to a CSV file using convert_into() method in tabula library.
# output just the first page tables in the PDF to a CSVtabula.convert_into("pdf_file_name", "Name_of_csv_file.csv")
tabula.convert_into("pdf_file_name","Name_of_csv_file.csv",all = True)
I hope you learned a great way to scrape PDF file tables using a single line in python.
Check out my related articles | [
{
"code": null,
"e": 278,
"s": 171,
"text": "Fetching tables from PDF files is no more a difficult task, you can do this using a single line in python."
},
{
"code": null,
"e": 497,
"s": 278,
"text": "Installing a tabula-py library.Importing library.Reading a PDF file.Reading a table on a particular page of a PDF file.Reading multiple tables on the same page of a PDF file.Converting PDF files directly to a CSV file."
},
{
"code": null,
"e": 529,
"s": 497,
"text": "Installing a tabula-py library."
},
{
"code": null,
"e": 548,
"s": 529,
"text": "Importing library."
},
{
"code": null,
"e": 568,
"s": 548,
"text": "Reading a PDF file."
},
{
"code": null,
"e": 620,
"s": 568,
"text": "Reading a table on a particular page of a PDF file."
},
{
"code": null,
"e": 676,
"s": 620,
"text": "Reading multiple tables on the same page of a PDF file."
},
{
"code": null,
"e": 721,
"s": 676,
"text": "Converting PDF files directly to a CSV file."
},
{
"code": null,
"e": 870,
"s": 721,
"text": "Tabula is one of the useful packages which not only allows you to scrape tables from PDF files but also convert a PDF file directly into a CSV file."
},
{
"code": null,
"e": 892,
"s": 870,
"text": "pip install tabula-py"
},
{
"code": null,
"e": 906,
"s": 892,
"text": "import tabula"
},
{
"code": null,
"e": 950,
"s": 906,
"text": "lets scrap this PDF into pandas Data Frame."
},
{
"code": null,
"e": 1101,
"s": 950,
"text": "file1 = \"https://nbviewer.jupyter.org/github/kuruvasatya/Scraping-Tables-from-PDF/blob/master/data1.pdf\"table = tabula.read_pdf(file1,pages=1)table[0]"
},
{
"code": null,
"e": 1175,
"s": 1101,
"text": "Take a look at the output of above code snippet executed in Google Colabs"
},
{
"code": null,
"e": 1251,
"s": 1175,
"text": "let say we need to scrap this PDF FILE which contains multiple pages in it."
},
{
"code": null,
"e": 1554,
"s": 1251,
"text": "file2 = \"https://nbviewer.jupyter.org/github/kuruvasatya/Reading-Table-Data-From-PDF/blob/master/data.pdf\"# To read table in first page of PDF filetable1 = tabula.read_pdf(file2 ,pages=1)# To read tables in secord page of PDF filetable2 = tabula.read_pdf(file2 ,pages=2)print(table1[0])print(table2[0])"
},
{
"code": null,
"e": 1639,
"s": 1554,
"text": "let's say we need to scrape these 2 tables which are on the same page of a PDF file."
},
{
"code": null,
"e": 1825,
"s": 1639,
"text": "To read multiple tables we need to add extra parametermultiple_tables = True -> Read multiple tables as independent tablesmultiple_tables = False -> Read multiple tables as single table"
},
{
"code": null,
"e": 2027,
"s": 1825,
"text": "file3 = \"https://nbviewer.jupyter.org/github/kuruvasatya/Reading-Table-Data-From-PDF/blob/master/data3.pdf\"tables = tabula.read_pdf(file3 ,pages=1, multiple_tables=True)print(tables[0])print(tables[1])"
},
{
"code": null,
"e": 2099,
"s": 2027,
"text": "tables = tabula.read_pdf(file3 ,pages=1,multiple_tables=False)tables[0]"
},
{
"code": null,
"e": 2228,
"s": 2099,
"text": "we can directly convert a PDF file containing tabular data directly to a CSV file using convert_into() method in tabula library."
},
{
"code": null,
"e": 2344,
"s": 2228,
"text": "# output just the first page tables in the PDF to a CSVtabula.convert_into(\"pdf_file_name\", \"Name_of_csv_file.csv\")"
},
{
"code": null,
"e": 2415,
"s": 2344,
"text": "tabula.convert_into(\"pdf_file_name\",\"Name_of_csv_file.csv\",all = True)"
},
{
"code": null,
"e": 2503,
"s": 2415,
"text": "I hope you learned a great way to scrape PDF file tables using a single line in python."
}
]
|
D3.js geoAlbers() Function - GeeksforGeeks | 14 Sep, 2020
The geoAlbers() function in d3.js is used to draw the Albers equal-area conic projection. Albers projection which is named after Heinrich C. Albers is a conic, equal-area map projection that uses two standard parallels. The scale and shape are not preserved and the distortion is minimal between the standard parallels. It draws a geoAlbers projection from geojson data.
Syntax:
d3.geoAlbers()
Parameters: This method does not accept any parameters.
Return Values This method returns the visual Albers equal-area conic projection.
Example 1: The following example makes projection of Asia Continent.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <div style="width:700px; height:700px;"> <center> <h4 style="color:green" font ='bold'> geoAlbers Projection of Asia </h4> </center> <svg width="700" height="500"> </svg> </div> <script src="https://d3js.org/d3.v4.js"> </script> <script src=" https://d3js.org/d3-geo-projection.v2.min.js"> </script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // geoAlbers projection var gfg = d3.geoAlbers() .scale(width / 1.5 / Math.PI) .translate([width / 2, height / 2]) // Loading the json data d3.json("https://raw.githubusercontent.com/ janasayantan/datageojson/master/geoasia.json", function(data){ // Draw the map svg.append("g") .selectAll("path") .data(data.features) .enter().append("path") .attr("fill", "black") .attr("d", d3.geoPath() .projection(gfg) ) .style("stroke", "#ffff")}) </script></body> </html>
Output :
Example 2:The The following example shows the projection of World.
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <div style="width:700px; height:700px;"> <center> <h3 style="color:green" font ='bold'> geoAlbers Projection of World </h3> </center> <svg width="700" height="500"> </svg> </div> <script src="https://d3js.org/d3.v4.js"> </script> <script src="https://d3js.org/ d3-geo-projection.v2.min.js"> </script> <script> var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // geoAlbers projection var gfg = d3.geoAlbers() .scale(width / 1.5 / Math.PI) .translate([width / 2, height / 2]) // Loading the json data d3.json("https://raw.githubusercontent.com/ janasayantan/datageojson/master/geoworld%20.json", function(data) { // Draw the map svg.append("g") .selectAll("path") .data(data.features) .enter().append("path") .attr("fill", "grey") .attr("d", d3.geoPath() .projection(gfg) ) .style("stroke", "#ffff") }) </script></body></html>
Output :
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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": 24880,
"s": 24852,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 25251,
"s": 24880,
"text": "The geoAlbers() function in d3.js is used to draw the Albers equal-area conic projection. Albers projection which is named after Heinrich C. Albers is a conic, equal-area map projection that uses two standard parallels. The scale and shape are not preserved and the distortion is minimal between the standard parallels. It draws a geoAlbers projection from geojson data."
},
{
"code": null,
"e": 25259,
"s": 25251,
"text": "Syntax:"
},
{
"code": null,
"e": 25276,
"s": 25259,
"text": " d3.geoAlbers()\n"
},
{
"code": null,
"e": 25332,
"s": 25276,
"text": "Parameters: This method does not accept any parameters."
},
{
"code": null,
"e": 25413,
"s": 25332,
"text": "Return Values This method returns the visual Albers equal-area conic projection."
},
{
"code": null,
"e": 25482,
"s": 25413,
"text": "Example 1: The following example makes projection of Asia Continent."
},
{
"code": null,
"e": 25487,
"s": 25482,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/> </head> <body> <div style=\"width:700px; height:700px;\"> <center> <h4 style=\"color:green\" font ='bold'> geoAlbers Projection of Asia </h4> </center> <svg width=\"700\" height=\"500\"> </svg> </div> <script src=\"https://d3js.org/d3.v4.js\"> </script> <script src=\" https://d3js.org/d3-geo-projection.v2.min.js\"> </script> <script> var svg = d3.select(\"svg\"), width = +svg.attr(\"width\"), height = +svg.attr(\"height\"); // geoAlbers projection var gfg = d3.geoAlbers() .scale(width / 1.5 / Math.PI) .translate([width / 2, height / 2]) // Loading the json data d3.json(\"https://raw.githubusercontent.com/ janasayantan/datageojson/master/geoasia.json\", function(data){ // Draw the map svg.append(\"g\") .selectAll(\"path\") .data(data.features) .enter().append(\"path\") .attr(\"fill\", \"black\") .attr(\"d\", d3.geoPath() .projection(gfg) ) .style(\"stroke\", \"#ffff\")}) </script></body> </html>",
"e": 26757,
"s": 25487,
"text": null
},
{
"code": null,
"e": 26766,
"s": 26757,
"text": "Output :"
},
{
"code": null,
"e": 26833,
"s": 26766,
"text": "Example 2:The The following example shows the projection of World."
},
{
"code": null,
"e": 26838,
"s": 26833,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/> </head> <body> <div style=\"width:700px; height:700px;\"> <center> <h3 style=\"color:green\" font ='bold'> geoAlbers Projection of World </h3> </center> <svg width=\"700\" height=\"500\"> </svg> </div> <script src=\"https://d3js.org/d3.v4.js\"> </script> <script src=\"https://d3js.org/ d3-geo-projection.v2.min.js\"> </script> <script> var svg = d3.select(\"svg\"), width = +svg.attr(\"width\"), height = +svg.attr(\"height\"); // geoAlbers projection var gfg = d3.geoAlbers() .scale(width / 1.5 / Math.PI) .translate([width / 2, height / 2]) // Loading the json data d3.json(\"https://raw.githubusercontent.com/ janasayantan/datageojson/master/geoworld%20.json\", function(data) { // Draw the map svg.append(\"g\") .selectAll(\"path\") .data(data.features) .enter().append(\"path\") .attr(\"fill\", \"grey\") .attr(\"d\", d3.geoPath() .projection(gfg) ) .style(\"stroke\", \"#ffff\") }) </script></body></html>",
"e": 28124,
"s": 26838,
"text": null
},
{
"code": null,
"e": 28133,
"s": 28124,
"text": "Output :"
},
{
"code": null,
"e": 28139,
"s": 28133,
"text": "D3.js"
},
{
"code": null,
"e": 28150,
"s": 28139,
"text": "JavaScript"
},
{
"code": null,
"e": 28167,
"s": 28150,
"text": "Web Technologies"
},
{
"code": null,
"e": 28265,
"s": 28167,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28274,
"s": 28265,
"text": "Comments"
},
{
"code": null,
"e": 28287,
"s": 28274,
"text": "Old Comments"
},
{
"code": null,
"e": 28332,
"s": 28287,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28393,
"s": 28332,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28465,
"s": 28393,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28517,
"s": 28465,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28563,
"s": 28517,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28605,
"s": 28563,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28638,
"s": 28605,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28681,
"s": 28638,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28743,
"s": 28681,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Biopython - Sequence input/output - GeeksforGeeks | 22 Oct, 2020
Biopython has an inbuilt Bio.SeqIO module which provides functionalities to read and write sequences from or to a file respectively. Bio.SeqIO supports nearly all file handling formats used in Bioinformatics. Biopython strictly follows single approach to represent the parsed data sequence to the user with the SeqRecord object.
SeqRecord object provided by the Bio.SeqRecord module holds the metadata of the sequence as well as the information about the sequence. Some main data information are listed below :
Biopython Seq module has a built-in read() method which takes a sequence file and turns it into a single SeqRecord according to the file format. It is able to parse sequence files having exactly one record, if the file has no records or more than one record then an exception is raised. Syntax and arguments of the read() method are given below :
Bio.SeqIO.read(handle, format, alphabet=None)
Python3
# Import librariesfrom Bio import SeqIO # Reading filerecord = SeqIO.read("sequence.gb", "genbank") # Showing recordsprint("ID: %s" % record.id)print("Sequence length: %i" % len(record))print("Sequence description: %s" % record.description)
Output:
The Parse() method provided by the Bio.Seq module is used when we have to read multiple records from the handle. It basically converts the sequence file into an iterator which returns the SeqRecords. If the file contains string data then it must be converted to handle to parse it. The file formats where alphabet can’t be determined, it is useful to specify the alphabet explicitly(ex. FASTA). Syntax and arguments of parse() method are given below :
Bio.SeqIO.parse(handle, format, alphabet=None)
Python3
# Import librariesfrom Bio import SeqIO # Parsing filefilename = "sequence.fasta"for record in SeqIO.parse(filename, "fasta"): # Showing records print("ID: %s" % record.id) print("Sequence length: %i" % len(record)) print("Sequence description: %s" % record.description)
Output :
For writing to the file Bio.Seq module has a write() method, which writes the set of sequences to the file and returns an integer representing the number of records written. Ensure to close the handle after calling the handle else data gets flushed to disk. Syntax and arguments of write() method are given below :
Bio.SeqIO.write(sequences, handle, format)
Note: To download files click here
Python3
# Import librariesfrom Bio import SeqIOfrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecord rec1 = SeqRecord(Seq("MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD" + "GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK" + "NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM"), id="gi|14150838|gb|AAK54648.1|AF376133_1", description="chalcone synthase [Cucumis sativus]") rec2 = SeqRecord(Seq("MVTVEEFRRAQCAEGPATVMAIGTATPSNCVDQSTYPDYYFRITNSEHKVELKEKFKRMC" + "EKSMIKKRYMHLTEEILKENPNICAYMAPSLDARQDIVVVEVPKLGKEAAQKAIKEWGQP" + "KSKITHLVFCTTSGVDMPGCDYQLTKLLGLRPSVKRFMMYQQGCFAGGTVLRMAKDLAEN" + "NKGARVLVVCSEITAVTFRGPNDTHLDSLVGQALFGDGAAAVIIGSDPIPEVERPLFELV" + "SAAQTLLPDSEGAIDGHLREVGLTFHLLKDVPGLISKNIEKSLVEAFQPLGISDWNSLFW" + "IAHPGGPAILDQVELKLGLKQEKLKATRKVLSNYGNMSSACVLFILDEMRKASAKEGLGT" + "TGEGLEWGVLFGFGPGLTVETVVLHSVAT"), id="gi|13925890|gb|AAK49457.1|", description="chalcone synthase [Nicotiana tabacum]")sequences = [rec1, rec2] # Writing to filewith open("example.fasta", "w") as output_handle: SeqIO.write(sequences, output_handle, "fasta") for record in SeqIO.parse("example.fasta", "fasta"): print("ID %s" % record.id) print("Sequence length %i" % len(record))
Output:
Python-BioPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n22 Oct, 2020"
},
{
"code": null,
"e": 24621,
"s": 24292,
"text": "Biopython has an inbuilt Bio.SeqIO module which provides functionalities to read and write sequences from or to a file respectively. Bio.SeqIO supports nearly all file handling formats used in Bioinformatics. Biopython strictly follows single approach to represent the parsed data sequence to the user with the SeqRecord object."
},
{
"code": null,
"e": 24803,
"s": 24621,
"text": "SeqRecord object provided by the Bio.SeqRecord module holds the metadata of the sequence as well as the information about the sequence. Some main data information are listed below :"
},
{
"code": null,
"e": 25150,
"s": 24803,
"text": "Biopython Seq module has a built-in read() method which takes a sequence file and turns it into a single SeqRecord according to the file format. It is able to parse sequence files having exactly one record, if the file has no records or more than one record then an exception is raised. Syntax and arguments of the read() method are given below :"
},
{
"code": null,
"e": 25197,
"s": 25150,
"text": "Bio.SeqIO.read(handle, format, alphabet=None)\n"
},
{
"code": null,
"e": 25205,
"s": 25197,
"text": "Python3"
},
{
"code": "# Import librariesfrom Bio import SeqIO # Reading filerecord = SeqIO.read(\"sequence.gb\", \"genbank\") # Showing recordsprint(\"ID: %s\" % record.id)print(\"Sequence length: %i\" % len(record))print(\"Sequence description: %s\" % record.description)",
"e": 25448,
"s": 25205,
"text": null
},
{
"code": null,
"e": 25456,
"s": 25448,
"text": "Output:"
},
{
"code": null,
"e": 25908,
"s": 25456,
"text": "The Parse() method provided by the Bio.Seq module is used when we have to read multiple records from the handle. It basically converts the sequence file into an iterator which returns the SeqRecords. If the file contains string data then it must be converted to handle to parse it. The file formats where alphabet can’t be determined, it is useful to specify the alphabet explicitly(ex. FASTA). Syntax and arguments of parse() method are given below :"
},
{
"code": null,
"e": 25956,
"s": 25908,
"text": "Bio.SeqIO.parse(handle, format, alphabet=None)\n"
},
{
"code": null,
"e": 25964,
"s": 25956,
"text": "Python3"
},
{
"code": "# Import librariesfrom Bio import SeqIO # Parsing filefilename = \"sequence.fasta\"for record in SeqIO.parse(filename, \"fasta\"): # Showing records print(\"ID: %s\" % record.id) print(\"Sequence length: %i\" % len(record)) print(\"Sequence description: %s\" % record.description)",
"e": 26250,
"s": 25964,
"text": null
},
{
"code": null,
"e": 26259,
"s": 26250,
"text": "Output :"
},
{
"code": null,
"e": 26574,
"s": 26259,
"text": "For writing to the file Bio.Seq module has a write() method, which writes the set of sequences to the file and returns an integer representing the number of records written. Ensure to close the handle after calling the handle else data gets flushed to disk. Syntax and arguments of write() method are given below :"
},
{
"code": null,
"e": 26618,
"s": 26574,
"text": "Bio.SeqIO.write(sequences, handle, format)\n"
},
{
"code": null,
"e": 26653,
"s": 26618,
"text": "Note: To download files click here"
},
{
"code": null,
"e": 26661,
"s": 26653,
"text": "Python3"
},
{
"code": "# Import librariesfrom Bio import SeqIOfrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecord rec1 = SeqRecord(Seq(\"MMYQQGCFAGGTVLRLAKDLAENNRGARVLVVCSEITAVTFRGPSETHLDSMVGQALFGD\" + \"GAGAVIVGSDPDLSVERPLYELVWTGATLLPDSEGAIDGHLREVGLTFHLLKDVPGLISK\" + \"NIEKSLKEAFTPLGISDWNSTFWIAHPGGPAILDQVEAKLGLKEEKMRATREVLSEYGNM\"), id=\"gi|14150838|gb|AAK54648.1|AF376133_1\", description=\"chalcone synthase [Cucumis sativus]\") rec2 = SeqRecord(Seq(\"MVTVEEFRRAQCAEGPATVMAIGTATPSNCVDQSTYPDYYFRITNSEHKVELKEKFKRMC\" + \"EKSMIKKRYMHLTEEILKENPNICAYMAPSLDARQDIVVVEVPKLGKEAAQKAIKEWGQP\" + \"KSKITHLVFCTTSGVDMPGCDYQLTKLLGLRPSVKRFMMYQQGCFAGGTVLRMAKDLAEN\" + \"NKGARVLVVCSEITAVTFRGPNDTHLDSLVGQALFGDGAAAVIIGSDPIPEVERPLFELV\" + \"SAAQTLLPDSEGAIDGHLREVGLTFHLLKDVPGLISKNIEKSLVEAFQPLGISDWNSLFW\" + \"IAHPGGPAILDQVELKLGLKQEKLKATRKVLSNYGNMSSACVLFILDEMRKASAKEGLGT\" + \"TGEGLEWGVLFGFGPGLTVETVVLHSVAT\"), id=\"gi|13925890|gb|AAK49457.1|\", description=\"chalcone synthase [Nicotiana tabacum]\")sequences = [rec1, rec2] # Writing to filewith open(\"example.fasta\", \"w\") as output_handle: SeqIO.write(sequences, output_handle, \"fasta\") for record in SeqIO.parse(\"example.fasta\", \"fasta\"): print(\"ID %s\" % record.id) print(\"Sequence length %i\" % len(record))",
"e": 28097,
"s": 26661,
"text": null
},
{
"code": null,
"e": 28105,
"s": 28097,
"text": "Output:"
},
{
"code": null,
"e": 28122,
"s": 28105,
"text": "Python-BioPython"
},
{
"code": null,
"e": 28129,
"s": 28122,
"text": "Python"
},
{
"code": null,
"e": 28227,
"s": 28129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28259,
"s": 28227,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28315,
"s": 28259,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28357,
"s": 28315,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28399,
"s": 28357,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28421,
"s": 28399,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28452,
"s": 28421,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28491,
"s": 28452,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28546,
"s": 28491,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 28575,
"s": 28546,
"text": "Create a directory in Python"
}
]
|
Clockwise Triangular traversal of a Binary Tree - GeeksforGeeks | 23 Jun, 2021
Given a Complete Binary Tree, the task is to print the elements in the Clockwise traversal order.Clockwise Traversal of a tree is defined as:
For the above binary tree, the Clockwise Triangular traversal will be 0, 2, 6, 14, 13, 12, 11, 10, 9, 8, 7, 3, 1, 5, 4
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ /\
8 9 10 11
Output: 1, 3, 7, 11, 10, 9, 8, 4, 2, 6, 5
Input:
1
/ \
2 3
Output: 1, 3, 2
Approach: Create a vector tree[] where tree[i] will store all the nodes of the tree at level i. Take an integer k which keeps track which level we are traversing other integer and cycle in which keep tracks how many cycles have been completed. Now, start printing the nodes the rightmost remaining node which has not been traversed yet & keep moving down until you reach down to the last level which has not been traversed now print this level from right to left, then move print leftmost remaining leftmost element of each level starting from last level to moving to the uppermost level whose elements has all not been traversed yet, now again do the same thing until all elements have not been traversed.Below is the implementation of the above approach:
C++
Python3
Javascript
// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to create an// edge between two verticesvoid addEdge(int a, int b, vector<int> tree[]){ // Add a to b's list tree[a].push_back(b); // Add b to a's list tree[b].push_back(a);} // Function to create// complete binary treevoid createTree(int n, vector<int> tree[]){ for (int i = 1;; i++) { // Adding edge to // a binary tree int c = 0; if (2 * i <= n) { addEdge(i, 2 * i, tree); c++; } if (2 * i + 1 <= n) { addEdge(i, 2 * i + 1, tree); c++; } if (c == 0) break; }} // Modified Breadth-First Functionvoid bfs(int node, vector<int> tree[], bool vis[], int level[], vector<int> nodes[], int& maxLevel){ // Create a queue of // {child, parent} queue<pair<int, int> > qu; // Push root node in the front of // the queue and mark as visited qu.push({ node, 0 }); nodes[0].push_back(node); vis[node] = true; level[1] = 0; while (!qu.empty()) { pair<int, int> p = qu.front(); // Dequeue a vertex // from queue qu.pop(); vis[p.first] = true; // Get all adjacent vertices of the dequeued // vertex s. If any adjacent has not // been visited then enqueue it for (int child : tree[p.first]) { if (!vis[child]) { qu.push({ child, p.first }); level[child] = level[p.first] + 1; maxLevel = max(maxLevel, level[child]); nodes[level[child]].push_back(child); } } }} // Function to display the patternvoid display(vector<int> nodes[], int maxLevel){ // k represents the level no. // cycle represents how many // cycles has been completed int k = 0, cycle = 0; // While there are nodes // left to traverse while (cycle - 1 <= maxLevel / 2) { // Traversing rightmost element // in each cycle as we move down while (k < maxLevel - cycle) { int j = nodes[k].size() - 1; cout << nodes[k][j - cycle] << " "; k++; } // Traversing each element of remaining // last level from right to left if (k == maxLevel - cycle) { int j = nodes[k].size() - 1; for (j -= cycle; j >= cycle; j--) cout << nodes[k][j] << " "; } k--; // Traversing leftmost remaining element // in each cycle as we move up while (k > cycle) { cout << nodes[k][cycle] << " "; k--; } // No of cycles // completed cycle++; // updating from which level to // start new cycle k = cycle + 1; }} // Driver codeint main(){ // Number of vertices int n = 12; const int sz = 1e5; int maxLevel = 0; vector<int> tree[sz + 1]; bool vis[sz + 1]; int level[sz + 1]; vector<int> nodes[sz + 1]; createTree(n, tree); bfs(1, tree, vis, level, nodes, maxLevel); display(nodes, maxLevel); return 0;}
# Python3 program for the# above approach # Function to create an# edge between two verticesdef addEdge(a, b): # Add a to b's list tree[a].append(b); # Add b to a's list tree[b].append(a); # Function to create# complete binary treedef createTree(n): i = 1 while True: # Adding edge to # a binary tree c = 0; if (2 * i <= n): addEdge(i, 2 * i); c += 1; if (2 * i + 1 <= n): addEdge(i, 2 * i + 1); c += 1 if (c == 0): break; i += 1 # Modified Breadth-First# Functiondef bfs(node, maxLevel): # Create a queue of # {child, parent} qu = [] # Push root node in the # front of the queue and # mark as visited qu.append([node, 0]); nodes[0].append(node); vis[node] = True; level[1] = 0; while (len(qu) != 0): p = qu[0]; # Dequeue a vertex # from queue qu.pop(0); vis[p[0]] = True; # Get all adjacent vertices # of the dequeued vertex s. # If any adjacent has not # been visited then enqueue it for child in tree[p[0]]: if (not vis[child]): qu.append([child, p[0]]); level[child] = level[p[0]] + 1; maxLevel = max(maxLevel, level[child]); nodes[level[child]].append(child); return maxLevel # Function to display# the patterndef display(maxLevel): # k represents the level no. # cycle represents how many # cycles has been completed k = 0 cycle = 0; # While there are nodes # left to traverse while (cycle - 1 <= maxLevel // 2): # Traversing rightmost element # in each cycle as we move down while(k < maxLevel - cycle): j = len(nodes[k]) - 1; print(nodes[k][j - cycle], end = ' ') k += 1 # Traversing each element of # remaining last level from right # to left if (k == maxLevel - cycle): j = len(nodes[k]) - 1 - cycle; while(j >= cycle): print(nodes[k][j], end = ' ') j -= 1 k -= 1 # Traversing leftmost remaining # element in each cycle as we # move up while (k > cycle): print(nodes[k][cycle], end = ' ') k -= 1 # No of cycles # completed cycle += 1 # updating from which # level to start new cycle k = cycle + 1; # Driver codeif __name__=="__main__": # Number of vertices n = 12; sz = 100005; maxLevel = 0; tree = [[] for i in range(sz + 1)] vis = [False for i in range(sz + 1)] level = [0 for i in range(sz + 1)] nodes = [[] for i in range(sz + 1)] createTree(n); maxLevel = bfs(1, maxLevel); display(maxLevel); # This code is contributed by Rutvik_56
<script> // JavaScript program for the above approach let sz = 1e5; let tree = new Array(sz + 1); let nodes = new Array(sz + 1); let vis = new Array(sz + 1); let level = new Array(sz + 1); // Function to create an // edge between two vertices function addEdge(a, b) { // Add a to b's list tree[a].push(b); // Add b to a's list tree[b].push(a); } // Function to create // complete binary tree function createTree(n) { let i = 1; while(true) { // Adding edge to // a binary tree let c = 0; if (2 * i <= n) { addEdge(i, 2 * i); c++; } if (2 * i + 1 <= n) { addEdge(i, 2 * i + 1); c++; } if (c == 0) break; i+=1; } } // Modified Breadth-First Function function bfs(node, maxLevel) { // Create a queue of // {child, parent} let qu = []; // Push root node in the front of // the queue and mark as visited qu.push([ node, 0 ]); nodes[0].push(node); vis[node] = true; level[1] = 0; while (qu.length > 0) { let p = qu[0]; // Dequeue a vertex // from queue qu.shift(); vis[p[0]] = true; // Get all adjacent vertices of the dequeued // vertex s. If any adjacent has not // been visited then enqueue it for (let child = 0; child < tree[p[0]].length; child++) { if (!vis[tree[p[0]][child]]) { qu.push([ tree[p[0]][child], p[0] ]); level[tree[p[0]][child]] = level[p[0]] + 1; maxLevel = Math.max(maxLevel, level[tree[p[0]][child]]); nodes[level[tree[p[0]][child]]]. push(tree[p[0]][child]); } } } return maxLevel; } // Function to display the pattern function display(maxLevel) { // k represents the level no. // cycle represents how many // cycles has been completed let k = 0, cycle = 0; // While there are nodes // left to traverse while (cycle - 1 <= parseInt(maxLevel / 2, 10)) { // Traversing rightmost element // in each cycle as we move down while (k < maxLevel - cycle) { let j = nodes[k].length - 1; document.write(nodes[k][j - cycle] + " "); k++; } // Traversing each element of remaining // last level from right to left if (k == maxLevel - cycle) { let j = nodes[k].length - 1; for (j -= cycle; j >= cycle; j--) document.write(nodes[k][j] + " "); } k--; // Traversing leftmost remaining element // in each cycle as we move up while (k > cycle) { document.write(nodes[k][cycle] + " "); k--; } // No of cycles // completed cycle++; // updating from which level to // start new cycle k = cycle + 1; } } // Number of vertices let n = 12; for(let i = 0; i < sz + 1; i++) { tree[i] = []; vis[i] = false; level[i] = 0; nodes[i] = []; } let maxLevel = 0; createTree(n); maxLevel = bfs(1, maxLevel); display(maxLevel); </script>
1 3 7 12 11 10 9 8 4 2 6 5
Time Complexity: O(n)
rutvik_56
ruhelaa48
simranarora5sos
divyesh072019
Binary Tree
Competitive Programming
Queue
Tree
Queue
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shortest path in a directed graph by Dijkstra’s algorithm
Breadth First Traversal ( BFS ) on a 2D array
Multistage Graph (Shortest Path)
Runtime Errors
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Queue in Python
Queue Interface In Java
Queue | Set 1 (Introduction and Array Implementation) | [
{
"code": null,
"e": 25126,
"s": 25098,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25270,
"s": 25126,
"text": "Given a Complete Binary Tree, the task is to print the elements in the Clockwise traversal order.Clockwise Traversal of a tree is defined as: "
},
{
"code": null,
"e": 25391,
"s": 25270,
"text": "For the above binary tree, the Clockwise Triangular traversal will be 0, 2, 6, 14, 13, 12, 11, 10, 9, 8, 7, 3, 1, 5, 4 "
},
{
"code": null,
"e": 25402,
"s": 25391,
"text": "Examples: "
},
{
"code": null,
"e": 25624,
"s": 25402,
"text": "Input:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n / \\ /\\\n8 9 10 11 \nOutput: 1, 3, 7, 11, 10, 9, 8, 4, 2, 6, 5\n\nInput:\n 1\n / \\\n 2 3\nOutput: 1, 3, 2"
},
{
"code": null,
"e": 26382,
"s": 25624,
"text": "Approach: Create a vector tree[] where tree[i] will store all the nodes of the tree at level i. Take an integer k which keeps track which level we are traversing other integer and cycle in which keep tracks how many cycles have been completed. Now, start printing the nodes the rightmost remaining node which has not been traversed yet & keep moving down until you reach down to the last level which has not been traversed now print this level from right to left, then move print leftmost remaining leftmost element of each level starting from last level to moving to the uppermost level whose elements has all not been traversed yet, now again do the same thing until all elements have not been traversed.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26386,
"s": 26382,
"text": "C++"
},
{
"code": null,
"e": 26394,
"s": 26386,
"text": "Python3"
},
{
"code": null,
"e": 26405,
"s": 26394,
"text": "Javascript"
},
{
"code": "// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to create an// edge between two verticesvoid addEdge(int a, int b, vector<int> tree[]){ // Add a to b's list tree[a].push_back(b); // Add b to a's list tree[b].push_back(a);} // Function to create// complete binary treevoid createTree(int n, vector<int> tree[]){ for (int i = 1;; i++) { // Adding edge to // a binary tree int c = 0; if (2 * i <= n) { addEdge(i, 2 * i, tree); c++; } if (2 * i + 1 <= n) { addEdge(i, 2 * i + 1, tree); c++; } if (c == 0) break; }} // Modified Breadth-First Functionvoid bfs(int node, vector<int> tree[], bool vis[], int level[], vector<int> nodes[], int& maxLevel){ // Create a queue of // {child, parent} queue<pair<int, int> > qu; // Push root node in the front of // the queue and mark as visited qu.push({ node, 0 }); nodes[0].push_back(node); vis[node] = true; level[1] = 0; while (!qu.empty()) { pair<int, int> p = qu.front(); // Dequeue a vertex // from queue qu.pop(); vis[p.first] = true; // Get all adjacent vertices of the dequeued // vertex s. If any adjacent has not // been visited then enqueue it for (int child : tree[p.first]) { if (!vis[child]) { qu.push({ child, p.first }); level[child] = level[p.first] + 1; maxLevel = max(maxLevel, level[child]); nodes[level[child]].push_back(child); } } }} // Function to display the patternvoid display(vector<int> nodes[], int maxLevel){ // k represents the level no. // cycle represents how many // cycles has been completed int k = 0, cycle = 0; // While there are nodes // left to traverse while (cycle - 1 <= maxLevel / 2) { // Traversing rightmost element // in each cycle as we move down while (k < maxLevel - cycle) { int j = nodes[k].size() - 1; cout << nodes[k][j - cycle] << \" \"; k++; } // Traversing each element of remaining // last level from right to left if (k == maxLevel - cycle) { int j = nodes[k].size() - 1; for (j -= cycle; j >= cycle; j--) cout << nodes[k][j] << \" \"; } k--; // Traversing leftmost remaining element // in each cycle as we move up while (k > cycle) { cout << nodes[k][cycle] << \" \"; k--; } // No of cycles // completed cycle++; // updating from which level to // start new cycle k = cycle + 1; }} // Driver codeint main(){ // Number of vertices int n = 12; const int sz = 1e5; int maxLevel = 0; vector<int> tree[sz + 1]; bool vis[sz + 1]; int level[sz + 1]; vector<int> nodes[sz + 1]; createTree(n, tree); bfs(1, tree, vis, level, nodes, maxLevel); display(nodes, maxLevel); return 0;}",
"e": 29547,
"s": 26405,
"text": null
},
{
"code": "# Python3 program for the# above approach # Function to create an# edge between two verticesdef addEdge(a, b): # Add a to b's list tree[a].append(b); # Add b to a's list tree[b].append(a); # Function to create# complete binary treedef createTree(n): i = 1 while True: # Adding edge to # a binary tree c = 0; if (2 * i <= n): addEdge(i, 2 * i); c += 1; if (2 * i + 1 <= n): addEdge(i, 2 * i + 1); c += 1 if (c == 0): break; i += 1 # Modified Breadth-First# Functiondef bfs(node, maxLevel): # Create a queue of # {child, parent} qu = [] # Push root node in the # front of the queue and # mark as visited qu.append([node, 0]); nodes[0].append(node); vis[node] = True; level[1] = 0; while (len(qu) != 0): p = qu[0]; # Dequeue a vertex # from queue qu.pop(0); vis[p[0]] = True; # Get all adjacent vertices # of the dequeued vertex s. # If any adjacent has not # been visited then enqueue it for child in tree[p[0]]: if (not vis[child]): qu.append([child, p[0]]); level[child] = level[p[0]] + 1; maxLevel = max(maxLevel, level[child]); nodes[level[child]].append(child); return maxLevel # Function to display# the patterndef display(maxLevel): # k represents the level no. # cycle represents how many # cycles has been completed k = 0 cycle = 0; # While there are nodes # left to traverse while (cycle - 1 <= maxLevel // 2): # Traversing rightmost element # in each cycle as we move down while(k < maxLevel - cycle): j = len(nodes[k]) - 1; print(nodes[k][j - cycle], end = ' ') k += 1 # Traversing each element of # remaining last level from right # to left if (k == maxLevel - cycle): j = len(nodes[k]) - 1 - cycle; while(j >= cycle): print(nodes[k][j], end = ' ') j -= 1 k -= 1 # Traversing leftmost remaining # element in each cycle as we # move up while (k > cycle): print(nodes[k][cycle], end = ' ') k -= 1 # No of cycles # completed cycle += 1 # updating from which # level to start new cycle k = cycle + 1; # Driver codeif __name__==\"__main__\": # Number of vertices n = 12; sz = 100005; maxLevel = 0; tree = [[] for i in range(sz + 1)] vis = [False for i in range(sz + 1)] level = [0 for i in range(sz + 1)] nodes = [[] for i in range(sz + 1)] createTree(n); maxLevel = bfs(1, maxLevel); display(maxLevel); # This code is contributed by Rutvik_56",
"e": 32623,
"s": 29547,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach let sz = 1e5; let tree = new Array(sz + 1); let nodes = new Array(sz + 1); let vis = new Array(sz + 1); let level = new Array(sz + 1); // Function to create an // edge between two vertices function addEdge(a, b) { // Add a to b's list tree[a].push(b); // Add b to a's list tree[b].push(a); } // Function to create // complete binary tree function createTree(n) { let i = 1; while(true) { // Adding edge to // a binary tree let c = 0; if (2 * i <= n) { addEdge(i, 2 * i); c++; } if (2 * i + 1 <= n) { addEdge(i, 2 * i + 1); c++; } if (c == 0) break; i+=1; } } // Modified Breadth-First Function function bfs(node, maxLevel) { // Create a queue of // {child, parent} let qu = []; // Push root node in the front of // the queue and mark as visited qu.push([ node, 0 ]); nodes[0].push(node); vis[node] = true; level[1] = 0; while (qu.length > 0) { let p = qu[0]; // Dequeue a vertex // from queue qu.shift(); vis[p[0]] = true; // Get all adjacent vertices of the dequeued // vertex s. If any adjacent has not // been visited then enqueue it for (let child = 0; child < tree[p[0]].length; child++) { if (!vis[tree[p[0]][child]]) { qu.push([ tree[p[0]][child], p[0] ]); level[tree[p[0]][child]] = level[p[0]] + 1; maxLevel = Math.max(maxLevel, level[tree[p[0]][child]]); nodes[level[tree[p[0]][child]]]. push(tree[p[0]][child]); } } } return maxLevel; } // Function to display the pattern function display(maxLevel) { // k represents the level no. // cycle represents how many // cycles has been completed let k = 0, cycle = 0; // While there are nodes // left to traverse while (cycle - 1 <= parseInt(maxLevel / 2, 10)) { // Traversing rightmost element // in each cycle as we move down while (k < maxLevel - cycle) { let j = nodes[k].length - 1; document.write(nodes[k][j - cycle] + \" \"); k++; } // Traversing each element of remaining // last level from right to left if (k == maxLevel - cycle) { let j = nodes[k].length - 1; for (j -= cycle; j >= cycle; j--) document.write(nodes[k][j] + \" \"); } k--; // Traversing leftmost remaining element // in each cycle as we move up while (k > cycle) { document.write(nodes[k][cycle] + \" \"); k--; } // No of cycles // completed cycle++; // updating from which level to // start new cycle k = cycle + 1; } } // Number of vertices let n = 12; for(let i = 0; i < sz + 1; i++) { tree[i] = []; vis[i] = false; level[i] = 0; nodes[i] = []; } let maxLevel = 0; createTree(n); maxLevel = bfs(1, maxLevel); display(maxLevel); </script>",
"e": 36340,
"s": 32623,
"text": null
},
{
"code": null,
"e": 36367,
"s": 36340,
"text": "1 3 7 12 11 10 9 8 4 2 6 5"
},
{
"code": null,
"e": 36392,
"s": 36369,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 36402,
"s": 36392,
"text": "rutvik_56"
},
{
"code": null,
"e": 36412,
"s": 36402,
"text": "ruhelaa48"
},
{
"code": null,
"e": 36428,
"s": 36412,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36442,
"s": 36428,
"text": "divyesh072019"
},
{
"code": null,
"e": 36454,
"s": 36442,
"text": "Binary Tree"
},
{
"code": null,
"e": 36478,
"s": 36454,
"text": "Competitive Programming"
},
{
"code": null,
"e": 36484,
"s": 36478,
"text": "Queue"
},
{
"code": null,
"e": 36489,
"s": 36484,
"text": "Tree"
},
{
"code": null,
"e": 36495,
"s": 36489,
"text": "Queue"
},
{
"code": null,
"e": 36500,
"s": 36495,
"text": "Tree"
},
{
"code": null,
"e": 36598,
"s": 36500,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36656,
"s": 36598,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 36702,
"s": 36656,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 36735,
"s": 36702,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 36750,
"s": 36735,
"text": "Runtime Errors"
},
{
"code": null,
"e": 36834,
"s": 36750,
"text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 36874,
"s": 36834,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 36908,
"s": 36874,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 36924,
"s": 36908,
"text": "Queue in Python"
},
{
"code": null,
"e": 36948,
"s": 36924,
"text": "Queue Interface In Java"
}
]
|
How to get the height of sibling div and send data to sibling component in Angular? - GeeksforGeeks | 12 Mar, 2021
In this post we will see how we can fetch the height of dynamic div in one component and send it to its sibling component in Angular. This task needs an understanding of some basic angular and DOM concepts. In angular, we can send and receive data to siblings using many methods and one of them is through the parent. See the figure below.
In Angular we can perform these steps:
Create an EventEmitter<T> object and send data to parent using @Output() decorator.
Receive data from parent using @Input() decorator.
Calculate the height of div using offsetHeight property of DOM and send it back to parent.
Receive the height from parent.
Let’s demonstrate these steps using a simple example. We will create two components : sibling1 and sibling2. In sibling1, we will take comma-separated input from user and use it to dynamically populate sibling2. The sibling2 component will dynamically send back its height to sibling1 through the parent.
Prerequisites: NPM must be installed.
Environment setup:
Install Angular and create a new project.npm install -g @angular/cli
ng new <project-name>
cd <project-name>Steps :
Install Angular and create a new project.
npm install -g @angular/cli
ng new <project-name>
cd <project-name>
Steps :
Create 2 new components named sibling1 and sibling2, this will create two new directories with 4 files in each.ng g c sibling1
ng g c sibling2
Create 2 new components named sibling1 and sibling2, this will create two new directories with 4 files in each.
ng g c sibling1
ng g c sibling2
In the above code, we have set the height variable as input to this component using @Input() decorator. The emitter object is an EventEmitter object. In send() method, we are using value of target element and emitting the data.
sibling1.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-sibling1', templateUrl: './sibling1.component.html', styleUrls: ['./sibling1.component.css']})export class Sibling1Component implements OnInit { constructor() { } ngOnInit(): void { this.height = 0; } @Input() height; @Output() emitter:EventEmitter<any> = new EventEmitter(); send(e){ let data = e.target.value; this.emitter.emit(data); }}
There is a input field that uses send() method on keyup event. To show the height variable, we have used a <p> tag.
sibling1.component.html
<input type="text" (keyup)="send($event)"> <p>Height of Sibling is {{height}}</p>
In this file, we have set the data variable as input and emitter object to emit the height. In send() method, we have emitted the height of div component. Now add the following code to sibling2.component.html:
sibling2.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-sibling2', templateUrl: './sibling2.component.html', styleUrls: ['./sibling2.component.css']})export class Sibling2Component implements OnInit { constructor() { } ngOnInit(): void { this.data = []; } @Input() data; @Output() emitter:EventEmitter<any> = new EventEmitter(); send(){ let height = document.querySelector('div').offsetHeight; this.emitter.emit(height); }}
Here we have used the DOMCharacterDataModified event to detect change in div on insertion of new data. The elements in data array are displayed in the inner <p> tag.
sibling2.component.html
<div id="targetDiv" (DOMCharacterDataModified)="send()"> <p *ngFor="let d of data">{{d}}</p> </div>
Now we have to add these components to app component. Add the following code to app.component.ts to create variables to transfer data among siblings:
app.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements OnInit{ height; data; ngOnInit(){ this.height = 0; this.data = []; } mergeData(data){ // Convert the string to array of strings this.data = data.split(","); } mergeHeight(height){ this.height = height; }}
The height and data variables will be used as input to components. The mergeData() and mergeHeight() methods will set the data to these variables. Now display these components in app.component.html :
app.component.html
<app-sibling1 [height]="height" (emitter)="mergeData($event)"></app-sibling1> <app-sibling2 [data]="data" (emitter)="mergeHeight($event)"></app-sibling2>
Now run the app using:
ng serve -o
Output: You should see the following output.
Note that the data sent to other component is used to dynamically increase or decrease the height of div that is being sent to the sibling component.
AngularJS-Questions
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25133,
"s": 25105,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 25473,
"s": 25133,
"text": "In this post we will see how we can fetch the height of dynamic div in one component and send it to its sibling component in Angular. This task needs an understanding of some basic angular and DOM concepts. In angular, we can send and receive data to siblings using many methods and one of them is through the parent. See the figure below."
},
{
"code": null,
"e": 25512,
"s": 25473,
"text": "In Angular we can perform these steps:"
},
{
"code": null,
"e": 25596,
"s": 25512,
"text": "Create an EventEmitter<T> object and send data to parent using @Output() decorator."
},
{
"code": null,
"e": 25647,
"s": 25596,
"text": "Receive data from parent using @Input() decorator."
},
{
"code": null,
"e": 25738,
"s": 25647,
"text": "Calculate the height of div using offsetHeight property of DOM and send it back to parent."
},
{
"code": null,
"e": 25770,
"s": 25738,
"text": "Receive the height from parent."
},
{
"code": null,
"e": 26075,
"s": 25770,
"text": "Let’s demonstrate these steps using a simple example. We will create two components : sibling1 and sibling2. In sibling1, we will take comma-separated input from user and use it to dynamically populate sibling2. The sibling2 component will dynamically send back its height to sibling1 through the parent."
},
{
"code": null,
"e": 26113,
"s": 26075,
"text": "Prerequisites: NPM must be installed."
},
{
"code": null,
"e": 26132,
"s": 26113,
"text": "Environment setup:"
},
{
"code": null,
"e": 26248,
"s": 26132,
"text": "Install Angular and create a new project.npm install -g @angular/cli\nng new <project-name>\ncd <project-name>Steps :"
},
{
"code": null,
"e": 26290,
"s": 26248,
"text": "Install Angular and create a new project."
},
{
"code": null,
"e": 26358,
"s": 26290,
"text": "npm install -g @angular/cli\nng new <project-name>\ncd <project-name>"
},
{
"code": null,
"e": 26366,
"s": 26358,
"text": "Steps :"
},
{
"code": null,
"e": 26509,
"s": 26366,
"text": "Create 2 new components named sibling1 and sibling2, this will create two new directories with 4 files in each.ng g c sibling1\nng g c sibling2"
},
{
"code": null,
"e": 26621,
"s": 26509,
"text": "Create 2 new components named sibling1 and sibling2, this will create two new directories with 4 files in each."
},
{
"code": null,
"e": 26653,
"s": 26621,
"text": "ng g c sibling1\nng g c sibling2"
},
{
"code": null,
"e": 26881,
"s": 26653,
"text": "In the above code, we have set the height variable as input to this component using @Input() decorator. The emitter object is an EventEmitter object. In send() method, we are using value of target element and emitting the data."
},
{
"code": null,
"e": 26903,
"s": 26881,
"text": "sibling1.component.ts"
},
{
"code": "import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-sibling1', templateUrl: './sibling1.component.html', styleUrls: ['./sibling1.component.css']})export class Sibling1Component implements OnInit { constructor() { } ngOnInit(): void { this.height = 0; } @Input() height; @Output() emitter:EventEmitter<any> = new EventEmitter(); send(e){ let data = e.target.value; this.emitter.emit(data); }}",
"e": 27379,
"s": 26903,
"text": null
},
{
"code": null,
"e": 27495,
"s": 27379,
"text": "There is a input field that uses send() method on keyup event. To show the height variable, we have used a <p> tag."
},
{
"code": null,
"e": 27519,
"s": 27495,
"text": "sibling1.component.html"
},
{
"code": "<input type=\"text\" (keyup)=\"send($event)\"> <p>Height of Sibling is {{height}}</p>",
"e": 27602,
"s": 27519,
"text": null
},
{
"code": null,
"e": 27812,
"s": 27602,
"text": "In this file, we have set the data variable as input and emitter object to emit the height. In send() method, we have emitted the height of div component. Now add the following code to sibling2.component.html:"
},
{
"code": null,
"e": 27834,
"s": 27812,
"text": "sibling2.component.ts"
},
{
"code": "import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-sibling2', templateUrl: './sibling2.component.html', styleUrls: ['./sibling2.component.css']})export class Sibling2Component implements OnInit { constructor() { } ngOnInit(): void { this.data = []; } @Input() data; @Output() emitter:EventEmitter<any> = new EventEmitter(); send(){ let height = document.querySelector('div').offsetHeight; this.emitter.emit(height); }}",
"e": 28336,
"s": 27834,
"text": null
},
{
"code": null,
"e": 28502,
"s": 28336,
"text": "Here we have used the DOMCharacterDataModified event to detect change in div on insertion of new data. The elements in data array are displayed in the inner <p> tag."
},
{
"code": null,
"e": 28526,
"s": 28502,
"text": "sibling2.component.html"
},
{
"code": "<div id=\"targetDiv\" (DOMCharacterDataModified)=\"send()\"> <p *ngFor=\"let d of data\">{{d}}</p> </div>",
"e": 28634,
"s": 28526,
"text": null
},
{
"code": null,
"e": 28784,
"s": 28634,
"text": "Now we have to add these components to app component. Add the following code to app.component.ts to create variables to transfer data among siblings:"
},
{
"code": null,
"e": 28801,
"s": 28784,
"text": "app.component.ts"
},
{
"code": "import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent implements OnInit{ height; data; ngOnInit(){ this.height = 0; this.data = []; } mergeData(data){ // Convert the string to array of strings this.data = data.split(\",\"); } mergeHeight(height){ this.height = height; }}",
"e": 29231,
"s": 28801,
"text": null
},
{
"code": null,
"e": 29431,
"s": 29231,
"text": "The height and data variables will be used as input to components. The mergeData() and mergeHeight() methods will set the data to these variables. Now display these components in app.component.html :"
},
{
"code": null,
"e": 29450,
"s": 29431,
"text": "app.component.html"
},
{
"code": "<app-sibling1 [height]=\"height\" (emitter)=\"mergeData($event)\"></app-sibling1> <app-sibling2 [data]=\"data\" (emitter)=\"mergeHeight($event)\"></app-sibling2>",
"e": 29647,
"s": 29450,
"text": null
},
{
"code": null,
"e": 29670,
"s": 29647,
"text": "Now run the app using:"
},
{
"code": null,
"e": 29682,
"s": 29670,
"text": "ng serve -o"
},
{
"code": null,
"e": 29727,
"s": 29682,
"text": "Output: You should see the following output."
},
{
"code": null,
"e": 29877,
"s": 29727,
"text": "Note that the data sent to other component is used to dynamically increase or decrease the height of div that is being sent to the sibling component."
},
{
"code": null,
"e": 29897,
"s": 29877,
"text": "AngularJS-Questions"
},
{
"code": null,
"e": 29904,
"s": 29897,
"text": "Picked"
},
{
"code": null,
"e": 29914,
"s": 29904,
"text": "AngularJS"
},
{
"code": null,
"e": 29931,
"s": 29914,
"text": "Web Technologies"
},
{
"code": null,
"e": 30029,
"s": 29931,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30073,
"s": 30029,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 30097,
"s": 30073,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 30132,
"s": 30097,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 30185,
"s": 30132,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 30234,
"s": 30185,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 30276,
"s": 30234,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 30309,
"s": 30276,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 30352,
"s": 30309,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 30414,
"s": 30352,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
C program that does not suspend when Ctrl+Z is pressed | In Programing when a program malfunction and runs unusually in the terminal compiler the programmer has the power to explicitly stop the program from running. For explicitly stopping the program, the user must know the right keyboard shortcut that is needed to be pressed.
To terminate the execution of a block of code, there are two types of keyboard shortcuts used.
Ctrl+c − It is used to stop the execution of the program, it take a bit of time to complete the i/o operations and then suspends the execution. It sends a SIGINT signal to the process which gets terminated. In some languages, there are ways to handle this SIGINT like the signal function in C.
Ctrl+c − It is used to stop the execution of the program, it take a bit of time to complete the i/o operations and then suspends the execution. It sends a SIGINT signal to the process which gets terminated. In some languages, there are ways to handle this SIGINT like the signal function in C.
Ctrl+z − It is used to stop the execution of the program, all the tasks related to the process are shut and execution is suspended. It sends a SINTSTP signal to the process which terminates the program though the implementation is the same but this signal is more powerful as compared to others. This can also be handled.
Ctrl+z − It is used to stop the execution of the program, all the tasks related to the process are shut and execution is suspended. It sends a SINTSTP signal to the process which terminates the program though the implementation is the same but this signal is more powerful as compared to others. This can also be handled.
Here, we will write a code that will be able to surpass the ctrl+z call. And instead of getting suspended the program will print “ctrl+z cannot suspend this code”.
As discussed above, the ctrl+z call can be handled in the C programming language. When the SINTSTP signal is invoked to end the process of the program. We will redefine what this signal does so that I will not terminate the code and print a line when used.
The signal() method is used to handle this type of thing.
Live Demo
#include <stdio.h>
#include <signal.h>
void signalhandler(int sig_num){
signal(SIGTSTP, signalhandler);
printf("Cannot execute Ctrl+Z\n");
}
int main(){
int a = 1;
signal(SIGTSTP, signalhandler);
while(a){
}
return 0;
}
// an infinite loop | [
{
"code": null,
"e": 1335,
"s": 1062,
"text": "In Programing when a program malfunction and runs unusually in the terminal compiler the programmer has the power to explicitly stop the program from running. For explicitly stopping the program, the user must know the right keyboard shortcut that is needed to be pressed."
},
{
"code": null,
"e": 1430,
"s": 1335,
"text": "To terminate the execution of a block of code, there are two types of keyboard shortcuts used."
},
{
"code": null,
"e": 1724,
"s": 1430,
"text": "Ctrl+c − It is used to stop the execution of the program, it take a bit of time to complete the i/o operations and then suspends the execution. It sends a SIGINT signal to the process which gets terminated. In some languages, there are ways to handle this SIGINT like the signal function in C."
},
{
"code": null,
"e": 2018,
"s": 1724,
"text": "Ctrl+c − It is used to stop the execution of the program, it take a bit of time to complete the i/o operations and then suspends the execution. It sends a SIGINT signal to the process which gets terminated. In some languages, there are ways to handle this SIGINT like the signal function in C."
},
{
"code": null,
"e": 2340,
"s": 2018,
"text": "Ctrl+z − It is used to stop the execution of the program, all the tasks related to the process are shut and execution is suspended. It sends a SINTSTP signal to the process which terminates the program though the implementation is the same but this signal is more powerful as compared to others. This can also be handled."
},
{
"code": null,
"e": 2662,
"s": 2340,
"text": "Ctrl+z − It is used to stop the execution of the program, all the tasks related to the process are shut and execution is suspended. It sends a SINTSTP signal to the process which terminates the program though the implementation is the same but this signal is more powerful as compared to others. This can also be handled."
},
{
"code": null,
"e": 2826,
"s": 2662,
"text": "Here, we will write a code that will be able to surpass the ctrl+z call. And instead of getting suspended the program will print “ctrl+z cannot suspend this code”."
},
{
"code": null,
"e": 3083,
"s": 2826,
"text": "As discussed above, the ctrl+z call can be handled in the C programming language. When the SINTSTP signal is invoked to end the process of the program. We will redefine what this signal does so that I will not terminate the code and print a line when used."
},
{
"code": null,
"e": 3141,
"s": 3083,
"text": "The signal() method is used to handle this type of thing."
},
{
"code": null,
"e": 3152,
"s": 3141,
"text": " Live Demo"
},
{
"code": null,
"e": 3393,
"s": 3152,
"text": "#include <stdio.h>\n#include <signal.h>\nvoid signalhandler(int sig_num){\n signal(SIGTSTP, signalhandler);\n printf(\"Cannot execute Ctrl+Z\\n\");\n}\nint main(){\n int a = 1;\n signal(SIGTSTP, signalhandler);\n while(a){\n }\n return 0;\n}"
},
{
"code": null,
"e": 3413,
"s": 3393,
"text": "// an infinite loop"
}
]
|
Example of goto in C or C++ | The goto statement is a jump statement that allows the program control to jump from goto to a label. Using the goto statement is frowned upon as it makes the program convoluted and hard to understand.
The following is the syntax of goto statement.
goto label;
.
.
.
label: statements;
A program that demonstrates the goto statement in C++ is given as follows.
Live Demo
#include <iostream>
using namespace std;
int main () {
int i = 1;
while(1) {
cout<< i <<"\n";
if(i == 10)
goto OUT;
i++;
}
OUT: cout<<"Out of the while loop";
return 0;
}
The output of the above program is as follows.
1
2
3
4
5
6
7
8
9
10
Out of the while loop
Now, let us understand the above program.
A while loop is used in the above program. In each pass of the while loop, the value of i is displayed. Then, if statement is used to check if the value of i is 10. If so, then goto statement is used to leave the while loop. Otherwise, i is incremented by 1.
The label used with the goto statement is OUT and it leads the program control out of the while loop. Then "Out of the while loop" is displayed. The code snippet for this is given as follows.
int i = 1;
while(1) {
cout<< i <<"\n";
if(i == 10)
goto OUT;
i++;
}
OUT: cout<<"Out of the while loop"; | [
{
"code": null,
"e": 1263,
"s": 1062,
"text": "The goto statement is a jump statement that allows the program control to jump from goto to a label. Using the goto statement is frowned upon as it makes the program convoluted and hard to understand."
},
{
"code": null,
"e": 1310,
"s": 1263,
"text": "The following is the syntax of goto statement."
},
{
"code": null,
"e": 1347,
"s": 1310,
"text": "goto label;\n.\n.\n.\nlabel: statements;"
},
{
"code": null,
"e": 1422,
"s": 1347,
"text": "A program that demonstrates the goto statement in C++ is given as follows."
},
{
"code": null,
"e": 1433,
"s": 1422,
"text": " Live Demo"
},
{
"code": null,
"e": 1643,
"s": 1433,
"text": "#include <iostream>\nusing namespace std;\nint main () {\n int i = 1;\n while(1) {\n cout<< i <<\"\\n\";\n if(i == 10)\n goto OUT;\n i++;\n }\n OUT: cout<<\"Out of the while loop\";\n return 0;\n}"
},
{
"code": null,
"e": 1690,
"s": 1643,
"text": "The output of the above program is as follows."
},
{
"code": null,
"e": 1733,
"s": 1690,
"text": "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\nOut of the while loop"
},
{
"code": null,
"e": 1775,
"s": 1733,
"text": "Now, let us understand the above program."
},
{
"code": null,
"e": 2034,
"s": 1775,
"text": "A while loop is used in the above program. In each pass of the while loop, the value of i is displayed. Then, if statement is used to check if the value of i is 10. If so, then goto statement is used to leave the while loop. Otherwise, i is incremented by 1."
},
{
"code": null,
"e": 2226,
"s": 2034,
"text": "The label used with the goto statement is OUT and it leads the program control out of the while loop. Then \"Out of the while loop\" is displayed. The code snippet for this is given as follows."
},
{
"code": null,
"e": 2342,
"s": 2226,
"text": "int i = 1;\nwhile(1) {\n cout<< i <<\"\\n\";\n if(i == 10)\n goto OUT;\n i++;\n}\nOUT: cout<<\"Out of the while loop\";"
}
]
|
Node.js process.title Property - GeeksforGeeks | 12 Oct, 2021
The process.title property is an inbuilt application programming interface of the process module which is used to get and set the title of the process.
Syntax:
process.title
Return Value: This property returns a string value that specifies the title of the process, current value is ‘ps’.
Note: Assigning the new value to this property will modify the current value. The different platforms can impose a restriction on the maximum length of process title.
Below examples illustrate the use of process.title property in Node.js:
Example 1:
// Node.js program to demonstrate the // process.title property // Include process moduleconst process = require('process'); // Printing process.title property valueconsole.log("PID: " + process.pid + " process title is " + process.title);
Output:
PID: 8852 process title is Command Prompt - node title_1
Example 2:
// Node.js program to demonstrate the // process.title property // Include process moduleconst process = require('process'); // Printing process.title property valueconsole.log("Before modification: PID: " + process.pid +" process title is " + process.title); // Setting new process title valueprocess.title = "gekchosCustomProcess"; // Printing process.title value after modificationconsole.log("After modification: PID: " + process.pid + " process title is " + process.title);
Output:
Before modification: PID: 14012 process title is Command Prompt - node title_2
After modification: PID: 14012 process title is gekchosCustomProcess
Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/process.html#process_process_title
Node.js-process-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 25002,
"s": 24974,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 25154,
"s": 25002,
"text": "The process.title property is an inbuilt application programming interface of the process module which is used to get and set the title of the process."
},
{
"code": null,
"e": 25162,
"s": 25154,
"text": "Syntax:"
},
{
"code": null,
"e": 25176,
"s": 25162,
"text": "process.title"
},
{
"code": null,
"e": 25291,
"s": 25176,
"text": "Return Value: This property returns a string value that specifies the title of the process, current value is ‘ps’."
},
{
"code": null,
"e": 25458,
"s": 25291,
"text": "Note: Assigning the new value to this property will modify the current value. The different platforms can impose a restriction on the maximum length of process title."
},
{
"code": null,
"e": 25530,
"s": 25458,
"text": "Below examples illustrate the use of process.title property in Node.js:"
},
{
"code": null,
"e": 25541,
"s": 25530,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // process.title property // Include process moduleconst process = require('process'); // Printing process.title property valueconsole.log(\"PID: \" + process.pid + \" process title is \" + process.title);",
"e": 25792,
"s": 25541,
"text": null
},
{
"code": null,
"e": 25800,
"s": 25792,
"text": "Output:"
},
{
"code": null,
"e": 25859,
"s": 25800,
"text": "PID: 8852 process title is Command Prompt - node title_1\n"
},
{
"code": null,
"e": 25870,
"s": 25859,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // process.title property // Include process moduleconst process = require('process'); // Printing process.title property valueconsole.log(\"Before modification: PID: \" + process.pid +\" process title is \" + process.title); // Setting new process title valueprocess.title = \"gekchosCustomProcess\"; // Printing process.title value after modificationconsole.log(\"After modification: PID: \" + process.pid + \" process title is \" + process.title);",
"e": 26374,
"s": 25870,
"text": null
},
{
"code": null,
"e": 26382,
"s": 26374,
"text": "Output:"
},
{
"code": null,
"e": 26532,
"s": 26382,
"text": "Before modification: PID: 14012 process title is Command Prompt - node title_2\nAfter modification: PID: 14012 process title is gekchosCustomProcess\n"
},
{
"code": null,
"e": 26616,
"s": 26532,
"text": "Note: The above program will compile and run by using the node filename.js command."
},
{
"code": null,
"e": 26685,
"s": 26616,
"text": "Reference: https://nodejs.org/api/process.html#process_process_title"
},
{
"code": null,
"e": 26708,
"s": 26685,
"text": "Node.js-process-module"
},
{
"code": null,
"e": 26716,
"s": 26708,
"text": "Node.js"
},
{
"code": null,
"e": 26733,
"s": 26716,
"text": "Web Technologies"
},
{
"code": null,
"e": 26831,
"s": 26733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26868,
"s": 26831,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26900,
"s": 26868,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 26931,
"s": 26900,
"text": "Express.js req.params Property"
},
{
"code": null,
"e": 26958,
"s": 26931,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 27005,
"s": 26958,
"text": "Difference between npm i and npm ci in Node.js"
},
{
"code": null,
"e": 27047,
"s": 27005,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27090,
"s": 27047,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27140,
"s": 27090,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 27202,
"s": 27140,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
]
|
Making a div vertically scrollable using CSS | 10 May, 2022
Making a div vertically scrollable is easy by using CSS overflow property. There are different values in overflow property. For example: overflow:auto; and the axis hiding procedure like overflow-x:hidden; and overflow-y:auto;. It will make vertical and horizontal scrollable bar and the auto will make only vertically scrollable bar.
For vertical scrollable bar use the x and y axis. Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable.
Example 1:
html
<!DOCTYPE html><html> <head> <style> h1 { color:Green; } div.scroll { margin:4px, 4px; padding:4px; background-color: green; width: 500px; height: 110px; overflow-x: hidden; overflow-y: auto; text-align:justify; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <div class="scroll">It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article </div> </center> </body></html>
Output:
Example 2: In this example use auto in place of overflow-x:hidden; and overflow-y:auto; to make div vertically scrollable.
html
<!DOCTYPE html><html> <head> <style> h1 { color:Green; } div.gfg { margin:5px; padding:5px; background-color: green; width: 500px; height: 110px; overflow: auto; text-align:justify; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <div class="gfg">It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article </div> </center> </body></html>
Output:
CSS is the foundation of webpages, and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
ankit bajpai
hardikkoriintern
CSS-Misc
Picked
Technical Scripter 2018
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 388,
"s": 52,
"text": "Making a div vertically scrollable is easy by using CSS overflow property. There are different values in overflow property. For example: overflow:auto; and the axis hiding procedure like overflow-x:hidden; and overflow-y:auto;. It will make vertical and horizontal scrollable bar and the auto will make only vertically scrollable bar. "
},
{
"code": null,
"e": 630,
"s": 388,
"text": "For vertical scrollable bar use the x and y axis. Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable. "
},
{
"code": null,
"e": 642,
"s": 630,
"text": "Example 1: "
},
{
"code": null,
"e": 647,
"s": 642,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color:Green; } div.scroll { margin:4px, 4px; padding:4px; background-color: green; width: 500px; height: 110px; overflow-x: hidden; overflow-y: auto; text-align:justify; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <div class=\"scroll\">It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article </div> </center> </body></html> ",
"e": 2118,
"s": 647,
"text": null
},
{
"code": null,
"e": 2126,
"s": 2118,
"text": "Output:"
},
{
"code": null,
"e": 2280,
"s": 2156,
"text": "Example 2: In this example use auto in place of overflow-x:hidden; and overflow-y:auto; to make div vertically scrollable. "
},
{
"code": null,
"e": 2285,
"s": 2280,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <style> h1 { color:Green; } div.gfg { margin:5px; padding:5px; background-color: green; width: 500px; height: 110px; overflow: auto; text-align:justify; } </style> </head> <body> <center> <h1>GeeksforGeeks</h1> <div class=\"gfg\">It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification/improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article </div> </center> </body></html> ",
"e": 3708,
"s": 2285,
"text": null
},
{
"code": null,
"e": 3717,
"s": 3708,
"text": "Output: "
},
{
"code": null,
"e": 3945,
"s": 3754,
"text": "CSS is the foundation of webpages, and is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 3958,
"s": 3945,
"text": "ankit bajpai"
},
{
"code": null,
"e": 3975,
"s": 3958,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 3984,
"s": 3975,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3991,
"s": 3984,
"text": "Picked"
},
{
"code": null,
"e": 4015,
"s": 3991,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4019,
"s": 4015,
"text": "CSS"
},
{
"code": null,
"e": 4024,
"s": 4019,
"text": "HTML"
},
{
"code": null,
"e": 4043,
"s": 4024,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4060,
"s": 4043,
"text": "Web Technologies"
},
{
"code": null,
"e": 4065,
"s": 4060,
"text": "HTML"
}
]
|
Python – Random range in list | 11 Oct, 2020
Given a List, extract random range from it.
Input : test_list = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] Output : [5, 7, 2, 1] Explanation : A random range elements are extracted of any length.
Input : test_list = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] Output : [4, 8] Explanation : A random range elements are extracted of any length.
Method : Using randrange() + slicing
randrange(): Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module.
In this, we extract index of list, and for first index, and then again employ the function to get end part of range using randrange() from start index to list length. The range is extracted using slicing.
Python3
# Python3 code to demonstrate working of# Random range in list# Using randrange() + slicingimport random # function to Random range in listdef rabdomRangeList(test_list): # getting ranges strt_idx = random.randrange(0, len(test_list) - 1) end_idx = random.randrange(strt_idx, len(test_list) - 1) # getting range elements res = test_list[strt_idx: end_idx] return str(res) # Driver Code# initializing listinput_list1 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] # printing original listprint("\nThe original list is : ", input_list1) # printing resultprint("Required List : " + rabdomRangeList(input_list1)) # initializing listinput_list2 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] # printing original listprint("\nThe original list is : ", input_list2) # printing resultprint("Required List : " + rabdomRangeList(input_list2)) # initializing listinput_list3 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] # printing original listprint("\nThe original list is : ", input_list3) # printing resultprint("Required List : " + rabdomRangeList(input_list3))
Output:
The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Required List : [19]
The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Required List : [10, 13, 5, 7]
The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]
Required List : []
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 73,
"s": 28,
"text": "Given a List, extract random range from it. "
},
{
"code": null,
"e": 219,
"s": 73,
"text": "Input : test_list = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] Output : [5, 7, 2, 1] Explanation : A random range elements are extracted of any length."
},
{
"code": null,
"e": 360,
"s": 219,
"text": "Input : test_list = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] Output : [4, 8] Explanation : A random range elements are extracted of any length. "
},
{
"code": null,
"e": 397,
"s": 360,
"text": "Method : Using randrange() + slicing"
},
{
"code": null,
"e": 578,
"s": 397,
"text": "randrange(): Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module."
},
{
"code": null,
"e": 783,
"s": 578,
"text": "In this, we extract index of list, and for first index, and then again employ the function to get end part of range using randrange() from start index to list length. The range is extracted using slicing."
},
{
"code": null,
"e": 791,
"s": 783,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Random range in list# Using randrange() + slicingimport random # function to Random range in listdef rabdomRangeList(test_list): # getting ranges strt_idx = random.randrange(0, len(test_list) - 1) end_idx = random.randrange(strt_idx, len(test_list) - 1) # getting range elements res = test_list[strt_idx: end_idx] return str(res) # Driver Code# initializing listinput_list1 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] # printing original listprint(\"\\nThe original list is : \", input_list1) # printing resultprint(\"Required List : \" + rabdomRangeList(input_list1)) # initializing listinput_list2 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] # printing original listprint(\"\\nThe original list is : \", input_list2) # printing resultprint(\"Required List : \" + rabdomRangeList(input_list2)) # initializing listinput_list3 = [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4] # printing original listprint(\"\\nThe original list is : \", input_list3) # printing resultprint(\"Required List : \" + rabdomRangeList(input_list3))",
"e": 1864,
"s": 791,
"text": null
},
{
"code": null,
"e": 1872,
"s": 1864,
"text": "Output:"
},
{
"code": null,
"e": 2128,
"s": 1872,
"text": "The original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]\nRequired List : [19]\n\nThe original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]\nRequired List : [10, 13, 5, 7]\n\nThe original list is : [3, 19, 4, 8, 10, 13, 5, 7, 2, 1, 4]\nRequired List : []"
},
{
"code": null,
"e": 2149,
"s": 2128,
"text": "Python list-programs"
},
{
"code": null,
"e": 2156,
"s": 2149,
"text": "Python"
},
{
"code": null,
"e": 2172,
"s": 2156,
"text": "Python Programs"
}
]
|
vector :: cbegin() and vector :: cend() in C++ STL | 09 Jun, 2022
Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container.
The function returns an iterator which is used to iterate container.
The iterator points to the beginning of the vector.
Iterator cannot modify the contents of the vector.
Syntax:
vectorname.cbegin()
Parameters: There is no parameter Return value: Constant random access iterator points to the beginning of the vector. Exception: No exception
Time Complexity – constant O(1)
Below program(s) illustrate the working of the function
CPP
// CPP program to illustrate// use of cbegin()#include <iostream>#include <string>#include <vector> using namespace std; int main(){ vector<string> vec; // 5 string are inserted vec.push_back("first"); vec.push_back("second"); vec.push_back("third"); vec.push_back("fourth"); vec.push_back("fifth"); // displaying the contents cout << "Contents of the vector:" << endl; for (auto itr = vec.cbegin(); itr != vec.end(); ++itr) cout << *itr << endl; return 0;}
Output:
Contents of the vector:
first
second
third
fourth
fifth
The function returns an iterator which is used to iterate container.
The iterator points to past-the-end element of the vector.
Iterator cannot modify the contents of the vector.
Syntax:
vectorname.cend()
Parameters: There is no parameter Return value: Constant random access iterator points to past-the-end element of the vector. Exception: No exception
Time Complexity – constant O(1)
Below program(s) illustrate the working of the function
CPP
// CPP programto illustrate// functioning of cend()#include <iostream>#include <string>#include <vector> using namespace std; int main(){ vector<string> vec; // 5 string are inserted vec.push_back("first"); vec.push_back("second"); vec.push_back("third"); vec.push_back("fourth"); vec.push_back("fifth"); // displaying the contents cout << "Contents of the vector:" << endl; for (auto itr = vec.cend() - 1; itr >= vec.begin(); --itr) cout << *itr << endl; return 0;}
Output:
Contents of the vector:
fifth
fourth
third
second
first
utkarshgupta110092
cpp-vector
C++
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 209,
"s": 52,
"text": "Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container."
},
{
"code": null,
"e": 278,
"s": 209,
"text": "The function returns an iterator which is used to iterate container."
},
{
"code": null,
"e": 330,
"s": 278,
"text": "The iterator points to the beginning of the vector."
},
{
"code": null,
"e": 381,
"s": 330,
"text": "Iterator cannot modify the contents of the vector."
},
{
"code": null,
"e": 389,
"s": 381,
"text": "Syntax:"
},
{
"code": null,
"e": 409,
"s": 389,
"text": "vectorname.cbegin()"
},
{
"code": null,
"e": 552,
"s": 409,
"text": "Parameters: There is no parameter Return value: Constant random access iterator points to the beginning of the vector. Exception: No exception"
},
{
"code": null,
"e": 584,
"s": 552,
"text": "Time Complexity – constant O(1)"
},
{
"code": null,
"e": 641,
"s": 584,
"text": "Below program(s) illustrate the working of the function "
},
{
"code": null,
"e": 645,
"s": 641,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// use of cbegin()#include <iostream>#include <string>#include <vector> using namespace std; int main(){ vector<string> vec; // 5 string are inserted vec.push_back(\"first\"); vec.push_back(\"second\"); vec.push_back(\"third\"); vec.push_back(\"fourth\"); vec.push_back(\"fifth\"); // displaying the contents cout << \"Contents of the vector:\" << endl; for (auto itr = vec.cbegin(); itr != vec.end(); ++itr) cout << *itr << endl; return 0;}",
"e": 1162,
"s": 645,
"text": null
},
{
"code": null,
"e": 1170,
"s": 1162,
"text": "Output:"
},
{
"code": null,
"e": 1226,
"s": 1170,
"text": "Contents of the vector:\nfirst\nsecond\nthird\nfourth\nfifth"
},
{
"code": null,
"e": 1295,
"s": 1226,
"text": "The function returns an iterator which is used to iterate container."
},
{
"code": null,
"e": 1354,
"s": 1295,
"text": "The iterator points to past-the-end element of the vector."
},
{
"code": null,
"e": 1405,
"s": 1354,
"text": "Iterator cannot modify the contents of the vector."
},
{
"code": null,
"e": 1413,
"s": 1405,
"text": "Syntax:"
},
{
"code": null,
"e": 1431,
"s": 1413,
"text": "vectorname.cend()"
},
{
"code": null,
"e": 1581,
"s": 1431,
"text": "Parameters: There is no parameter Return value: Constant random access iterator points to past-the-end element of the vector. Exception: No exception"
},
{
"code": null,
"e": 1613,
"s": 1581,
"text": "Time Complexity – constant O(1)"
},
{
"code": null,
"e": 1670,
"s": 1613,
"text": "Below program(s) illustrate the working of the function "
},
{
"code": null,
"e": 1674,
"s": 1670,
"text": "CPP"
},
{
"code": "// CPP programto illustrate// functioning of cend()#include <iostream>#include <string>#include <vector> using namespace std; int main(){ vector<string> vec; // 5 string are inserted vec.push_back(\"first\"); vec.push_back(\"second\"); vec.push_back(\"third\"); vec.push_back(\"fourth\"); vec.push_back(\"fifth\"); // displaying the contents cout << \"Contents of the vector:\" << endl; for (auto itr = vec.cend() - 1; itr >= vec.begin(); --itr) cout << *itr << endl; return 0;}",
"e": 2200,
"s": 1674,
"text": null
},
{
"code": null,
"e": 2208,
"s": 2200,
"text": "Output:"
},
{
"code": null,
"e": 2264,
"s": 2208,
"text": "Contents of the vector:\nfifth\nfourth\nthird\nsecond\nfirst"
},
{
"code": null,
"e": 2283,
"s": 2264,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 2294,
"s": 2283,
"text": "cpp-vector"
},
{
"code": null,
"e": 2298,
"s": 2294,
"text": "C++"
},
{
"code": null,
"e": 2317,
"s": 2298,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2321,
"s": 2317,
"text": "CPP"
},
{
"code": null,
"e": 2419,
"s": 2321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2443,
"s": 2419,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 2463,
"s": 2443,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 2488,
"s": 2463,
"text": "std::string class in C++"
},
{
"code": null,
"e": 2521,
"s": 2488,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 2565,
"s": 2521,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2610,
"s": 2565,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2658,
"s": 2610,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 2675,
"s": 2658,
"text": "std::find in C++"
},
{
"code": null,
"e": 2719,
"s": 2675,
"text": "List in C++ Standard Template Library (STL)"
}
]
|
Find the maximum amount that can be collected by selling movie tickets | 13 May, 2022
Given an integer N and an array seats[] where N is the number of people standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the ith row of the movie theater. The task is to find the maximum amount a theater owner can make by selling movie tickets to N people. Price of a ticket is equal to the maximum number of empty seats among all the rows.Example:
Input: seats[] = {1, 2, 4}, N = 3 Output: 9
4 + 3 + 2 = 9Input: seats[] = {2, 3, 5, 3}, N = 4 Output: 15
Approach: This problem can be solved by using a priority queue that will store the count of empty seats for every row and the maximum among them will be available at the top.
Create an empty priority_queue q and traverse the seats[] array and insert all element into the priority_queue.
Initialize two integer variable ticketSold = 0 and ans = 0 that will store the number of tickets sold and the total collection of the amount so far.
Now check while ticketSold < N and q.top() > 0 then remove the top element from the priority_queue and update ans by adding top element of the priority queue. Also store this top value in a variable temp and insert temp – 1 back to the priority_queue.
Repeat these steps until all the people have been sold the tickets and print the final result.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum amount// that can be collected by selling ticketsint maxAmount(int M, int N, int seats[]){ // Priority queue that stores // the count of empty seats priority_queue<int> q; // Insert each array element // into the priority queue for (int i = 0; i < M; i++) { q.push(seats[i]); } // To store the total // number of tickets sold int ticketSold = 0; // To store the total amount // of collection int ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while (ticketSold < N && q.top() > 0) { ans = ans + q.top(); int temp = q.top(); q.pop(); q.push(temp - 1); ticketSold++; } return ans;} // Driver codeint main(){ int seats[] = { 1, 2, 4 }; int M = sizeof(seats) / sizeof(int); int N = 3; cout << maxAmount(N, M, seats); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static int[] seats = new int[]{ 1, 2, 4 }; // Function to return the maximum amount // that can be collected by selling tickets public static int maxAmount(int M, int N) { // Priority queue that stores // the count of empty seats PriorityQueue<Integer> q = new PriorityQueue<Integer>(Collections.reverseOrder()); // Insert each array element // into the priority queue for (int i = 0; i < M; i++) { q.add(seats[i]); } // To store the total // number of tickets sold int ticketSold = 0; // To store the total amount // of collection int ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while (ticketSold < N && q.peek() > 0) { ans = ans + q.peek(); int temp = q.peek(); q.poll(); q.add(temp - 1); ticketSold++; } return ans; } // Driver code public static void main(String[] args) { int M = seats.length; int N = 3; System.out.print(maxAmount(M, N)); }} // This code is contributed by Sanjit_Prasad
# Python3 implementation of the approachimport heapq# Function to return the maximum amount# that can be collected by selling tickets def maxAmount(M, N, seats): # Priority queue that stores # the count of empty seats q = seats # for maintaining the property of max heap heapq._heapify_max(q) # To store the total # number of tickets sold ticketSold = 0 # To store the total amount # of collection ans = 0 # While tickets sold are less than N # and q[0] > 0 then update the collected # amount with the top of the priority # queue while ticketSold < N and q[0] > 0: # updating ans # with maximum number of tickets ans += q[0] q[0] -= 1 if q[0] == 0: break # for maintaining the property of max heap heapq._heapify_max(q) ticketSold += 1 return ans # Driver Codeseats = [1, 2, 4]M = len(seats)N = 3print(maxAmount(M, N, seats)) '''Code is written by Rajat Kumar (GLAU)'''
// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to return the maximum amount // that can be collected by selling tickets static int maxAmount(int M, int N, int[] seats) { // Priority queue that stores // the count of empty seats List<int> q = new List<int>(); // Insert each array element // into the priority queue for (int i = 0; i < M; i++) { q.Add(seats[i]); } q.Sort(); q.Reverse(); // To store the total // number of tickets sold int ticketSold = 0; // To store the total amount // of collection int ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while (ticketSold < N && q[0] > 0) { ans = ans + q[0]; int temp = q[0]; q.RemoveAt(0); q.Add(temp - 1); q.Sort(); q.Reverse(); ticketSold++; } return ans; } // Driver code static void Main() { int[] seats = { 1, 2, 4 }; int M = seats.Length; int N = 3; Console.WriteLine(maxAmount(N, M, seats)); }} // This code is contributed by divyesh072019.
<script> // Javascript implementation of the approach // Function to return the maximum amount // that can be collected by selling tickets function maxAmount(M, N, seats) { // Priority queue that stores // the count of empty seats let q = []; // Insert each array element // into the priority queue for (let i = 0; i < M; i++) { q.push(seats[i]); } q.sort(function(a, b){return a - b}); q.reverse(); // To store the total // number of tickets sold let ticketSold = 0; // To store the total amount // of collection let ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while ((ticketSold < N) && (q[0] > 0)) { ans = ans + q[0]; let temp = q[0]; q.shift(); q.push(temp - 1); q.sort(function(a, b){return a - b}); q.reverse(); ticketSold++; } return ans; } let seats = [ 1, 2, 4 ]; let M = seats.length; let N = 3; document.write(maxAmount(N, M, seats)); </script>
9
Time Complexity: O(N*logM) where N is tickets to be sold.
Explanation: In the condition of the while loop: ticketSold < N and q.top() >0, Value of N is determining the time required and here we need to maintain heap every time that needs O(Log(M))....so overall complexity will be O(N* Log(m)) where M is the size of given array.
Auxiliary Space: O(M) to store heap q.
Sanjit_Prasad
SURENDRA_GANGWAR
divyesh072019
mukesh07
rohan07
rajatkumargla19
priority-queue
Advanced Data Structure
Arrays
Competitive Programming
Heap
Arrays
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 441,
"s": 54,
"text": "Given an integer N and an array seats[] where N is the number of people standing in a line to buy a movie ticket and seat[i] is the number of empty seats in the ith row of the movie theater. The task is to find the maximum amount a theater owner can make by selling movie tickets to N people. Price of a ticket is equal to the maximum number of empty seats among all the rows.Example: "
},
{
"code": null,
"e": 487,
"s": 441,
"text": "Input: seats[] = {1, 2, 4}, N = 3 Output: 9 "
},
{
"code": null,
"e": 550,
"s": 487,
"text": "4 + 3 + 2 = 9Input: seats[] = {2, 3, 5, 3}, N = 4 Output: 15 "
},
{
"code": null,
"e": 729,
"s": 552,
"text": "Approach: This problem can be solved by using a priority queue that will store the count of empty seats for every row and the maximum among them will be available at the top. "
},
{
"code": null,
"e": 841,
"s": 729,
"text": "Create an empty priority_queue q and traverse the seats[] array and insert all element into the priority_queue."
},
{
"code": null,
"e": 990,
"s": 841,
"text": "Initialize two integer variable ticketSold = 0 and ans = 0 that will store the number of tickets sold and the total collection of the amount so far."
},
{
"code": null,
"e": 1242,
"s": 990,
"text": "Now check while ticketSold < N and q.top() > 0 then remove the top element from the priority_queue and update ans by adding top element of the priority queue. Also store this top value in a variable temp and insert temp – 1 back to the priority_queue."
},
{
"code": null,
"e": 1337,
"s": 1242,
"text": "Repeat these steps until all the people have been sold the tickets and print the final result."
},
{
"code": null,
"e": 1389,
"s": 1337,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1393,
"s": 1389,
"text": "C++"
},
{
"code": null,
"e": 1398,
"s": 1393,
"text": "Java"
},
{
"code": null,
"e": 1407,
"s": 1398,
"text": "Python 3"
},
{
"code": null,
"e": 1410,
"s": 1407,
"text": "C#"
},
{
"code": null,
"e": 1421,
"s": 1410,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum amount// that can be collected by selling ticketsint maxAmount(int M, int N, int seats[]){ // Priority queue that stores // the count of empty seats priority_queue<int> q; // Insert each array element // into the priority queue for (int i = 0; i < M; i++) { q.push(seats[i]); } // To store the total // number of tickets sold int ticketSold = 0; // To store the total amount // of collection int ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while (ticketSold < N && q.top() > 0) { ans = ans + q.top(); int temp = q.top(); q.pop(); q.push(temp - 1); ticketSold++; } return ans;} // Driver codeint main(){ int seats[] = { 1, 2, 4 }; int M = sizeof(seats) / sizeof(int); int N = 3; cout << maxAmount(N, M, seats); return 0;}",
"e": 2478,
"s": 1421,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static int[] seats = new int[]{ 1, 2, 4 }; // Function to return the maximum amount // that can be collected by selling tickets public static int maxAmount(int M, int N) { // Priority queue that stores // the count of empty seats PriorityQueue<Integer> q = new PriorityQueue<Integer>(Collections.reverseOrder()); // Insert each array element // into the priority queue for (int i = 0; i < M; i++) { q.add(seats[i]); } // To store the total // number of tickets sold int ticketSold = 0; // To store the total amount // of collection int ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while (ticketSold < N && q.peek() > 0) { ans = ans + q.peek(); int temp = q.peek(); q.poll(); q.add(temp - 1); ticketSold++; } return ans; } // Driver code public static void main(String[] args) { int M = seats.length; int N = 3; System.out.print(maxAmount(M, N)); }} // This code is contributed by Sanjit_Prasad",
"e": 3844,
"s": 2478,
"text": null
},
{
"code": "# Python3 implementation of the approachimport heapq# Function to return the maximum amount# that can be collected by selling tickets def maxAmount(M, N, seats): # Priority queue that stores # the count of empty seats q = seats # for maintaining the property of max heap heapq._heapify_max(q) # To store the total # number of tickets sold ticketSold = 0 # To store the total amount # of collection ans = 0 # While tickets sold are less than N # and q[0] > 0 then update the collected # amount with the top of the priority # queue while ticketSold < N and q[0] > 0: # updating ans # with maximum number of tickets ans += q[0] q[0] -= 1 if q[0] == 0: break # for maintaining the property of max heap heapq._heapify_max(q) ticketSold += 1 return ans # Driver Codeseats = [1, 2, 4]M = len(seats)N = 3print(maxAmount(M, N, seats)) '''Code is written by Rajat Kumar (GLAU)'''",
"e": 4834,
"s": 3844,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic;class GFG{ // Function to return the maximum amount // that can be collected by selling tickets static int maxAmount(int M, int N, int[] seats) { // Priority queue that stores // the count of empty seats List<int> q = new List<int>(); // Insert each array element // into the priority queue for (int i = 0; i < M; i++) { q.Add(seats[i]); } q.Sort(); q.Reverse(); // To store the total // number of tickets sold int ticketSold = 0; // To store the total amount // of collection int ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while (ticketSold < N && q[0] > 0) { ans = ans + q[0]; int temp = q[0]; q.RemoveAt(0); q.Add(temp - 1); q.Sort(); q.Reverse(); ticketSold++; } return ans; } // Driver code static void Main() { int[] seats = { 1, 2, 4 }; int M = seats.Length; int N = 3; Console.WriteLine(maxAmount(N, M, seats)); }} // This code is contributed by divyesh072019.",
"e": 6206,
"s": 4834,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the maximum amount // that can be collected by selling tickets function maxAmount(M, N, seats) { // Priority queue that stores // the count of empty seats let q = []; // Insert each array element // into the priority queue for (let i = 0; i < M; i++) { q.push(seats[i]); } q.sort(function(a, b){return a - b}); q.reverse(); // To store the total // number of tickets sold let ticketSold = 0; // To store the total amount // of collection let ans = 0; // While tickets sold are less than N // and q.top > 0 then update the collected // amount with the top of the priority // queue while ((ticketSold < N) && (q[0] > 0)) { ans = ans + q[0]; let temp = q[0]; q.shift(); q.push(temp - 1); q.sort(function(a, b){return a - b}); q.reverse(); ticketSold++; } return ans; } let seats = [ 1, 2, 4 ]; let M = seats.length; let N = 3; document.write(maxAmount(N, M, seats)); </script>",
"e": 7499,
"s": 6206,
"text": null
},
{
"code": null,
"e": 7501,
"s": 7499,
"text": "9"
},
{
"code": null,
"e": 7561,
"s": 7503,
"text": "Time Complexity: O(N*logM) where N is tickets to be sold."
},
{
"code": null,
"e": 7834,
"s": 7561,
"text": "Explanation: In the condition of the while loop: ticketSold < N and q.top() >0, Value of N is determining the time required and here we need to maintain heap every time that needs O(Log(M))....so overall complexity will be O(N* Log(m)) where M is the size of given array."
},
{
"code": null,
"e": 7873,
"s": 7834,
"text": "Auxiliary Space: O(M) to store heap q."
},
{
"code": null,
"e": 7887,
"s": 7873,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 7904,
"s": 7887,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 7918,
"s": 7904,
"text": "divyesh072019"
},
{
"code": null,
"e": 7927,
"s": 7918,
"text": "mukesh07"
},
{
"code": null,
"e": 7935,
"s": 7927,
"text": "rohan07"
},
{
"code": null,
"e": 7951,
"s": 7935,
"text": "rajatkumargla19"
},
{
"code": null,
"e": 7966,
"s": 7951,
"text": "priority-queue"
},
{
"code": null,
"e": 7990,
"s": 7966,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 7997,
"s": 7990,
"text": "Arrays"
},
{
"code": null,
"e": 8021,
"s": 7997,
"text": "Competitive Programming"
},
{
"code": null,
"e": 8026,
"s": 8021,
"text": "Heap"
},
{
"code": null,
"e": 8033,
"s": 8026,
"text": "Arrays"
},
{
"code": null,
"e": 8038,
"s": 8033,
"text": "Heap"
},
{
"code": null,
"e": 8053,
"s": 8038,
"text": "priority-queue"
}
]
|
Find smallest range containing elements from k lists | 01 Jul, 2022
Given k sorted lists of integers of size n each, find the smallest range that includes at least one element from each of the k lists. If more than one smallest range is found, print any one of them.
Example:
Input: K = 3
arr1[] : [4, 7, 9, 12, 15]
arr2[] : [0, 8, 10, 14, 20]
arr3[] : [6, 12, 16, 30, 50]
Output:
The smallest range is [6 8]
Explanation: Smallest range is formed by
number 7 from the first list, 8 from second
list and 6 from the third list.
Input: k = 3
arr1[] : [4, 7]
arr2[] : [1, 2]
arr3[] : [20, 40]
Output:
The smallest range is [2 20]
Explanation:The range [2, 20] contains 2, 4, 7, 20
which contains element from all the three arrays.
Naive Approach: Given K sorted list, find a range where there is at least one element from every list. The idea to solve the problem is very simple, keep k pointers which will constitute the elements in the range, by taking the min and max of the k elements the range can be formed. Initially, all the pointers will point to the start of all the k arrays. Store the range max to min. If the range has to be minimized then either the minimum value has to be increased or the maximum value has to be decreased. To decrease the maximum value we have to move our pointer of current maximum to the left and since we are currently at 0 the index of every list so we can’t move our pointer to left, hence we can’t decrease the current max. So, the only possible option to get a better range is to increase the current minimum. To continue increasing the minimum value, increase the pointer of the list containing the minimum value and update the range until one of the lists exhausts.
Algorithm: Create an extra space ptr of length k to store the pointers and a variable minrange initialized to a maximum value.Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range.Repeat the following steps until at least one list exhausts: Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element.
Create an extra space ptr of length k to store the pointers and a variable minrange initialized to a maximum value.Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range.Repeat the following steps until at least one list exhausts: Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element.
Create an extra space ptr of length k to store the pointers and a variable minrange initialized to a maximum value.
Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range.
Repeat the following steps until at least one list exhausts: Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element.
Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element.
Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.
Now update the minrange if current (max-min) is less than minrange.
increment the pointer pointing to current minimum element.
Implementation:
C++
Java
Python
C#
Javascript
// C++ program to finds out smallest range that includes// elements from each of the given sorted lists.#include <bits/stdc++.h> using namespace std; #define N 5 // array for storing the current index of list iint ptr[501]; // This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.void findSmallestRange(int arr[][N], int n, int k){ int i, minval, maxval, minrange, minel, maxel, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) ptr[i] = 0; minrange = INT_MAX; while (1) { // for maintaining the index of list containing the minimum element minind = -1; minval = INT_MAX; maxval = INT_MIN; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better answer, so break the while loop if (flag) break; ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } printf("The smallest range is [%d, %d]\n", minel, maxel);} // Driver program to test above functionint main(){ int arr[][N] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = sizeof(arr) / sizeof(arr[0]); findSmallestRange(arr, N, k); return 0;}// This code is contributed by Aditya Krishna Namdeo
// Java program to finds out smallest range that includes// elements from each of the given sorted lists.class GFG { static final int N = 5; // array for storing the current index of list i static int ptr[] = new int[501]; // This function takes an k sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists. static void findSmallestRange(int arr[][], int n, int k) { int i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) { ptr[i] = 0; } minrange = Integer.MAX_VALUE; while (true) { // for maintaining the index of list containing the minimum element minind = -1; minval = Integer.MAX_VALUE; maxval = Integer.MIN_VALUE; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better answer, so break the while loop if (flag == 1) { break; } ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } System.out.printf("The smallest range is [%d, %d]\n", minel, maxel); } // Driver program to test above function public static void main(String[] args) { int arr[][] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.length; findSmallestRange(arr, N, k); }}// this code contributed by Rajput-Ji
# Python3 program to finds out# smallest range that includes# elements from each of the# given sorted lists. N = 5 # array for storing the# current index of list iptr = [0 for i in range(501)] # This function takes an k sorted# lists in the form of 2D array as# an argument. It finds out smallest# range that includes elements from# each of the k lists.def findSmallestRange(arr, n, k): i, minval, maxval, minrange, minel, maxel, flag, minind = 0, 0, 0, 0, 0, 0, 0, 0 # initializing to 0 index for i in range(k + 1): ptr[i] = 0 minrange = 10**9 while(1): # for maintaining the index of list # containing the minimum element minind = -1 minval = 10**9 maxval = -10**9 flag = 0 # iterating over all the list for i in range(k): # if every element of list[i] is # traversed then break the loop if(ptr[i] == n): flag = 1 break # find minimum value among all the list # elements pointing by the ptr[] array if(ptr[i] < n and arr[i][ptr[i]] < minval): minind = i # update the index of the list minval = arr[i][ptr[i]] # find maximum value among all the # list elements pointing by the ptr[] array if(ptr[i] < n and arr[i][ptr[i]] > maxval): maxval = arr[i][ptr[i]] # if any list exhaust we will # not get any better answer, # so break the while loop if(flag): break ptr[minind] += 1 # updating the minrange if((maxval-minval) < minrange): minel = minval maxel = maxval minrange = maxel - minel print("The smallest range is [", minel, maxel, "]") # Driver codearr = [ [4, 7, 9, 12, 15], [0, 8, 10, 14, 20], [6, 12, 16, 30, 50] ] k = len(arr) findSmallestRange(arr, N, k) # This code is contributed by mohit kumar
// C# program to finds out smallest// range that includes elements from// each of the given sorted lists.using System; class GFG { static int N = 5; // array for storing the current index of list i static int[] ptr = new int[501]; // This function takes an k sorted // lists in the form of 2D array as // an argument. It finds out smallest range // that includes elements from each of the k lists. static void findSmallestRange(int[, ] arr, int n, int k) { int i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) { ptr[i] = 0; } minrange = int.MaxValue; while (true) { // for maintaining the index of // list containing the minimum element minind = -1; minval = int.MaxValue; maxval = int.MinValue; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] // is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the // list elements pointing by the ptr[] array if (ptr[i] < n && arr[i, ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i, ptr[i]]; } // find maximum value among all the // list elements pointing by the ptr[] array if (ptr[i] < n && arr[i, ptr[i]] > maxval) { maxval = arr[i, ptr[i]]; } } // if any list exhaust we will // not get any better answer, // so break the while loop if (flag == 1) { break; } ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } Console.WriteLine("The smallest range is" + "[{0}, {1}]\n", minel, maxel); } // Driver code public static void Main(String[] args) { int[, ] arr = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.GetLength(0); findSmallestRange(arr, N, k); }} // This code has been contributed by 29AjayKumar
<script> // Javascript program to finds out smallest range that includes// elements from each of the given sorted lists.let N = 5; // array for storing the current index of list ilet ptr=new Array(501); // This function takes an k sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists.function findSmallestRange(arr,n,k){ let i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) { ptr[i] = 0; } minrange = Number.MAX_VALUE; while (true) { // for maintaining the index of list containing the minimum element minind = -1; minval = Number.MAX_VALUE; maxval = Number.MIN_VALUE; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better answer, so break the while loop if (flag == 1) { break; } ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } document.write("The smallest range is ["+minel+", "+maxel+"]<br>");} // Driver program to test above functionlet arr = [ [4, 7, 9, 12, 15], [0, 8, 10, 14, 20], [6, 12, 16, 30, 50] ]let k = arr.length;findSmallestRange(arr, N, k); // This code is contributed by unknown2108 </script>
The smallest range is [6, 8]
Complexity Analysis: Time complexity : O(n * k2), to find the maximum and minimum in an array of length k the time required is O(k), and to traverse all the k arrays of length n (in worst case), the time complexity is O(n*k), then the total time complexity is O(n*k2).Space complexity: O(k), an extra array is required of length k so the space complexity is O(k)
Time complexity : O(n * k2), to find the maximum and minimum in an array of length k the time required is O(k), and to traverse all the k arrays of length n (in worst case), the time complexity is O(n*k), then the total time complexity is O(n*k2).
Space complexity: O(k), an extra array is required of length k so the space complexity is O(k)
Efficient approach: The approach remains the same but the time complexity can be reduced by using min-heap or priority queue. Min heap can be used to find the maximum and minimum value in logarithmic time or log k time instead of linear time. Rest of the approach remains the same.
Algorithm: create a Min heap to store k elements, one from each array and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer.Initially put the first element of each element from each list and store the maximum value in max.Repeat the following steps until at least one list exhausts : To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted.
create a Min heap to store k elements, one from each array and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer.Initially put the first element of each element from each list and store the maximum value in max.Repeat the following steps until at least one list exhausts : To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted.
create a Min heap to store k elements, one from each array and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer.
Initially put the first element of each element from each list and store the maximum value in max.
Repeat the following steps until at least one list exhausts : To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted.
To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted.
To find the minimum value or min, use the top or root of the Min heap which is the minimum element.
Now update the minrange if current (max-min) is less than minrange.
remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted.
Implementation:
C++
Java
C#
Javascript
// C++ program to finds out smallest range that includes// elements from each of the given sorted lists.#include <bits/stdc++.h>using namespace std; #define N 5 // A min heap nodestruct MinHeapNode { // The element to be stored int element; // index of the list from which the element is taken int i; // index of the next element to be picked from list int j;}; // Prototype of a utility function to swap two min heap nodesvoid swap(MinHeapNode* x, MinHeapNode* y); // A class for Min Heapclass MinHeap { // pointer to array of elements in heap MinHeapNode* harr; // size of min heap int heap_size; public: // Constructor: creates a min heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with root at given index void MinHeapify(int); // to get index of left child of node at index i int left(int i) { return (2 * i + 1); } // to get index of right child of node at index i int right(int i) { return (2 * i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node x and heapify() new root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); }}; // Constructor: Builds a heap from a// given array a[] of given sizeMinHeap::MinHeap(MinHeapNode a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; }} // A recursive method to heapify a subtree with root at// given index. This method assumes that the subtrees// are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); }} // This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.void findSmallestRange(int arr[][N], int k){ // Create a min heap with k heap nodes. Every heap node // has first element of an list int range = INT_MAX; int min = INT_MAX, max = INT_MIN; int start, end; MinHeapNode* harr = new MinHeapNode[k]; for (int i = 0; i < k; i++) { // Store the first element harr[i].element = arr[i][0]; // index of list harr[i].i = i; // Index of next element to be stored // from list harr[i].j = 1; // store max element if (harr[i].element > max) max = harr[i].element; } // Create the heap MinHeap hp(harr, k); // Now one by one get the minimum element from min // heap and replace it with next element of its list while (1) { // Get the minimum element and store it in output MinHeapNode root = hp.getMin(); // update min min = hp.getMin().element; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will replace current // root of heap. The next element belongs to same // list as the current root. if (root.j < N) { root.element = arr[root.i][root.j]; root.j += 1; // update max element if (root.element > max) max = root.element; } // break if we have reached end of any list else break; // Replace root with next element of list hp.replaceMin(root); } cout << "The smallest range is " << "[" << start << " " << end << "]" << endl; ;} // Driver program to test above functionsint main(){ int arr[][N] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = sizeof(arr) / sizeof(arr[0]); findSmallestRange(arr, k); return 0;}
// Java program to find out smallest// range that includes elements from// each of the given sorted lists.class GFG { // A min heap node static class Node { // The element to be stored int ele; // index of the list from which // the element is taken int i; // index of the next element // to be picked from list int j; Node(int a, int b, int c) { this.ele = a; this.i = b; this.j = c; } } // A class for Min Heap static class MinHeap { Node[] harr; // array of elements in heap int size; // size of min heap // Constructor: creates a min heap // of given size MinHeap(Node[] arr, int size) { this.harr = arr; this.size = size; int i = (size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; } } // to get index of left child // of node at index i int left(int i) { return 2 * i + 1; } // to get index of right child // of node at index i int right(int i) { return 2 * i + 2; } // to heapify a subtree with // root at given index void MinHeapify(int i) { int l = left(i); int r = right(i); int small = i; if (l < size && harr[l].ele < harr[i].ele) small = l; if (r < size && harr[r].ele < harr[small].ele) small = r; if (small != i) { swap(small, i); MinHeapify(small); } } void swap(int i, int j) { Node temp = harr[i]; harr[i] = harr[j]; harr[j] = temp; } // to get the root Node getMin() { return harr[0]; } // to replace root with new node x // and heapify() new root void replaceMin(Node x) { harr[0] = x; MinHeapify(0); } } // This function takes an k sorted lists // in the form of 2D array as an argument. // It finds out smallest range that includes // elements from each of the k lists. static void findSmallestRange(int[][] arr, int k) { int range = Integer.MAX_VALUE; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int start = -1, end = -1; int n = arr[0].length; // Create a min heap with k heap nodes. // Every heap node has first element of an list Node[] arr1 = new Node[k]; for (int i = 0; i < k; i++) { Node node = new Node(arr[i][0], i, 1); arr1[i] = node; // store max element max = Math.max(max, node.ele); } // Create the heap MinHeap mh = new MinHeap(arr1, k); // Now one by one get the minimum element // from min heap and replace it with // next element of its list while (true) { // Get the minimum element and // store it in output Node root = mh.getMin(); // update min min = root.ele; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will // replace current root of heap. // The next element belongs to same // list as the current root. if (root.j < n) { root.ele = arr[root.i][root.j]; root.j++; // update max element if (root.ele > max) max = root.ele; } // break if we have reached // end of any list else break; // Replace root with next element of list mh.replaceMin(root); } System.out.print("The smallest range is [" + start + " " + end + "]"); } // Driver Code public static void main(String[] args) { int arr[][] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.length; findSmallestRange(arr, k); }} // This code is contributed by nobody_cares
// C# program to find out smallest// range that includes elements from// each of the given sorted lists.using System;using System.Collections.Generic; class GFG { // A min heap node public class Node { // The element to be stored public int ele; // index of the list from which // the element is taken public int i; // index of the next element // to be picked from list public int j; public Node(int a, int b, int c) { this.ele = a; this.i = b; this.j = c; } } // A class for Min Heap public class MinHeap { // array of elements in heap public Node[] harr; // size of min heap public int size; // Constructor: creates a min heap // of given size public MinHeap(Node[] arr, int size) { this.harr = arr; this.size = size; int i = (size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; } } // to get index of left child // of node at index i int left(int i) { return 2 * i + 1; } // to get index of right child // of node at index i int right(int i) { return 2 * i + 2; } // to heapify a subtree with // root at given index void MinHeapify(int i) { int l = left(i); int r = right(i); int small = i; if (l < size && harr[l].ele < harr[i].ele) small = l; if (r < size && harr[r].ele < harr[small].ele) small = r; if (small != i) { swap(small, i); MinHeapify(small); } } void swap(int i, int j) { Node temp = harr[i]; harr[i] = harr[j]; harr[j] = temp; } // to get the root public Node getMin() { return harr[0]; } // to replace root with new node x // and heapify() new root public void replaceMin(Node x) { harr[0] = x; MinHeapify(0); } } // This function takes an k sorted lists // in the form of 2D array as an argument. // It finds out smallest range that includes // elements from each of the k lists. static void findSmallestRange(int[, ] arr, int k) { int range = int.MaxValue; int min = int.MaxValue; int max = int.MinValue; int start = -1, end = -1; int n = arr.GetLength(0); // Create a min heap with k heap nodes. // Every heap node has first element of an list Node[] arr1 = new Node[k]; for (int i = 0; i < k; i++) { Node node = new Node(arr[i, 0], i, 1); arr1[i] = node; // store max element max = Math.Max(max, node.ele); } // Create the heap MinHeap mh = new MinHeap(arr1, k); // Now one by one get the minimum element // from min heap and replace it with // next element of its list while (true) { // Get the minimum element and // store it in output Node root = mh.getMin(); // update min min = root.ele; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will // replace current root of heap. // The next element belongs to same // list as the current root. if (root.j < n) { root.ele = arr[root.i, root.j]; root.j++; // update max element if (root.ele > max) max = root.ele; } else break; // break if we have reached // end of any list // Replace root with next element of list mh.replaceMin(root); } Console.Write("The smallest range is [" + start + " " + end + "]"); } // Driver Code public static void Main(String[] args) { int[, ] arr = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.GetLength(0); findSmallestRange(arr, k); }} // This code is contributed by Rajput-Ji
<script> // Javascript program to find out smallest// range that includes elements from// each of the given sorted lists.class Node{ constructor(a, b, c) { this.ele = a; this.i = b; this.j = c; }} // A class for Min Heapclass MinHeap{ // Array of elements in heap harr; // Size of min heap size; // Constructor: creates a min heap // of given size constructor(arr,size) { this.harr = arr; this.size = size; let i = Math.floor((size - 1) / 2); while (i >= 0) { this.MinHeapify(i); i--; } } // To get index of left child // of node at index i left(i) { return 2 * i + 1; } // To get index of right child // of node at index i right(i) { return 2 * i + 2; } // To heapify a subtree with // root at given index MinHeapify(i) { let l = this.left(i); let r = this.right(i); let small = i; if (l < this.size && this.harr[l].ele < this.harr[i].ele) small = l; if (r < this.size && this.harr[r].ele < this.harr[small].ele) small = r; if (small != i) { this.swap(small, i); this.MinHeapify(small); } } swap(i, j) { let temp = this.harr[i]; this.harr[i] = this.harr[j]; this.harr[j] = temp; } // To get the root getMin() { return this.harr[0]; } // To replace root with new node x // and heapify() new root replaceMin(x) { this.harr[0] = x; this.MinHeapify(0); } } // This function takes an k sorted lists// in the form of 2D array as an argument.// It finds out smallest range that includes// elements from each of the k lists.function findSmallestRange(arr, k){ let range = Number.MAX_VALUE; let min = Number.MAX_VALUE; let max = Number.MIN_VALUE; let start = -1, end = -1; let n = arr[0].length; // Create a min heap with k heap nodes. // Every heap node has first element of an list let arr1 = new Array(k); for(let i = 0; i < k; i++) { let node = new Node(arr[i][0], i, 1); arr1[i] = node; // Store max element max = Math.max(max, node.ele); } // Create the heap let mh = new MinHeap(arr1, k); // Now one by one get the minimum element // from min heap and replace it with // next element of its list while (true) { // Get the minimum element and // store it in output let root = mh.getMin(); // Update min min = root.ele; // Update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will // replace current root of heap. // The next element belongs to same // list as the current root. if (root.j < n) { root.ele = arr[root.i][root.j]; root.j++; // Update max element if (root.ele > max) max = root.ele; } // Break if we have reached // end of any list else break; // Replace root with next element of list mh.replaceMin(root); } document.write("The smallest range is [" + start + " " + end + "]");} // Driver Codelet arr = [ [ 4, 7, 9, 12, 15 ], [ 0, 8, 10, 14, 20 ], [ 6, 12, 16, 30, 50 ] ];let k = arr.length; findSmallestRange(arr, k); // This code is contributed by rag2127 </script>
The smallest range is [6 8]
Complexity Analysis: Time complexity : O(n * k *log k). To find the maximum and minimum in a Min Heap of length k the time required is O(log k), and to traverse all the k arrays of length n (in the worst case), the time complexity is O(n*k), then the total time complexity is O(n * k *log k).Space complexity: O(k). The priority queue will store k elements so the space complexity of O(k)
Time complexity : O(n * k *log k). To find the maximum and minimum in a Min Heap of length k the time required is O(log k), and to traverse all the k arrays of length n (in the worst case), the time complexity is O(n*k), then the total time complexity is O(n * k *log k).
Space complexity: O(k). The priority queue will store k elements so the space complexity of O(k)
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Rajput-Ji
mohit kumar 29
29AjayKumar
nobody_cares
andrew1234
unknown2108
arorakashish0911
rag2127
surindertarika1234
rkbhola5
debayanbiswas31
hardikkoriintern
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Longest Consecutive Subsequence
What is Hashing | A Complete Tutorial
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Longest Consecutive Subsequence
Count pairs with given sum | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Jul, 2022"
},
{
"code": null,
"e": 251,
"s": 52,
"text": "Given k sorted lists of integers of size n each, find the smallest range that includes at least one element from each of the k lists. If more than one smallest range is found, print any one of them."
},
{
"code": null,
"e": 261,
"s": 251,
"text": "Example: "
},
{
"code": null,
"e": 716,
"s": 261,
"text": "Input: K = 3\narr1[] : [4, 7, 9, 12, 15]\narr2[] : [0, 8, 10, 14, 20]\narr3[] : [6, 12, 16, 30, 50]\nOutput:\nThe smallest range is [6 8]\n\nExplanation: Smallest range is formed by \nnumber 7 from the first list, 8 from second\nlist and 6 from the third list.\n\nInput: k = 3\narr1[] : [4, 7]\narr2[] : [1, 2]\narr3[] : [20, 40]\nOutput:\nThe smallest range is [2 20]\n\nExplanation:The range [2, 20] contains 2, 4, 7, 20\nwhich contains element from all the three arrays."
},
{
"code": null,
"e": 1694,
"s": 716,
"text": "Naive Approach: Given K sorted list, find a range where there is at least one element from every list. The idea to solve the problem is very simple, keep k pointers which will constitute the elements in the range, by taking the min and max of the k elements the range can be formed. Initially, all the pointers will point to the start of all the k arrays. Store the range max to min. If the range has to be minimized then either the minimum value has to be increased or the maximum value has to be decreased. To decrease the maximum value we have to move our pointer of current maximum to the left and since we are currently at 0 the index of every list so we can’t move our pointer to left, hence we can’t decrease the current max. So, the only possible option to get a better range is to increase the current minimum. To continue increasing the minimum value, increase the pointer of the list containing the minimum value and update the range until one of the lists exhausts."
},
{
"code": null,
"e": 2279,
"s": 1694,
"text": "Algorithm: Create an extra space ptr of length k to store the pointers and a variable minrange initialized to a maximum value.Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range.Repeat the following steps until at least one list exhausts: Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element."
},
{
"code": null,
"e": 2853,
"s": 2279,
"text": "Create an extra space ptr of length k to store the pointers and a variable minrange initialized to a maximum value.Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range.Repeat the following steps until at least one list exhausts: Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element."
},
{
"code": null,
"e": 2969,
"s": 2853,
"text": "Create an extra space ptr of length k to store the pointers and a variable minrange initialized to a maximum value."
},
{
"code": null,
"e": 3128,
"s": 2969,
"text": "Initially the index of every list is 0, therefore initialize every element of ptr[0..k] to 0, the array ptr will store the index of the elements in the range."
},
{
"code": null,
"e": 3429,
"s": 3128,
"text": "Repeat the following steps until at least one list exhausts: Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element."
},
{
"code": null,
"e": 3669,
"s": 3429,
"text": "Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array.Now update the minrange if current (max-min) is less than minrange.increment the pointer pointing to current minimum element."
},
{
"code": null,
"e": 3784,
"s": 3669,
"text": "Now find the minimum and maximum value among the current elements of all the list pointed by the ptr[0...k] array."
},
{
"code": null,
"e": 3852,
"s": 3784,
"text": "Now update the minrange if current (max-min) is less than minrange."
},
{
"code": null,
"e": 3911,
"s": 3852,
"text": "increment the pointer pointing to current minimum element."
},
{
"code": null,
"e": 3927,
"s": 3911,
"text": "Implementation:"
},
{
"code": null,
"e": 3931,
"s": 3927,
"text": "C++"
},
{
"code": null,
"e": 3936,
"s": 3931,
"text": "Java"
},
{
"code": null,
"e": 3943,
"s": 3936,
"text": "Python"
},
{
"code": null,
"e": 3946,
"s": 3943,
"text": "C#"
},
{
"code": null,
"e": 3957,
"s": 3946,
"text": "Javascript"
},
{
"code": "// C++ program to finds out smallest range that includes// elements from each of the given sorted lists.#include <bits/stdc++.h> using namespace std; #define N 5 // array for storing the current index of list iint ptr[501]; // This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.void findSmallestRange(int arr[][N], int n, int k){ int i, minval, maxval, minrange, minel, maxel, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) ptr[i] = 0; minrange = INT_MAX; while (1) { // for maintaining the index of list containing the minimum element minind = -1; minval = INT_MAX; maxval = INT_MIN; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better answer, so break the while loop if (flag) break; ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } printf(\"The smallest range is [%d, %d]\\n\", minel, maxel);} // Driver program to test above functionint main(){ int arr[][N] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = sizeof(arr) / sizeof(arr[0]); findSmallestRange(arr, N, k); return 0;}// This code is contributed by Aditya Krishna Namdeo",
"e": 6139,
"s": 3957,
"text": null
},
{
"code": "// Java program to finds out smallest range that includes// elements from each of the given sorted lists.class GFG { static final int N = 5; // array for storing the current index of list i static int ptr[] = new int[501]; // This function takes an k sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists. static void findSmallestRange(int arr[][], int n, int k) { int i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) { ptr[i] = 0; } minrange = Integer.MAX_VALUE; while (true) { // for maintaining the index of list containing the minimum element minind = -1; minval = Integer.MAX_VALUE; maxval = Integer.MIN_VALUE; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better answer, so break the while loop if (flag == 1) { break; } ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } System.out.printf(\"The smallest range is [%d, %d]\\n\", minel, maxel); } // Driver program to test above function public static void main(String[] args) { int arr[][] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.length; findSmallestRange(arr, N, k); }}// this code contributed by Rajput-Ji",
"e": 8629,
"s": 6139,
"text": null
},
{
"code": "# Python3 program to finds out# smallest range that includes# elements from each of the# given sorted lists. N = 5 # array for storing the# current index of list iptr = [0 for i in range(501)] # This function takes an k sorted# lists in the form of 2D array as# an argument. It finds out smallest# range that includes elements from# each of the k lists.def findSmallestRange(arr, n, k): i, minval, maxval, minrange, minel, maxel, flag, minind = 0, 0, 0, 0, 0, 0, 0, 0 # initializing to 0 index for i in range(k + 1): ptr[i] = 0 minrange = 10**9 while(1): # for maintaining the index of list # containing the minimum element minind = -1 minval = 10**9 maxval = -10**9 flag = 0 # iterating over all the list for i in range(k): # if every element of list[i] is # traversed then break the loop if(ptr[i] == n): flag = 1 break # find minimum value among all the list # elements pointing by the ptr[] array if(ptr[i] < n and arr[i][ptr[i]] < minval): minind = i # update the index of the list minval = arr[i][ptr[i]] # find maximum value among all the # list elements pointing by the ptr[] array if(ptr[i] < n and arr[i][ptr[i]] > maxval): maxval = arr[i][ptr[i]] # if any list exhaust we will # not get any better answer, # so break the while loop if(flag): break ptr[minind] += 1 # updating the minrange if((maxval-minval) < minrange): minel = minval maxel = maxval minrange = maxel - minel print(\"The smallest range is [\", minel, maxel, \"]\") # Driver codearr = [ [4, 7, 9, 12, 15], [0, 8, 10, 14, 20], [6, 12, 16, 30, 50] ] k = len(arr) findSmallestRange(arr, N, k) # This code is contributed by mohit kumar",
"e": 10703,
"s": 8629,
"text": null
},
{
"code": "// C# program to finds out smallest// range that includes elements from// each of the given sorted lists.using System; class GFG { static int N = 5; // array for storing the current index of list i static int[] ptr = new int[501]; // This function takes an k sorted // lists in the form of 2D array as // an argument. It finds out smallest range // that includes elements from each of the k lists. static void findSmallestRange(int[, ] arr, int n, int k) { int i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) { ptr[i] = 0; } minrange = int.MaxValue; while (true) { // for maintaining the index of // list containing the minimum element minind = -1; minval = int.MaxValue; maxval = int.MinValue; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] // is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the // list elements pointing by the ptr[] array if (ptr[i] < n && arr[i, ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i, ptr[i]]; } // find maximum value among all the // list elements pointing by the ptr[] array if (ptr[i] < n && arr[i, ptr[i]] > maxval) { maxval = arr[i, ptr[i]]; } } // if any list exhaust we will // not get any better answer, // so break the while loop if (flag == 1) { break; } ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } Console.WriteLine(\"The smallest range is\" + \"[{0}, {1}]\\n\", minel, maxel); } // Driver code public static void Main(String[] args) { int[, ] arr = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.GetLength(0); findSmallestRange(arr, N, k); }} // This code has been contributed by 29AjayKumar",
"e": 13386,
"s": 10703,
"text": null
},
{
"code": "<script> // Javascript program to finds out smallest range that includes// elements from each of the given sorted lists.let N = 5; // array for storing the current index of list ilet ptr=new Array(501); // This function takes an k sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists.function findSmallestRange(arr,n,k){ let i, minval, maxval, minrange, minel = 0, maxel = 0, flag, minind; // initializing to 0 index; for (i = 0; i <= k; i++) { ptr[i] = 0; } minrange = Number.MAX_VALUE; while (true) { // for maintaining the index of list containing the minimum element minind = -1; minval = Number.MAX_VALUE; maxval = Number.MIN_VALUE; flag = 0; // iterating over all the list for (i = 0; i < k; i++) { // if every element of list[i] is traversed then break the loop if (ptr[i] == n) { flag = 1; break; } // find minimum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list elements pointing by the ptr[] array if (ptr[i] < n && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better answer, so break the while loop if (flag == 1) { break; } ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } document.write(\"The smallest range is [\"+minel+\", \"+maxel+\"]<br>\");} // Driver program to test above functionlet arr = [ [4, 7, 9, 12, 15], [0, 8, 10, 14, 20], [6, 12, 16, 30, 50] ]let k = arr.length;findSmallestRange(arr, N, k); // This code is contributed by unknown2108 </script>",
"e": 15709,
"s": 13386,
"text": null
},
{
"code": null,
"e": 15738,
"s": 15709,
"text": "The smallest range is [6, 8]"
},
{
"code": null,
"e": 16101,
"s": 15738,
"text": "Complexity Analysis: Time complexity : O(n * k2), to find the maximum and minimum in an array of length k the time required is O(k), and to traverse all the k arrays of length n (in worst case), the time complexity is O(n*k), then the total time complexity is O(n*k2).Space complexity: O(k), an extra array is required of length k so the space complexity is O(k)"
},
{
"code": null,
"e": 16349,
"s": 16101,
"text": "Time complexity : O(n * k2), to find the maximum and minimum in an array of length k the time required is O(k), and to traverse all the k arrays of length n (in worst case), the time complexity is O(n*k), then the total time complexity is O(n*k2)."
},
{
"code": null,
"e": 16444,
"s": 16349,
"text": "Space complexity: O(k), an extra array is required of length k so the space complexity is O(k)"
},
{
"code": null,
"e": 16727,
"s": 16444,
"text": "Efficient approach: The approach remains the same but the time complexity can be reduced by using min-heap or priority queue. Min heap can be used to find the maximum and minimum value in logarithmic time or log k time instead of linear time. Rest of the approach remains the same. "
},
{
"code": null,
"e": 17410,
"s": 16727,
"text": "Algorithm: create a Min heap to store k elements, one from each array and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer.Initially put the first element of each element from each list and store the maximum value in max.Repeat the following steps until at least one list exhausts : To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted."
},
{
"code": null,
"e": 18082,
"s": 17410,
"text": "create a Min heap to store k elements, one from each array and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer.Initially put the first element of each element from each list and store the maximum value in max.Repeat the following steps until at least one list exhausts : To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted."
},
{
"code": null,
"e": 18255,
"s": 18082,
"text": "create a Min heap to store k elements, one from each array and a variable minrange initialized to a maximum value and also keep a variable max to store the maximum integer."
},
{
"code": null,
"e": 18354,
"s": 18255,
"text": "Initially put the first element of each element from each list and store the maximum value in max."
},
{
"code": null,
"e": 18756,
"s": 18354,
"text": "Repeat the following steps until at least one list exhausts : To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted."
},
{
"code": null,
"e": 19096,
"s": 18756,
"text": "To find the minimum value or min, use the top or root of the Min heap which is the minimum element.Now update the minrange if current (max-min) is less than minrange.remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted."
},
{
"code": null,
"e": 19196,
"s": 19096,
"text": "To find the minimum value or min, use the top or root of the Min heap which is the minimum element."
},
{
"code": null,
"e": 19264,
"s": 19196,
"text": "Now update the minrange if current (max-min) is less than minrange."
},
{
"code": null,
"e": 19438,
"s": 19264,
"text": "remove the top or root element from priority queue and insert the next element from the list which contains the min element and update the max with the new element inserted."
},
{
"code": null,
"e": 19454,
"s": 19438,
"text": "Implementation:"
},
{
"code": null,
"e": 19458,
"s": 19454,
"text": "C++"
},
{
"code": null,
"e": 19463,
"s": 19458,
"text": "Java"
},
{
"code": null,
"e": 19466,
"s": 19463,
"text": "C#"
},
{
"code": null,
"e": 19477,
"s": 19466,
"text": "Javascript"
},
{
"code": "// C++ program to finds out smallest range that includes// elements from each of the given sorted lists.#include <bits/stdc++.h>using namespace std; #define N 5 // A min heap nodestruct MinHeapNode { // The element to be stored int element; // index of the list from which the element is taken int i; // index of the next element to be picked from list int j;}; // Prototype of a utility function to swap two min heap nodesvoid swap(MinHeapNode* x, MinHeapNode* y); // A class for Min Heapclass MinHeap { // pointer to array of elements in heap MinHeapNode* harr; // size of min heap int heap_size; public: // Constructor: creates a min heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with root at given index void MinHeapify(int); // to get index of left child of node at index i int left(int i) { return (2 * i + 1); } // to get index of right child of node at index i int right(int i) { return (2 * i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node x and heapify() new root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); }}; // Constructor: Builds a heap from a// given array a[] of given sizeMinHeap::MinHeap(MinHeapNode a[], int size){ heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; }} // A recursive method to heapify a subtree with root at// given index. This method assumes that the subtrees// are already heapifiedvoid MinHeap::MinHeapify(int i){ int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); }} // This function takes an k sorted lists in the form of// 2D array as an argument. It finds out smallest range// that includes elements from each of the k lists.void findSmallestRange(int arr[][N], int k){ // Create a min heap with k heap nodes. Every heap node // has first element of an list int range = INT_MAX; int min = INT_MAX, max = INT_MIN; int start, end; MinHeapNode* harr = new MinHeapNode[k]; for (int i = 0; i < k; i++) { // Store the first element harr[i].element = arr[i][0]; // index of list harr[i].i = i; // Index of next element to be stored // from list harr[i].j = 1; // store max element if (harr[i].element > max) max = harr[i].element; } // Create the heap MinHeap hp(harr, k); // Now one by one get the minimum element from min // heap and replace it with next element of its list while (1) { // Get the minimum element and store it in output MinHeapNode root = hp.getMin(); // update min min = hp.getMin().element; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will replace current // root of heap. The next element belongs to same // list as the current root. if (root.j < N) { root.element = arr[root.i][root.j]; root.j += 1; // update max element if (root.element > max) max = root.element; } // break if we have reached end of any list else break; // Replace root with next element of list hp.replaceMin(root); } cout << \"The smallest range is \" << \"[\" << start << \" \" << end << \"]\" << endl; ;} // Driver program to test above functionsint main(){ int arr[][N] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = sizeof(arr) / sizeof(arr[0]); findSmallestRange(arr, k); return 0;}",
"e": 23575,
"s": 19477,
"text": null
},
{
"code": "// Java program to find out smallest// range that includes elements from// each of the given sorted lists.class GFG { // A min heap node static class Node { // The element to be stored int ele; // index of the list from which // the element is taken int i; // index of the next element // to be picked from list int j; Node(int a, int b, int c) { this.ele = a; this.i = b; this.j = c; } } // A class for Min Heap static class MinHeap { Node[] harr; // array of elements in heap int size; // size of min heap // Constructor: creates a min heap // of given size MinHeap(Node[] arr, int size) { this.harr = arr; this.size = size; int i = (size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; } } // to get index of left child // of node at index i int left(int i) { return 2 * i + 1; } // to get index of right child // of node at index i int right(int i) { return 2 * i + 2; } // to heapify a subtree with // root at given index void MinHeapify(int i) { int l = left(i); int r = right(i); int small = i; if (l < size && harr[l].ele < harr[i].ele) small = l; if (r < size && harr[r].ele < harr[small].ele) small = r; if (small != i) { swap(small, i); MinHeapify(small); } } void swap(int i, int j) { Node temp = harr[i]; harr[i] = harr[j]; harr[j] = temp; } // to get the root Node getMin() { return harr[0]; } // to replace root with new node x // and heapify() new root void replaceMin(Node x) { harr[0] = x; MinHeapify(0); } } // This function takes an k sorted lists // in the form of 2D array as an argument. // It finds out smallest range that includes // elements from each of the k lists. static void findSmallestRange(int[][] arr, int k) { int range = Integer.MAX_VALUE; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; int start = -1, end = -1; int n = arr[0].length; // Create a min heap with k heap nodes. // Every heap node has first element of an list Node[] arr1 = new Node[k]; for (int i = 0; i < k; i++) { Node node = new Node(arr[i][0], i, 1); arr1[i] = node; // store max element max = Math.max(max, node.ele); } // Create the heap MinHeap mh = new MinHeap(arr1, k); // Now one by one get the minimum element // from min heap and replace it with // next element of its list while (true) { // Get the minimum element and // store it in output Node root = mh.getMin(); // update min min = root.ele; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will // replace current root of heap. // The next element belongs to same // list as the current root. if (root.j < n) { root.ele = arr[root.i][root.j]; root.j++; // update max element if (root.ele > max) max = root.ele; } // break if we have reached // end of any list else break; // Replace root with next element of list mh.replaceMin(root); } System.out.print(\"The smallest range is [\" + start + \" \" + end + \"]\"); } // Driver Code public static void main(String[] args) { int arr[][] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.length; findSmallestRange(arr, k); }} // This code is contributed by nobody_cares",
"e": 27994,
"s": 23575,
"text": null
},
{
"code": "// C# program to find out smallest// range that includes elements from// each of the given sorted lists.using System;using System.Collections.Generic; class GFG { // A min heap node public class Node { // The element to be stored public int ele; // index of the list from which // the element is taken public int i; // index of the next element // to be picked from list public int j; public Node(int a, int b, int c) { this.ele = a; this.i = b; this.j = c; } } // A class for Min Heap public class MinHeap { // array of elements in heap public Node[] harr; // size of min heap public int size; // Constructor: creates a min heap // of given size public MinHeap(Node[] arr, int size) { this.harr = arr; this.size = size; int i = (size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; } } // to get index of left child // of node at index i int left(int i) { return 2 * i + 1; } // to get index of right child // of node at index i int right(int i) { return 2 * i + 2; } // to heapify a subtree with // root at given index void MinHeapify(int i) { int l = left(i); int r = right(i); int small = i; if (l < size && harr[l].ele < harr[i].ele) small = l; if (r < size && harr[r].ele < harr[small].ele) small = r; if (small != i) { swap(small, i); MinHeapify(small); } } void swap(int i, int j) { Node temp = harr[i]; harr[i] = harr[j]; harr[j] = temp; } // to get the root public Node getMin() { return harr[0]; } // to replace root with new node x // and heapify() new root public void replaceMin(Node x) { harr[0] = x; MinHeapify(0); } } // This function takes an k sorted lists // in the form of 2D array as an argument. // It finds out smallest range that includes // elements from each of the k lists. static void findSmallestRange(int[, ] arr, int k) { int range = int.MaxValue; int min = int.MaxValue; int max = int.MinValue; int start = -1, end = -1; int n = arr.GetLength(0); // Create a min heap with k heap nodes. // Every heap node has first element of an list Node[] arr1 = new Node[k]; for (int i = 0; i < k; i++) { Node node = new Node(arr[i, 0], i, 1); arr1[i] = node; // store max element max = Math.Max(max, node.ele); } // Create the heap MinHeap mh = new MinHeap(arr1, k); // Now one by one get the minimum element // from min heap and replace it with // next element of its list while (true) { // Get the minimum element and // store it in output Node root = mh.getMin(); // update min min = root.ele; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will // replace current root of heap. // The next element belongs to same // list as the current root. if (root.j < n) { root.ele = arr[root.i, root.j]; root.j++; // update max element if (root.ele > max) max = root.ele; } else break; // break if we have reached // end of any list // Replace root with next element of list mh.replaceMin(root); } Console.Write(\"The smallest range is [\" + start + \" \" + end + \"]\"); } // Driver Code public static void Main(String[] args) { int[, ] arr = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int k = arr.GetLength(0); findSmallestRange(arr, k); }} // This code is contributed by Rajput-Ji",
"e": 32513,
"s": 27994,
"text": null
},
{
"code": "<script> // Javascript program to find out smallest// range that includes elements from// each of the given sorted lists.class Node{ constructor(a, b, c) { this.ele = a; this.i = b; this.j = c; }} // A class for Min Heapclass MinHeap{ // Array of elements in heap harr; // Size of min heap size; // Constructor: creates a min heap // of given size constructor(arr,size) { this.harr = arr; this.size = size; let i = Math.floor((size - 1) / 2); while (i >= 0) { this.MinHeapify(i); i--; } } // To get index of left child // of node at index i left(i) { return 2 * i + 1; } // To get index of right child // of node at index i right(i) { return 2 * i + 2; } // To heapify a subtree with // root at given index MinHeapify(i) { let l = this.left(i); let r = this.right(i); let small = i; if (l < this.size && this.harr[l].ele < this.harr[i].ele) small = l; if (r < this.size && this.harr[r].ele < this.harr[small].ele) small = r; if (small != i) { this.swap(small, i); this.MinHeapify(small); } } swap(i, j) { let temp = this.harr[i]; this.harr[i] = this.harr[j]; this.harr[j] = temp; } // To get the root getMin() { return this.harr[0]; } // To replace root with new node x // and heapify() new root replaceMin(x) { this.harr[0] = x; this.MinHeapify(0); } } // This function takes an k sorted lists// in the form of 2D array as an argument.// It finds out smallest range that includes// elements from each of the k lists.function findSmallestRange(arr, k){ let range = Number.MAX_VALUE; let min = Number.MAX_VALUE; let max = Number.MIN_VALUE; let start = -1, end = -1; let n = arr[0].length; // Create a min heap with k heap nodes. // Every heap node has first element of an list let arr1 = new Array(k); for(let i = 0; i < k; i++) { let node = new Node(arr[i][0], i, 1); arr1[i] = node; // Store max element max = Math.max(max, node.ele); } // Create the heap let mh = new MinHeap(arr1, k); // Now one by one get the minimum element // from min heap and replace it with // next element of its list while (true) { // Get the minimum element and // store it in output let root = mh.getMin(); // Update min min = root.ele; // Update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will // replace current root of heap. // The next element belongs to same // list as the current root. if (root.j < n) { root.ele = arr[root.i][root.j]; root.j++; // Update max element if (root.ele > max) max = root.ele; } // Break if we have reached // end of any list else break; // Replace root with next element of list mh.replaceMin(root); } document.write(\"The smallest range is [\" + start + \" \" + end + \"]\");} // Driver Codelet arr = [ [ 4, 7, 9, 12, 15 ], [ 0, 8, 10, 14, 20 ], [ 6, 12, 16, 30, 50 ] ];let k = arr.length; findSmallestRange(arr, k); // This code is contributed by rag2127 </script>",
"e": 36257,
"s": 32513,
"text": null
},
{
"code": null,
"e": 36285,
"s": 36257,
"text": "The smallest range is [6 8]"
},
{
"code": null,
"e": 36674,
"s": 36285,
"text": "Complexity Analysis: Time complexity : O(n * k *log k). To find the maximum and minimum in a Min Heap of length k the time required is O(log k), and to traverse all the k arrays of length n (in the worst case), the time complexity is O(n*k), then the total time complexity is O(n * k *log k).Space complexity: O(k). The priority queue will store k elements so the space complexity of O(k)"
},
{
"code": null,
"e": 36946,
"s": 36674,
"text": "Time complexity : O(n * k *log k). To find the maximum and minimum in a Min Heap of length k the time required is O(log k), and to traverse all the k arrays of length n (in the worst case), the time complexity is O(n*k), then the total time complexity is O(n * k *log k)."
},
{
"code": null,
"e": 37043,
"s": 36946,
"text": "Space complexity: O(k). The priority queue will store k elements so the space complexity of O(k)"
},
{
"code": null,
"e": 37309,
"s": 37043,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 37319,
"s": 37309,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37334,
"s": 37319,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 37346,
"s": 37334,
"text": "29AjayKumar"
},
{
"code": null,
"e": 37359,
"s": 37346,
"text": "nobody_cares"
},
{
"code": null,
"e": 37370,
"s": 37359,
"text": "andrew1234"
},
{
"code": null,
"e": 37382,
"s": 37370,
"text": "unknown2108"
},
{
"code": null,
"e": 37399,
"s": 37382,
"text": "arorakashish0911"
},
{
"code": null,
"e": 37407,
"s": 37399,
"text": "rag2127"
},
{
"code": null,
"e": 37426,
"s": 37407,
"text": "surindertarika1234"
},
{
"code": null,
"e": 37435,
"s": 37426,
"text": "rkbhola5"
},
{
"code": null,
"e": 37451,
"s": 37435,
"text": "debayanbiswas31"
},
{
"code": null,
"e": 37468,
"s": 37451,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 37475,
"s": 37468,
"text": "Arrays"
},
{
"code": null,
"e": 37480,
"s": 37475,
"text": "Hash"
},
{
"code": null,
"e": 37487,
"s": 37480,
"text": "Arrays"
},
{
"code": null,
"e": 37492,
"s": 37487,
"text": "Hash"
},
{
"code": null,
"e": 37590,
"s": 37492,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37622,
"s": 37590,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 37669,
"s": 37622,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 37694,
"s": 37669,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 37725,
"s": 37694,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 37757,
"s": 37725,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 37795,
"s": 37757,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 37826,
"s": 37795,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 37862,
"s": 37826,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 37894,
"s": 37862,
"text": "Longest Consecutive Subsequence"
}
]
|
How to parse float with two decimal places in JavaScript ? | 26 Jul, 2021
JavaScript is high level, dynamically typed, and interpreted client-side scripting language. JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number.
The parseFloat() method checks if the first character of the string is a number, if it is a number the method parses the string till the end. In case the first character of the string is not a number then parseFloat() returns NaN (Not a Number). The parseFloat() method parses the entire string. If the passed string has 5 digits after the decimal then the output is a floating-point number with 5 digits after the decimal. To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.
Syntax:
parseFloat(string)
Parameters:
String: The floating-point number in the string format that is to be parsed.
Return value: It returns the parsed floating-point number if the first character of the string is a number else it returns a NaN.
Syntax:
toFixed( int )
Parameter
int: The number of places after the decimal up to which the string must be parsed.
Return value: It returns the number or string rounded up to the specified places after the decimal. If the specified value is greater than the number of digits after decimal in the actual string then the resulting value is padded with 0 to maintain the number of digits after decimal in the final output.
Example 1:
Javascript
var num1 = parseFloat("10.547892")var num2 = parseFloat("10.547892").toFixed(2)console.log("Without using toFixed() method");console.log(num1);console.log("Using toFixed() method");console.log(num2);
Output:
Example 2: The above example rounds up the number up to 2 places after the decimal. But in some cases, the developer may not want to round up the number. This is an alternative method to get the floating-point number up to the specified places without rounding it.
In this example, a function ParseFloat() is defined which takes 2 arguments. The first argument is a string or number to be parsed and the second argument is the number of places after the decimal.
Approach: At first, the first argument is converted to a string, this helps if the passed argument is not already in string format. The string is now sliced from the starting up to the number of places specified after the decimal. Finally, the sliced string is returned after type conversion into a number. The limitation of this method is that unlike parseFloat(), this method cannot detect if the passed string actually contains a floating-point number.
Example:
Javascript
function ParseFloat(str,val) { str = str.toString(); str = str.slice(0, (str.indexOf(".")) + val + 1); return Number(str); }console.log(ParseFloat("10.547892",2))
Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
JavaScript-Misc
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 228,
"s": 28,
"text": "JavaScript is high level, dynamically typed, and interpreted client-side scripting language. JavaScript provides an inbuilt parseFloat() method to parse a string and returns a floating-point number. "
},
{
"code": null,
"e": 838,
"s": 228,
"text": "The parseFloat() method checks if the first character of the string is a number, if it is a number the method parses the string till the end. In case the first character of the string is not a number then parseFloat() returns NaN (Not a Number). The parseFloat() method parses the entire string. If the passed string has 5 digits after the decimal then the output is a floating-point number with 5 digits after the decimal. To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal. "
},
{
"code": null,
"e": 846,
"s": 838,
"text": "Syntax:"
},
{
"code": null,
"e": 866,
"s": 846,
"text": "parseFloat(string) "
},
{
"code": null,
"e": 878,
"s": 866,
"text": "Parameters:"
},
{
"code": null,
"e": 955,
"s": 878,
"text": "String: The floating-point number in the string format that is to be parsed."
},
{
"code": null,
"e": 1085,
"s": 955,
"text": "Return value: It returns the parsed floating-point number if the first character of the string is a number else it returns a NaN."
},
{
"code": null,
"e": 1093,
"s": 1085,
"text": "Syntax:"
},
{
"code": null,
"e": 1108,
"s": 1093,
"text": "toFixed( int )"
},
{
"code": null,
"e": 1118,
"s": 1108,
"text": "Parameter"
},
{
"code": null,
"e": 1201,
"s": 1118,
"text": "int: The number of places after the decimal up to which the string must be parsed."
},
{
"code": null,
"e": 1506,
"s": 1201,
"text": "Return value: It returns the number or string rounded up to the specified places after the decimal. If the specified value is greater than the number of digits after decimal in the actual string then the resulting value is padded with 0 to maintain the number of digits after decimal in the final output."
},
{
"code": null,
"e": 1517,
"s": 1506,
"text": "Example 1:"
},
{
"code": null,
"e": 1528,
"s": 1517,
"text": "Javascript"
},
{
"code": "var num1 = parseFloat(\"10.547892\")var num2 = parseFloat(\"10.547892\").toFixed(2)console.log(\"Without using toFixed() method\");console.log(num1);console.log(\"Using toFixed() method\");console.log(num2);",
"e": 1728,
"s": 1528,
"text": null
},
{
"code": null,
"e": 1736,
"s": 1728,
"text": "Output:"
},
{
"code": null,
"e": 2001,
"s": 1736,
"text": "Example 2: The above example rounds up the number up to 2 places after the decimal. But in some cases, the developer may not want to round up the number. This is an alternative method to get the floating-point number up to the specified places without rounding it."
},
{
"code": null,
"e": 2199,
"s": 2001,
"text": "In this example, a function ParseFloat() is defined which takes 2 arguments. The first argument is a string or number to be parsed and the second argument is the number of places after the decimal."
},
{
"code": null,
"e": 2656,
"s": 2199,
"text": "Approach: At first, the first argument is converted to a string, this helps if the passed argument is not already in string format. The string is now sliced from the starting up to the number of places specified after the decimal. Finally, the sliced string is returned after type conversion into a number. The limitation of this method is that unlike parseFloat(), this method cannot detect if the passed string actually contains a floating-point number. "
},
{
"code": null,
"e": 2665,
"s": 2656,
"text": "Example:"
},
{
"code": null,
"e": 2676,
"s": 2665,
"text": "Javascript"
},
{
"code": "function ParseFloat(str,val) { str = str.toString(); str = str.slice(0, (str.indexOf(\".\")) + val + 1); return Number(str); }console.log(ParseFloat(\"10.547892\",2))",
"e": 2851,
"s": 2676,
"text": null
},
{
"code": null,
"e": 2859,
"s": 2851,
"text": "Output:"
},
{
"code": null,
"e": 3078,
"s": 2859,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3094,
"s": 3078,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3101,
"s": 3094,
"text": "Picked"
},
{
"code": null,
"e": 3125,
"s": 3101,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3136,
"s": 3125,
"text": "JavaScript"
},
{
"code": null,
"e": 3155,
"s": 3136,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3172,
"s": 3155,
"text": "Web Technologies"
}
]
|
Seating Arrangement | Aptitude | 10 May, 2021
Overview :The seating arrangement is the arrangement of people/objects logically. It can be a linear arrangement or circular arrangement. In circular seating arrangement, we arrange people around a circle while in linear seating arrangement, we arrange people in a line. Some detail regarding the objects/person and how they are seated is given, one should arrange either in a Linear or circular as mentioned. This concept involves the arrangement of people in many possible ways. In these type of questions, you will have to arrange a group of persons satisfying certain conditions. The questions on this topic can be asked in any sequence (linear arrangement, circular arrangement). By applying the logical analysis, we can perform the logical arrangement to answer the questions or decode.
Rules for Seating arrangement :Here, we will discuss the rules as follows.
Identifying the right and left in a given seating arrangementIf it is not mentioned in the question we cannot assume left an immediate left.Always start the arrangement with complete fixed details.In the case of a circular arrangement, if nothing is mention regarding the direction they are facing then by default take it as facing Centre.
Identifying the right and left in a given seating arrangement
If it is not mentioned in the question we cannot assume left an immediate left.
Always start the arrangement with complete fixed details.
In the case of a circular arrangement, if nothing is mention regarding the direction they are facing then by default take it as facing Centre.
Features :The questions on Seating arrangement are the most common types of questions asked in reasoning in all entrance exams. There are different types of problems with the concept of seating arrangement as follows.
Linear ArrangementSquare/Rectangular ArrangementCircular ArrangementTriangular arrangementHexagonal arrangementPentagon arrangement.Combination of the above.
Linear Arrangement
Square/Rectangular Arrangement
Circular Arrangement
Triangular arrangement
Hexagonal arrangement
Pentagon arrangement.
Combination of the above.
Examples :Following are some questions on seating arrangement as follows.
Example-1 : B, L, M, N, P, and Q are in a row. P and Q are in the center, B and L are at the ends. M is sitting to the left of B. Who is to the right of L?
Solution –The seating arrangement is as follows.
L--N--P--Q--M--B
Therefore, the right of L is N.
Example-2 : Five boys are sitting to be photographed. S is to the left of R and to the right of B. M is to the right of R. E is between R and M.
Who is sitting immediate right to E? Answer- MWho is second from the right? Answer- E
Who is sitting immediate right to E? Answer- M
Who is second from the right? Answer- E
Solution –The seating arrangement is as follows.
B--S--R--E--M
Example-3 : Five girls are standing in a line. One of the two girls at extreme end is P and the other is B. A is to the right of S. C is to the left of the B. What is the position of A from the left?
Solution –The seating arrangement is as follows.
P--S--A--C--B
Answer - 3
Conclusion : Seating arrangements can be asked as mixed with puzzles or any topic of logical reasoning. In any seating arrangement problem, the easiest way is from the possible cases, eliminate one by one using the statements. While solving questions, first start with the clues with more connectors. It is important that students practice all types of questions on this topic to ace it in any competitive exam. If you can solve seating arrangement questions with ease, then you can ace any competitive exam easily.
Picked
Aptitude
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 May, 2021"
},
{
"code": null,
"e": 847,
"s": 54,
"text": "Overview :The seating arrangement is the arrangement of people/objects logically. It can be a linear arrangement or circular arrangement. In circular seating arrangement, we arrange people around a circle while in linear seating arrangement, we arrange people in a line. Some detail regarding the objects/person and how they are seated is given, one should arrange either in a Linear or circular as mentioned. This concept involves the arrangement of people in many possible ways. In these type of questions, you will have to arrange a group of persons satisfying certain conditions. The questions on this topic can be asked in any sequence (linear arrangement, circular arrangement). By applying the logical analysis, we can perform the logical arrangement to answer the questions or decode."
},
{
"code": null,
"e": 922,
"s": 847,
"text": "Rules for Seating arrangement :Here, we will discuss the rules as follows."
},
{
"code": null,
"e": 1262,
"s": 922,
"text": "Identifying the right and left in a given seating arrangementIf it is not mentioned in the question we cannot assume left an immediate left.Always start the arrangement with complete fixed details.In the case of a circular arrangement, if nothing is mention regarding the direction they are facing then by default take it as facing Centre."
},
{
"code": null,
"e": 1324,
"s": 1262,
"text": "Identifying the right and left in a given seating arrangement"
},
{
"code": null,
"e": 1404,
"s": 1324,
"text": "If it is not mentioned in the question we cannot assume left an immediate left."
},
{
"code": null,
"e": 1462,
"s": 1404,
"text": "Always start the arrangement with complete fixed details."
},
{
"code": null,
"e": 1605,
"s": 1462,
"text": "In the case of a circular arrangement, if nothing is mention regarding the direction they are facing then by default take it as facing Centre."
},
{
"code": null,
"e": 1823,
"s": 1605,
"text": "Features :The questions on Seating arrangement are the most common types of questions asked in reasoning in all entrance exams. There are different types of problems with the concept of seating arrangement as follows."
},
{
"code": null,
"e": 1981,
"s": 1823,
"text": "Linear ArrangementSquare/Rectangular ArrangementCircular ArrangementTriangular arrangementHexagonal arrangementPentagon arrangement.Combination of the above."
},
{
"code": null,
"e": 2000,
"s": 1981,
"text": "Linear Arrangement"
},
{
"code": null,
"e": 2031,
"s": 2000,
"text": "Square/Rectangular Arrangement"
},
{
"code": null,
"e": 2052,
"s": 2031,
"text": "Circular Arrangement"
},
{
"code": null,
"e": 2075,
"s": 2052,
"text": "Triangular arrangement"
},
{
"code": null,
"e": 2097,
"s": 2075,
"text": "Hexagonal arrangement"
},
{
"code": null,
"e": 2119,
"s": 2097,
"text": "Pentagon arrangement."
},
{
"code": null,
"e": 2145,
"s": 2119,
"text": "Combination of the above."
},
{
"code": null,
"e": 2219,
"s": 2145,
"text": "Examples :Following are some questions on seating arrangement as follows."
},
{
"code": null,
"e": 2375,
"s": 2219,
"text": "Example-1 : B, L, M, N, P, and Q are in a row. P and Q are in the center, B and L are at the ends. M is sitting to the left of B. Who is to the right of L?"
},
{
"code": null,
"e": 2424,
"s": 2375,
"text": "Solution –The seating arrangement is as follows."
},
{
"code": null,
"e": 2441,
"s": 2424,
"text": "L--N--P--Q--M--B"
},
{
"code": null,
"e": 2473,
"s": 2441,
"text": "Therefore, the right of L is N."
},
{
"code": null,
"e": 2618,
"s": 2473,
"text": "Example-2 : Five boys are sitting to be photographed. S is to the left of R and to the right of B. M is to the right of R. E is between R and M."
},
{
"code": null,
"e": 2709,
"s": 2618,
"text": "Who is sitting immediate right to E? Answer- MWho is second from the right? Answer- E"
},
{
"code": null,
"e": 2757,
"s": 2709,
"text": "Who is sitting immediate right to E? Answer- M"
},
{
"code": null,
"e": 2801,
"s": 2757,
"text": "Who is second from the right? Answer- E"
},
{
"code": null,
"e": 2850,
"s": 2801,
"text": "Solution –The seating arrangement is as follows."
},
{
"code": null,
"e": 2864,
"s": 2850,
"text": "B--S--R--E--M"
},
{
"code": null,
"e": 3064,
"s": 2864,
"text": "Example-3 : Five girls are standing in a line. One of the two girls at extreme end is P and the other is B. A is to the right of S. C is to the left of the B. What is the position of A from the left?"
},
{
"code": null,
"e": 3113,
"s": 3064,
"text": "Solution –The seating arrangement is as follows."
},
{
"code": null,
"e": 3138,
"s": 3113,
"text": "P--S--A--C--B\nAnswer - 3"
},
{
"code": null,
"e": 3654,
"s": 3138,
"text": "Conclusion : Seating arrangements can be asked as mixed with puzzles or any topic of logical reasoning. In any seating arrangement problem, the easiest way is from the possible cases, eliminate one by one using the statements. While solving questions, first start with the clues with more connectors. It is important that students practice all types of questions on this topic to ace it in any competitive exam. If you can solve seating arrangement questions with ease, then you can ace any competitive exam easily."
},
{
"code": null,
"e": 3661,
"s": 3654,
"text": "Picked"
},
{
"code": null,
"e": 3670,
"s": 3661,
"text": "Aptitude"
}
]
|
numpy.multiply() in Python | 16 May, 2020
numpy.multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.
Syntax : numpy.multiply(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘multiply’)
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 product of arr1 and arr2, element-wise.
Example #1 :
# Python program explaining# numpy.multiply() function import numpy as geekin_num1 = 4in_num2 = 6 print ("1st Input number : ", in_num1)print ("2nd Input number : ", in_num2) out_num = geek.multiply(in_num1, in_num2) print ("output number : ", out_num)
1st Input number : 4
2nd Input number : 6
output number : 24
Example #2 :The following code is also known as the Hadamard product which is nothing but the element-wise-product of the two matrices. It is the most commonly used product for those who are interested in Machine Learning or statistics.
# Python program explaining# numpy.multiply() function import numpy as geek in_arr1 = geek.array([[2, -7, 5], [-6, 2, 0]])in_arr2 = geek.array([[0, -7, 8], [5, -2, 9]]) print ("1st Input array : ", in_arr1)print ("2nd Input array : ", in_arr2) out_arr = geek.multiply(in_arr1, in_arr2) print ("Resultant output array: ", out_arr)
1st Input array : [[ 2 -7 5]
[-6 2 0]]
2nd Input array : [[ 0 -7 8]
[ 5 -2 9]]
Resultant output array: [[ 0 49 40]
[-30 -4 0]]
Another way to find the same is
import numpy as geekin_arr1=geek.matrix([[2, -7, 5], [-6, 2, 0]])in_arr2 = geek.matrix([[0, -7, 8], [5, -2, 9]]) print ("1st Input array : ", in_arr1)print ("2nd Input array : ", in_arr2) out_arr=geek.array(in_arr1)*geek.array(in_arr2)print ("Resultant output array: ", out_arr)
Output :
1st Input array : [[ 2 -7 5]
[-6 2 0]]
2nd Input array : [[ 0 -7 8]
[ 5 -2 9]]
Resultant output array: [[ 0 49 40]
[-30 -4 0]]
riasehgal1999
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 May, 2020"
},
{
"code": null,
"e": 198,
"s": 52,
"text": "numpy.multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise."
},
{
"code": null,
"e": 357,
"s": 198,
"text": "Syntax : numpy.multiply(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘multiply’)"
},
{
"code": null,
"e": 1030,
"s": 357,
"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": 1102,
"s": 1030,
"text": "Return: [ndarray or scalar] The product of arr1 and arr2, element-wise."
},
{
"code": null,
"e": 1115,
"s": 1102,
"text": "Example #1 :"
},
{
"code": "# Python program explaining# numpy.multiply() function import numpy as geekin_num1 = 4in_num2 = 6 print (\"1st Input number : \", in_num1)print (\"2nd Input number : \", in_num2) out_num = geek.multiply(in_num1, in_num2) print (\"output number : \", out_num) ",
"e": 1376,
"s": 1115,
"text": null
},
{
"code": null,
"e": 1441,
"s": 1376,
"text": "1st Input number : 4\n2nd Input number : 6\noutput number : 24\n"
},
{
"code": null,
"e": 1680,
"s": 1443,
"text": "Example #2 :The following code is also known as the Hadamard product which is nothing but the element-wise-product of the two matrices. It is the most commonly used product for those who are interested in Machine Learning or statistics."
},
{
"code": "# Python program explaining# numpy.multiply() function import numpy as geek in_arr1 = geek.array([[2, -7, 5], [-6, 2, 0]])in_arr2 = geek.array([[0, -7, 8], [5, -2, 9]]) print (\"1st Input array : \", in_arr1)print (\"2nd Input array : \", in_arr2) out_arr = geek.multiply(in_arr1, in_arr2) print (\"Resultant output array: \", out_arr) ",
"e": 2021,
"s": 1680,
"text": null
},
{
"code": null,
"e": 2166,
"s": 2021,
"text": "1st Input array : [[ 2 -7 5]\n [-6 2 0]]\n2nd Input array : [[ 0 -7 8]\n [ 5 -2 9]]\nResultant output array: [[ 0 49 40]\n [-30 -4 0]]\n"
},
{
"code": null,
"e": 2198,
"s": 2166,
"text": "Another way to find the same is"
},
{
"code": "import numpy as geekin_arr1=geek.matrix([[2, -7, 5], [-6, 2, 0]])in_arr2 = geek.matrix([[0, -7, 8], [5, -2, 9]]) print (\"1st Input array : \", in_arr1)print (\"2nd Input array : \", in_arr2) out_arr=geek.array(in_arr1)*geek.array(in_arr2)print (\"Resultant output array: \", out_arr)",
"e": 2482,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2491,
"s": 2482,
"text": "Output :"
},
{
"code": null,
"e": 2636,
"s": 2491,
"text": "1st Input array : [[ 2 -7 5]\n [-6 2 0]]\n2nd Input array : [[ 0 -7 8]\n [ 5 -2 9]]\nResultant output array: [[ 0 49 40]\n [-30 -4 0]]\n"
},
{
"code": null,
"e": 2650,
"s": 2636,
"text": "riasehgal1999"
},
{
"code": null,
"e": 2685,
"s": 2650,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 2698,
"s": 2685,
"text": "Python-numpy"
},
{
"code": null,
"e": 2705,
"s": 2698,
"text": "Python"
}
]
|
Python | Pandas Series/Dataframe.any() | 16 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas any() method is applicable both on Series and Dataframe. It checks whether any value in the caller object (Dataframe or series) is not 0 and returns True for that. If all values are 0, it will return False.
Syntax: DataFrame.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)
Parameters:axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columns.bool_only: Checks for bool only series in Data frame, if none found, it will use only boolean values. This parameter is not for series since there is only one column.skipna: Boolean value, If False, returns True for whole NaN column/rowlevel: int or str, specifies level in case of multilevel
Return type: Boolean series
Example #1: Index wise implementation
In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method. Null values are also passed to some indexes using Numpy np.nan to check behaviour with null values. Since in this example, the method is implemented on index, the axis parameter is kept 0 (that stands for rows).
# importing pandas module import pandas as pd # importing numpy moduleimport numpy as np # creating dictionarydic = {'A': [1, 2, 3, 4, 0, np.nan, 3], 'B': [3, 1, 4, 5, 0, np.nan, 5], 'C': [0, 0, 0, 0, 0, 0, 0]} # making dataframe using dictionarydata = pd.DataFrame(dic) # calling data.any column wiseresult = data.any(axis = 0) # displaying resultresult
Output:As shown in output, since last column is having all values equal to zero, Hence False was returned only for that column.
Example #2: Column wise Implementation
In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method just like in above example. But instead of passing 0 to axis parameter, 1 is passed to implement for each value in every column.
# importing pandas module import pandas as pd # importing numpy moduleimport numpy as np # creating dictionarydic = {'A': [1, 2, 3, 4, 0, np.nan, 3], 'B': [3, 1, 4, 5, 0, np.nan, 5], 'C': [0, 0, 0, 0, 0, 0, 0]} # making dataframe using dictionarydata = pd.DataFrame(dic) # calling data.any column wiseresult = data.any(axis = 1) # displaying resultresult
Output:As shown in the output, False was returned for only rows where all values were 0 or NaN and 0.
Python pandas-dataFrame-methods
Python pandas-general-functions
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2018"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 456,
"s": 242,
"text": "Pandas any() method is applicable both on Series and Dataframe. It checks whether any value in the caller object (Dataframe or series) is not 0 and returns True for that. If all values are 0, it will return False."
},
{
"code": null,
"e": 537,
"s": 456,
"text": "Syntax: DataFrame.any(axis=0, bool_only=None, skipna=True, level=None, **kwargs)"
},
{
"code": null,
"e": 923,
"s": 537,
"text": "Parameters:axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columns.bool_only: Checks for bool only series in Data frame, if none found, it will use only boolean values. This parameter is not for series since there is only one column.skipna: Boolean value, If False, returns True for whole NaN column/rowlevel: int or str, specifies level in case of multilevel"
},
{
"code": null,
"e": 951,
"s": 923,
"text": "Return type: Boolean series"
},
{
"code": null,
"e": 989,
"s": 951,
"text": "Example #1: Index wise implementation"
},
{
"code": null,
"e": 1301,
"s": 989,
"text": "In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method. Null values are also passed to some indexes using Numpy np.nan to check behaviour with null values. Since in this example, the method is implemented on index, the axis parameter is kept 0 (that stands for rows)."
},
{
"code": "# importing pandas module import pandas as pd # importing numpy moduleimport numpy as np # creating dictionarydic = {'A': [1, 2, 3, 4, 0, np.nan, 3], 'B': [3, 1, 4, 5, 0, np.nan, 5], 'C': [0, 0, 0, 0, 0, 0, 0]} # making dataframe using dictionarydata = pd.DataFrame(dic) # calling data.any column wiseresult = data.any(axis = 0) # displaying resultresult",
"e": 1674,
"s": 1301,
"text": null
},
{
"code": null,
"e": 1802,
"s": 1674,
"text": "Output:As shown in output, since last column is having all values equal to zero, Hence False was returned only for that column."
},
{
"code": null,
"e": 1842,
"s": 1802,
"text": " Example #2: Column wise Implementation"
},
{
"code": null,
"e": 2070,
"s": 1842,
"text": "In this example, a sample data frame is created by passing dictionary to Pandas DataFrame() method just like in above example. But instead of passing 0 to axis parameter, 1 is passed to implement for each value in every column."
},
{
"code": "# importing pandas module import pandas as pd # importing numpy moduleimport numpy as np # creating dictionarydic = {'A': [1, 2, 3, 4, 0, np.nan, 3], 'B': [3, 1, 4, 5, 0, np.nan, 5], 'C': [0, 0, 0, 0, 0, 0, 0]} # making dataframe using dictionarydata = pd.DataFrame(dic) # calling data.any column wiseresult = data.any(axis = 1) # displaying resultresult",
"e": 2443,
"s": 2070,
"text": null
},
{
"code": null,
"e": 2545,
"s": 2443,
"text": "Output:As shown in the output, False was returned for only rows where all values were 0 or NaN and 0."
},
{
"code": null,
"e": 2577,
"s": 2545,
"text": "Python pandas-dataFrame-methods"
},
{
"code": null,
"e": 2609,
"s": 2577,
"text": "Python pandas-general-functions"
},
{
"code": null,
"e": 2638,
"s": 2609,
"text": "Python pandas-series-methods"
},
{
"code": null,
"e": 2652,
"s": 2638,
"text": "Python-pandas"
},
{
"code": null,
"e": 2659,
"s": 2652,
"text": "Python"
}
]
|
Maximal Clique Problem | Recursive Solution | 01 Nov, 2021
Given a small graph with N nodes and E edges, the task is to find the maximum clique in the given graph. A clique is a complete subgraph of a given graph. This means that all nodes in the said subgraph are directly connected to each other, or there is an edge between any two nodes in the subgraph. The maximal clique is the complete subgraph of a given graph which contains the maximum number of nodes.Examples:
Input: N = 4, edges[][] = {{1, 2}, {2, 3}, {3, 1}, {4, 3}, {4, 1}, {4, 2}} Output: 4Input: N = 5, edges[][] = {{1, 2}, {2, 3}, {3, 1}, {4, 3}, {4, 5}, {5, 3}} Output: 3
Approach: The idea is to use recursion to solve the problem.
When an edge is added to the present list, check that if by adding that edge to the present list, does it still form a clique or not.
The vertices are added until the list does not form a clique. Then, the list is backtracked to find a larger subset which forms a clique.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Stores the verticesint store[MAX], n; // Graphint graph[MAX][MAX]; // Degree of the verticesint d[MAX]; // Function to check if the given set of// vertices in store array is a clique or notbool is_clique(int b){ // Run a loop for all set of edges for (int i = 1; i < b; i++) { for (int j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i]][store[j]] == 0) return false; } return true;} // Function to find all the sizes// of maximal cliquesint maxCliques(int i, int l){ // Maximal clique size int max_ = 0; // Check if any vertices from i+1 // can be inserted for (int j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = max(max_, l); // Check if another edge can be added max_ = max(max_, maxCliques(j, l + 1)); } } return max_;} // Driver codeint main(){ int edges[][2] = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 4, 3 }, { 4, 1 }, { 4, 2 } }; int size = sizeof(edges) / sizeof(edges[0]); n = 4; for (int i = 0; i < size; i++) { graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]]++; d[edges[i][1]]++; } cout << maxCliques(0, 1); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ static int MAX = 100, n; // Stores the verticesstatic int []store = new int[MAX]; // Graphstatic int [][]graph = new int[MAX][MAX]; // Degree of the verticesstatic int []d = new int[MAX]; // Function to check if the given set of// vertices in store array is a clique or notstatic boolean is_clique(int b){ // Run a loop for all set of edges for (int i = 1; i < b; i++) { for (int j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i]][store[j]] == 0) return false; } return true;} // Function to find all the sizes// of maximal cliquesstatic int maxCliques(int i, int l){ // Maximal clique size int max_ = 0; // Check if any vertices from i+1 // can be inserted for (int j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = Math.max(max_, l); // Check if another edge can be added max_ = Math.max(max_, maxCliques(j, l + 1)); } } return max_;} // Driver codepublic static void main(String[] args){ int [][]edges = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 4, 3 }, { 4, 1 }, { 4, 2 } }; int size = edges.length; n = 4; for (int i = 0; i < size; i++) { graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]]++; d[edges[i][1]]++; } System.out.print(maxCliques(0, 1));}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approachMAX = 100;n = 0; # Stores the verticesstore = [0] * MAX; # Graphgraph = [[0 for i in range(MAX)] for j in range(MAX)]; # Degree of the verticesd = [0] * MAX; # Function to check if the given set of# vertices in store array is a clique or notdef is_clique(b): # Run a loop for all set of edges for i in range(1, b): for j in range(i + 1, b): # If any edge is missing if (graph[store[i]][store[j]] == 0): return False; return True; # Function to find all the sizes# of maximal cliquesdef maxCliques(i, l): # Maximal clique size max_ = 0; # Check if any vertices from i+1 # can be inserted for j in range(i + 1, n + 1): # Add the vertex to store store[l] = j; # If the graph is not a clique of size k then # it cannot be a clique by adding another edge if (is_clique(l + 1)): # Update max max_ = max(max_, l); # Check if another edge can be added max_ = max(max_, maxCliques(j, l + 1)); return max_; # Driver codeif __name__ == '__main__': edges = [[ 1, 2 ],[ 2, 3 ],[ 3, 1 ], [ 4, 3 ],[ 4, 1 ],[ 4, 2 ]]; size = len(edges); n = 4; for i in range(size): graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]] += 1; d[edges[i][1]] += 1; print(maxCliques(0, 1)); # This code is contributed by PrinciRaj1992
// C# implementation of the approachusing System; class GFG{ static int MAX = 100, n; // Stores the verticesstatic int []store = new int[MAX]; // Graphstatic int [,]graph = new int[MAX,MAX]; // Degree of the verticesstatic int []d = new int[MAX]; // Function to check if the given set of// vertices in store array is a clique or notstatic bool is_clique(int b){ // Run a loop for all set of edges for (int i = 1; i < b; i++) { for (int j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i],store[j]] == 0) return false; } return true;} // Function to find all the sizes// of maximal cliquesstatic int maxCliques(int i, int l){ // Maximal clique size int max_ = 0; // Check if any vertices from i+1 // can be inserted for (int j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = Math.Max(max_, l); // Check if another edge can be added max_ = Math.Max(max_, maxCliques(j, l + 1)); } } return max_;} // Driver codepublic static void Main(String[] args){ int [,]edges = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 4, 3 }, { 4, 1 }, { 4, 2 } }; int size = edges.GetLength(0); n = 4; for (int i = 0; i < size; i++) { graph[edges[i, 0], edges[i, 1]] = 1; graph[edges[i, 1], edges[i, 0]] = 1; d[edges[i, 0]]++; d[edges[i, 1]]++; } Console.Write(maxCliques(0, 1));}} // This code is contributed by PrinciRaj1992
<script> // Javascript implementation of the approach let MAX = 100, n; // Stores the vertices let store = new Array(MAX); store.fill(0); // Graph let graph = new Array(MAX); for(let i = 0; i < MAX; i++) { graph[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { graph[i][j] = 0; } } // Degree of the vertices let d = new Array(MAX); d.fill(0); // Function to check if the given set of // vertices in store array is a clique or not function is_clique(b) { // Run a loop for all set of edges for (let i = 1; i < b; i++) { for (let j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i]][store[j]] == 0) return false; } return true; } // Function to find all the sizes // of maximal cliques function maxCliques(i, l) { // Maximal clique size let max_ = 0; // Check if any vertices from i+1 // can be inserted for (let j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = Math.max(max_, l); // Check if another edge can be added max_ = Math.max(max_, maxCliques(j, l + 1)); } } return max_; } let edges = [ [ 1, 2 ], [ 2, 3 ], [ 3, 1 ], [ 4, 3 ], [ 4, 1 ], [ 4, 2 ] ]; let size = edges.length; n = 4; for (let i = 0; i < size; i++) { graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]]++; d[edges[i][1]]++; } document.write(maxCliques(0, 1)); // This code is contributed by suresh07.</script>
4
29AjayKumar
princiraj1992
joshi_arihant
suresh07
Technical Scripter 2019
Graph
Recursion
Technical Scripter
Recursion
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Find if there is a path between two vertices in an undirected graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
Detect Cycle in a Directed Graph
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 467,
"s": 52,
"text": "Given a small graph with N nodes and E edges, the task is to find the maximum clique in the given graph. A clique is a complete subgraph of a given graph. This means that all nodes in the said subgraph are directly connected to each other, or there is an edge between any two nodes in the subgraph. The maximal clique is the complete subgraph of a given graph which contains the maximum number of nodes.Examples: "
},
{
"code": null,
"e": 638,
"s": 467,
"text": "Input: N = 4, edges[][] = {{1, 2}, {2, 3}, {3, 1}, {4, 3}, {4, 1}, {4, 2}} Output: 4Input: N = 5, edges[][] = {{1, 2}, {2, 3}, {3, 1}, {4, 3}, {4, 5}, {5, 3}} Output: 3 "
},
{
"code": null,
"e": 703,
"s": 640,
"text": "Approach: The idea is to use recursion to solve the problem. "
},
{
"code": null,
"e": 837,
"s": 703,
"text": "When an edge is added to the present list, check that if by adding that edge to the present list, does it still form a clique or not."
},
{
"code": null,
"e": 975,
"s": 837,
"text": "The vertices are added until the list does not form a clique. Then, the list is backtracked to find a larger subset which forms a clique."
},
{
"code": null,
"e": 1028,
"s": 975,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1032,
"s": 1028,
"text": "C++"
},
{
"code": null,
"e": 1037,
"s": 1032,
"text": "Java"
},
{
"code": null,
"e": 1045,
"s": 1037,
"text": "Python3"
},
{
"code": null,
"e": 1048,
"s": 1045,
"text": "C#"
},
{
"code": null,
"e": 1059,
"s": 1048,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Stores the verticesint store[MAX], n; // Graphint graph[MAX][MAX]; // Degree of the verticesint d[MAX]; // Function to check if the given set of// vertices in store array is a clique or notbool is_clique(int b){ // Run a loop for all set of edges for (int i = 1; i < b; i++) { for (int j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i]][store[j]] == 0) return false; } return true;} // Function to find all the sizes// of maximal cliquesint maxCliques(int i, int l){ // Maximal clique size int max_ = 0; // Check if any vertices from i+1 // can be inserted for (int j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = max(max_, l); // Check if another edge can be added max_ = max(max_, maxCliques(j, l + 1)); } } return max_;} // Driver codeint main(){ int edges[][2] = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 4, 3 }, { 4, 1 }, { 4, 2 } }; int size = sizeof(edges) / sizeof(edges[0]); n = 4; for (int i = 0; i < size; i++) { graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]]++; d[edges[i][1]]++; } cout << maxCliques(0, 1); return 0;}",
"e": 2651,
"s": 1059,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ static int MAX = 100, n; // Stores the verticesstatic int []store = new int[MAX]; // Graphstatic int [][]graph = new int[MAX][MAX]; // Degree of the verticesstatic int []d = new int[MAX]; // Function to check if the given set of// vertices in store array is a clique or notstatic boolean is_clique(int b){ // Run a loop for all set of edges for (int i = 1; i < b; i++) { for (int j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i]][store[j]] == 0) return false; } return true;} // Function to find all the sizes// of maximal cliquesstatic int maxCliques(int i, int l){ // Maximal clique size int max_ = 0; // Check if any vertices from i+1 // can be inserted for (int j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = Math.max(max_, l); // Check if another edge can be added max_ = Math.max(max_, maxCliques(j, l + 1)); } } return max_;} // Driver codepublic static void main(String[] args){ int [][]edges = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 4, 3 }, { 4, 1 }, { 4, 2 } }; int size = edges.length; n = 4; for (int i = 0; i < size; i++) { graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]]++; d[edges[i][1]]++; } System.out.print(maxCliques(0, 1));}} // This code is contributed by 29AjayKumar",
"e": 4376,
"s": 2651,
"text": null
},
{
"code": "# Python3 implementation of the approachMAX = 100;n = 0; # Stores the verticesstore = [0] * MAX; # Graphgraph = [[0 for i in range(MAX)] for j in range(MAX)]; # Degree of the verticesd = [0] * MAX; # Function to check if the given set of# vertices in store array is a clique or notdef is_clique(b): # Run a loop for all set of edges for i in range(1, b): for j in range(i + 1, b): # If any edge is missing if (graph[store[i]][store[j]] == 0): return False; return True; # Function to find all the sizes# of maximal cliquesdef maxCliques(i, l): # Maximal clique size max_ = 0; # Check if any vertices from i+1 # can be inserted for j in range(i + 1, n + 1): # Add the vertex to store store[l] = j; # If the graph is not a clique of size k then # it cannot be a clique by adding another edge if (is_clique(l + 1)): # Update max max_ = max(max_, l); # Check if another edge can be added max_ = max(max_, maxCliques(j, l + 1)); return max_; # Driver codeif __name__ == '__main__': edges = [[ 1, 2 ],[ 2, 3 ],[ 3, 1 ], [ 4, 3 ],[ 4, 1 ],[ 4, 2 ]]; size = len(edges); n = 4; for i in range(size): graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]] += 1; d[edges[i][1]] += 1; print(maxCliques(0, 1)); # This code is contributed by PrinciRaj1992",
"e": 5887,
"s": 4376,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ static int MAX = 100, n; // Stores the verticesstatic int []store = new int[MAX]; // Graphstatic int [,]graph = new int[MAX,MAX]; // Degree of the verticesstatic int []d = new int[MAX]; // Function to check if the given set of// vertices in store array is a clique or notstatic bool is_clique(int b){ // Run a loop for all set of edges for (int i = 1; i < b; i++) { for (int j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i],store[j]] == 0) return false; } return true;} // Function to find all the sizes// of maximal cliquesstatic int maxCliques(int i, int l){ // Maximal clique size int max_ = 0; // Check if any vertices from i+1 // can be inserted for (int j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = Math.Max(max_, l); // Check if another edge can be added max_ = Math.Max(max_, maxCliques(j, l + 1)); } } return max_;} // Driver codepublic static void Main(String[] args){ int [,]edges = { { 1, 2 }, { 2, 3 }, { 3, 1 }, { 4, 3 }, { 4, 1 }, { 4, 2 } }; int size = edges.GetLength(0); n = 4; for (int i = 0; i < size; i++) { graph[edges[i, 0], edges[i, 1]] = 1; graph[edges[i, 1], edges[i, 0]] = 1; d[edges[i, 0]]++; d[edges[i, 1]]++; } Console.Write(maxCliques(0, 1));}} // This code is contributed by PrinciRaj1992",
"e": 7602,
"s": 5887,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach let MAX = 100, n; // Stores the vertices let store = new Array(MAX); store.fill(0); // Graph let graph = new Array(MAX); for(let i = 0; i < MAX; i++) { graph[i] = new Array(MAX); for(let j = 0; j < MAX; j++) { graph[i][j] = 0; } } // Degree of the vertices let d = new Array(MAX); d.fill(0); // Function to check if the given set of // vertices in store array is a clique or not function is_clique(b) { // Run a loop for all set of edges for (let i = 1; i < b; i++) { for (let j = i + 1; j < b; j++) // If any edge is missing if (graph[store[i]][store[j]] == 0) return false; } return true; } // Function to find all the sizes // of maximal cliques function maxCliques(i, l) { // Maximal clique size let max_ = 0; // Check if any vertices from i+1 // can be inserted for (let j = i + 1; j <= n; j++) { // Add the vertex to store store[l] = j; // If the graph is not a clique of size k then // it cannot be a clique by adding another edge if (is_clique(l + 1)) { // Update max max_ = Math.max(max_, l); // Check if another edge can be added max_ = Math.max(max_, maxCliques(j, l + 1)); } } return max_; } let edges = [ [ 1, 2 ], [ 2, 3 ], [ 3, 1 ], [ 4, 3 ], [ 4, 1 ], [ 4, 2 ] ]; let size = edges.length; n = 4; for (let i = 0; i < size; i++) { graph[edges[i][0]][edges[i][1]] = 1; graph[edges[i][1]][edges[i][0]] = 1; d[edges[i][0]]++; d[edges[i][1]]++; } document.write(maxCliques(0, 1)); // This code is contributed by suresh07.</script>",
"e": 9588,
"s": 7602,
"text": null
},
{
"code": null,
"e": 9590,
"s": 9588,
"text": "4"
},
{
"code": null,
"e": 9604,
"s": 9592,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9618,
"s": 9604,
"text": "princiraj1992"
},
{
"code": null,
"e": 9632,
"s": 9618,
"text": "joshi_arihant"
},
{
"code": null,
"e": 9641,
"s": 9632,
"text": "suresh07"
},
{
"code": null,
"e": 9665,
"s": 9641,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 9671,
"s": 9665,
"text": "Graph"
},
{
"code": null,
"e": 9681,
"s": 9671,
"text": "Recursion"
},
{
"code": null,
"e": 9700,
"s": 9681,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9710,
"s": 9700,
"text": "Recursion"
},
{
"code": null,
"e": 9716,
"s": 9710,
"text": "Graph"
},
{
"code": null,
"e": 9814,
"s": 9716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9879,
"s": 9814,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 9947,
"s": 9879,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 10005,
"s": 9947,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 10025,
"s": 10005,
"text": "Topological Sorting"
},
{
"code": null,
"e": 10058,
"s": 10025,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 10118,
"s": 10058,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10203,
"s": 10118,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 10213,
"s": 10203,
"text": "Recursion"
},
{
"code": null,
"e": 10240,
"s": 10213,
"text": "Program for Tower of Hanoi"
}
]
|
Python Tweepy – Getting the screen name of a user | 03 Jul, 2020
In this article we will see how we can get the screen name of a user. Screen name is the username of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their screen name, often in a shortened version. All the screen names must be unique.
Identifying the screen name in the GUI :
In the above mentioned profile, geeksforgeeks is the screen name of the profile.
In order to get the screen name we have to do the following :
Identify the user ID of the profile.Get the User object of the profile using the get_user() method and the user ID.From this object, fetch the screen_name attribute present in it.
Identify the user ID of the profile.
Get the User object of the profile using the get_user() method and the user ID.
From this object, fetch the screen_name attribute present in it.
Example 1: Consider the following profile :The user ID of the above mentioned profile is 57741058.
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the screen namescreen_name = user.screen_name print("The screen name of the user is : " + screen_name)
Output :
The screen name of the user is : geeksforgeeks
Example 2: Consider the following profile :The user ID of the above mentioned profile is 4802800777.
# the ID of the userid = 4802800777 # fetching the useruser = api.get_user(id) # fetching the screen namescreen_name = user.screen_name print("The screen name of the user is : " + screen_name)
Output :
The screen name of the user is : PracticeGfG
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 373,
"s": 28,
"text": "In this article we will see how we can get the screen name of a user. Screen name is the username of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their screen name, often in a shortened version. All the screen names must be unique."
},
{
"code": null,
"e": 414,
"s": 373,
"text": "Identifying the screen name in the GUI :"
},
{
"code": null,
"e": 495,
"s": 414,
"text": "In the above mentioned profile, geeksforgeeks is the screen name of the profile."
},
{
"code": null,
"e": 557,
"s": 495,
"text": "In order to get the screen name we have to do the following :"
},
{
"code": null,
"e": 737,
"s": 557,
"text": "Identify the user ID of the profile.Get the User object of the profile using the get_user() method and the user ID.From this object, fetch the screen_name attribute present in it."
},
{
"code": null,
"e": 774,
"s": 737,
"text": "Identify the user ID of the profile."
},
{
"code": null,
"e": 854,
"s": 774,
"text": "Get the User object of the profile using the get_user() method and the user ID."
},
{
"code": null,
"e": 919,
"s": 854,
"text": "From this object, fetch the screen_name attribute present in it."
},
{
"code": null,
"e": 1018,
"s": 919,
"text": "Example 1: Consider the following profile :The user ID of the above mentioned profile is 57741058."
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the userid = 57741058 # fetching the useruser = api.get_user(id) # fetching the screen namescreen_name = user.screen_name print(\"The screen name of the user is : \" + screen_name)",
"e": 1619,
"s": 1018,
"text": null
},
{
"code": null,
"e": 1628,
"s": 1619,
"text": "Output :"
},
{
"code": null,
"e": 1676,
"s": 1628,
"text": "The screen name of the user is : geeksforgeeks\n"
},
{
"code": null,
"e": 1777,
"s": 1676,
"text": "Example 2: Consider the following profile :The user ID of the above mentioned profile is 4802800777."
},
{
"code": "# the ID of the userid = 4802800777 # fetching the useruser = api.get_user(id) # fetching the screen namescreen_name = user.screen_name print(\"The screen name of the user is : \" + screen_name)",
"e": 1973,
"s": 1777,
"text": null
},
{
"code": null,
"e": 1982,
"s": 1973,
"text": "Output :"
},
{
"code": null,
"e": 2028,
"s": 1982,
"text": "The screen name of the user is : PracticeGfG\n"
},
{
"code": null,
"e": 2042,
"s": 2028,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 2049,
"s": 2042,
"text": "Python"
}
]
|
MySQL - CREATE TRIGGER Statement | Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.
Triggers are, in fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
You can create a trigger using the CREATE TRIGGER Statement.
Following is the syntax of the MySQL CREATE TRIGGER Statement.
CREATE TRIGGER trigger_name
trigger_time trigger_event
ON table_name FOR EACH ROW
BEGIN
...
END;
Where, Trigger_name is the name of the trigger you need to create, Trigger_time is the time of trigger activation, Trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked, Table_name is the name of the table to which the trigger is associated with.
Assume we have created a table with name student as shown below −
mysql> Create table Student(Name Varchar(35), age INT, Score INT);
Query OK, 0 rows affected (1.81 sec)
Following query creates a trigger, this will set the score value 0 if you enter a value that is less than 0 as score.
mysql> DELIMITER //
mysql> Create Trigger sample_trigger BEFORE INSERT ON student FOR EACH ROW
BEGIN
IF NEW.score < 0 THEN SET NEW.score = 0;
END IF; MySQL CREATE TRIGGER Statement
END //
Mysql> DELIMITER ;
Query OK, 0 rows affected (0.44 sec)
If you try to insert records in the student table and if you use a value that is less than 0 as age it will be automatically set to 0.
mysql> INSERT INTO student values ('Jeevan', 22, 8);
mysql> INSERT INTO student values ('Raghav', 26, –3);
mysql> INSERT INTO student values ('Khaleel', 21, –9);
mysql> INSERT INTO student values ('Deva', 30, 9);
If you verify the contents of the student table you can observe that no negative values inserted under the column score −
mysql> SELECT * from student;
+---------+------+-------+
| Name | age | Score |
+---------+------+-------+
| Jeevan | 22 | 8 |
| Raghav | 26 | 0 |
| Khaleel | 21 | 0 |
| Deva | 30 | 9 |
+---------+------+-------+
5 rows in set (0.00 sec)
Following is an example query to create a trigger using the after clause −
mysql> CREATE TRIGGER testTrigger
–> AFTER UPDATE ON Student
–> FOR EACH ROW
–> INSERT INTO Student
–> SET action = 'update',
–> Name = OLD.Name,
–> age = OLD.age,
–> score = OLD.score;
Query OK, 0 rows affected (0.14 sec)
If you verify the contents of the student table you can observe that no negative values inserted under the column score −
mysql> SELECT * FROM Student;
+---------+------+-------+
| Name | age | Score |
+---------+------+-------+
| Jeevan | 22 | 8 |
| Jeevan | 22 | 8 |
| Raghav | 22 | 0 |
| Khaleel | 22 | 0 |
| Deva | 22 | 9 |
+---------+------+-------+
5 rows in set (0.08 sec)
31 Lectures
6 hours
Eduonix Learning Solutions
84 Lectures
5.5 hours
Frahaan Hussain
6 Lectures
3.5 hours
DATAhill Solutions Srinivas Reddy
60 Lectures
10 hours
Vijay Kumar Parvatha Reddy
10 Lectures
1 hours
Harshit Srivastava
25 Lectures
4 hours
Trevoir Williams
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2551,
"s": 2333,
"text": "Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked."
},
{
"code": null,
"e": 2642,
"s": 2551,
"text": "Triggers are, in fact, written to be executed in response to any of the following events −"
},
{
"code": null,
"e": 2710,
"s": 2642,
"text": "A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)"
},
{
"code": null,
"e": 2774,
"s": 2710,
"text": "A database definition (DDL) statement (CREATE, ALTER, or DROP)."
},
{
"code": null,
"e": 2847,
"s": 2774,
"text": "A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN)."
},
{
"code": null,
"e": 2908,
"s": 2847,
"text": "You can create a trigger using the CREATE TRIGGER Statement."
},
{
"code": null,
"e": 2971,
"s": 2908,
"text": "Following is the syntax of the MySQL CREATE TRIGGER Statement."
},
{
"code": null,
"e": 3069,
"s": 2971,
"text": "CREATE TRIGGER trigger_name\ntrigger_time trigger_event\nON table_name FOR EACH ROW\nBEGIN\n...\nEND;\n"
},
{
"code": null,
"e": 3354,
"s": 3069,
"text": "Where, Trigger_name is the name of the trigger you need to create, Trigger_time is the time of trigger activation, Trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked, Table_name is the name of the table to which the trigger is associated with."
},
{
"code": null,
"e": 3420,
"s": 3354,
"text": "Assume we have created a table with name student as shown below −"
},
{
"code": null,
"e": 3525,
"s": 3420,
"text": "mysql> Create table Student(Name Varchar(35), age INT, Score INT);\nQuery OK, 0 rows affected (1.81 sec)\n"
},
{
"code": null,
"e": 3643,
"s": 3525,
"text": "Following query creates a trigger, this will set the score value 0 if you enter a value that is less than 0 as score."
},
{
"code": null,
"e": 3887,
"s": 3643,
"text": "mysql> DELIMITER //\nmysql> Create Trigger sample_trigger BEFORE INSERT ON student FOR EACH ROW\nBEGIN\nIF NEW.score < 0 THEN SET NEW.score = 0;\nEND IF; MySQL CREATE TRIGGER Statement\nEND //\nMysql> DELIMITER ;\nQuery OK, 0 rows affected (0.44 sec)"
},
{
"code": null,
"e": 4022,
"s": 3887,
"text": "If you try to insert records in the student table and if you use a value that is less than 0 as age it will be automatically set to 0."
},
{
"code": null,
"e": 4235,
"s": 4022,
"text": "mysql> INSERT INTO student values ('Jeevan', 22, 8);\nmysql> INSERT INTO student values ('Raghav', 26, –3);\nmysql> INSERT INTO student values ('Khaleel', 21, –9);\nmysql> INSERT INTO student values ('Deva', 30, 9);"
},
{
"code": null,
"e": 4357,
"s": 4235,
"text": "If you verify the contents of the student table you can observe that no negative values inserted under the column score −"
},
{
"code": null,
"e": 4628,
"s": 4357,
"text": "mysql> SELECT * from student;\n+---------+------+-------+\n| Name | age | Score |\n+---------+------+-------+\n| Jeevan | 22 | 8 |\n| Raghav | 26 | 0 |\n| Khaleel | 21 | 0 |\n| Deva | 30 | 9 |\n+---------+------+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 4703,
"s": 4628,
"text": "Following is an example query to create a trigger using the after clause −"
},
{
"code": null,
"e": 4947,
"s": 4703,
"text": "mysql> CREATE TRIGGER testTrigger\n –> AFTER UPDATE ON Student\n –> FOR EACH ROW\n –> INSERT INTO Student\n –> SET action = 'update',\n –> Name = OLD.Name,\n –> age = OLD.age,\n –> score = OLD.score;\nQuery OK, 0 rows affected (0.14 sec)"
},
{
"code": null,
"e": 5069,
"s": 4947,
"text": "If you verify the contents of the student table you can observe that no negative values inserted under the column score −"
},
{
"code": null,
"e": 5367,
"s": 5069,
"text": "mysql> SELECT * FROM Student;\n+---------+------+-------+\n| Name | age | Score |\n+---------+------+-------+\n| Jeevan | 22 | 8 |\n| Jeevan | 22 | 8 |\n| Raghav | 22 | 0 |\n| Khaleel | 22 | 0 |\n| Deva | 22 | 9 |\n+---------+------+-------+\n5 rows in set (0.08 sec)"
},
{
"code": null,
"e": 5400,
"s": 5367,
"text": "\n 31 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5428,
"s": 5400,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5463,
"s": 5428,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5480,
"s": 5463,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5514,
"s": 5480,
"text": "\n 6 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5549,
"s": 5514,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 5583,
"s": 5549,
"text": "\n 60 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 5611,
"s": 5583,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 5644,
"s": 5611,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5664,
"s": 5644,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5697,
"s": 5664,
"text": "\n 25 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5715,
"s": 5697,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 5722,
"s": 5715,
"text": " Print"
},
{
"code": null,
"e": 5733,
"s": 5722,
"text": " Add Notes"
}
]
|
How to Fix “Failed to install the following Android SDK packages as some licenses have not been accepted” Error in Android Studio? - GeeksforGeeks | 31 Mar, 2021
When you download the latest Android SDK tools version using the command line to install SDKs and you just try to build gradle then this error shows up:
Failed to install the following Android SDK packages as some licenses have not been accepted.
platforms;android-27 Android SDK Platform 27
build-tools;27.0.3 Android SDK Build-Tools 27.0.3
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html
You may face this error even after typing y as the answer for the question: Do you accept the license ‘android-sdk-license-c81a61d9’ [y/n]: y. So we need to look at why this error is popping up? Because of this error, we cannot compile our project. So In this article, we will talk about how to solve this error using five different methods. But before directly jumping to solutions first let’s see something about Android SDK.
SDK stands for software development kit or devkit for short. The Android SDK consists of an emulator, development tools, sample projects with source code, and the required libraries to build Android applications. The Android SDK Manager, manages various Android SDK versions, tools, and various other useful packages that you can select and download, to keep your development environment up-to-date.
You need to accept the licenses before building. According to Android SDK docs, you can use the following command depending on the SDK manager location: Docs on –licenses option seems to be missing though. yes | sdkmanager –licenses
Windows:
Step 1: Navigate to %ANDROID_HOME%/tools/bin .
%ANDROID_HOME% is the path to SDK. By default it is located at : C:\Users\UserName\AppData\Local\android\Sdk . If you have moved SDK to another directory location then you can follow below steps :
Search for edit the system environment variables.
Then in the environment variables, you will see ANDROID_HOME.
Navigate to that path in cmd
Step 2:
After successfully navigating just type below command and you are done.
sdkmanager –licenses
GNU/Linux Distributions:
yes | ~/Android/Sdk/tools/bin/sdkmanager –licenses
macOS:
export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home
yes | ~/Library/Android/sdk/tools/bin/sdkmanager –licenses
Flutter Users:
Just type flutter doctor –android-licenses in the terminal and wait for few seconds. You will see “All SDK package licenses accepted” on your screen.
Step 1: In Android Studio go to Tools > SDK Manager.
Step 2: Go to the SDK Tools tab as shown in the below image.
Step 3: Select the Android SDK Command-line Tools (latest) and download by pressing Apply.
in Windows OS go to your sdkmanager path then execute
./sdkmanager.bat –licenses
You can find your sdkmanager at: \Android\tools\bin
IF you don’t know where is your SDK located, then follow these steps:
Open Android Studio
Navigate to Your Project > Files > Setting > Appearance and Behavior > Android SDK
Step 1:Go to your $ANDROID_HOME/tools/bin and fire the cmd and type the below command:
./sdkmanager –licenses
Accept All licenses listed there.
Step 2:
After this just go to the licenses folder in SDK.
Check that it’s having these five files:
android-sdk-license
android-googletv-license
android-sdk-preview-license
google-gdk-license
mips-android-sysimage-license
Step 3:
Give a retry and build again, still, Jenkins giving ‘licenses not accepted” then you have to give full permission to your ‘SDK’ directory and all its parent directories. Here is the command:
sudo chmod -R 777 /opt/
If you having sdk in /opt/ directory.
For Windows users:
Step 1: Go to the location of your sdkmanager.bat file. By default, it is at Android\sdk\tools\bin inside the %LOCALAPPDATA% folder.
Step 2: Open a terminal window there by typing cmd into the title bar. Then go to the above path(Android\sdk\tools\bin as highlighted by the white line in the below image) and type :
sdkmanager.bat –licenses
Accept all licenses with ‘y’.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Retrofit with Kotlin Coroutine in Android
How to Add Image to Drawable Folder in Android Studio?
How to Change the Background Color After Clicking the Button in Android?
How to Retrieve Data from the Firebase Realtime Database in Android?
GridView in Android with Example
ImageView in Android with Example | [
{
"code": null,
"e": 24463,
"s": 24435,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 24616,
"s": 24463,
"text": "When you download the latest Android SDK tools version using the command line to install SDKs and you just try to build gradle then this error shows up:"
},
{
"code": null,
"e": 25076,
"s": 24616,
"text": "Failed to install the following Android SDK packages as some licenses have not been accepted.\nplatforms;android-27 Android SDK Platform 27\nbuild-tools;27.0.3 Android SDK Build-Tools 27.0.3\nTo build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.\nAlternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html"
},
{
"code": null,
"e": 25504,
"s": 25076,
"text": "You may face this error even after typing y as the answer for the question: Do you accept the license ‘android-sdk-license-c81a61d9’ [y/n]: y. So we need to look at why this error is popping up? Because of this error, we cannot compile our project. So In this article, we will talk about how to solve this error using five different methods. But before directly jumping to solutions first let’s see something about Android SDK."
},
{
"code": null,
"e": 25904,
"s": 25504,
"text": "SDK stands for software development kit or devkit for short. The Android SDK consists of an emulator, development tools, sample projects with source code, and the required libraries to build Android applications. The Android SDK Manager, manages various Android SDK versions, tools, and various other useful packages that you can select and download, to keep your development environment up-to-date."
},
{
"code": null,
"e": 26137,
"s": 25904,
"text": "You need to accept the licenses before building. According to Android SDK docs, you can use the following command depending on the SDK manager location: Docs on –licenses option seems to be missing though. yes | sdkmanager –licenses"
},
{
"code": null,
"e": 26146,
"s": 26137,
"text": "Windows:"
},
{
"code": null,
"e": 26194,
"s": 26146,
"text": "Step 1: Navigate to %ANDROID_HOME%/tools/bin . "
},
{
"code": null,
"e": 26392,
"s": 26194,
"text": "%ANDROID_HOME% is the path to SDK. By default it is located at : C:\\Users\\UserName\\AppData\\Local\\android\\Sdk . If you have moved SDK to another directory location then you can follow below steps :"
},
{
"code": null,
"e": 26442,
"s": 26392,
"text": "Search for edit the system environment variables."
},
{
"code": null,
"e": 26504,
"s": 26442,
"text": "Then in the environment variables, you will see ANDROID_HOME."
},
{
"code": null,
"e": 26533,
"s": 26504,
"text": "Navigate to that path in cmd"
},
{
"code": null,
"e": 26541,
"s": 26533,
"text": "Step 2:"
},
{
"code": null,
"e": 26614,
"s": 26541,
"text": "After successfully navigating just type below command and you are done. "
},
{
"code": null,
"e": 26635,
"s": 26614,
"text": "sdkmanager –licenses"
},
{
"code": null,
"e": 26660,
"s": 26635,
"text": "GNU/Linux Distributions:"
},
{
"code": null,
"e": 26711,
"s": 26660,
"text": "yes | ~/Android/Sdk/tools/bin/sdkmanager –licenses"
},
{
"code": null,
"e": 26718,
"s": 26711,
"text": "macOS:"
},
{
"code": null,
"e": 26800,
"s": 26718,
"text": "export JAVA_HOME=/Applications/Android\\ Studio.app/Contents/jre/jdk/Contents/Home"
},
{
"code": null,
"e": 26859,
"s": 26800,
"text": "yes | ~/Library/Android/sdk/tools/bin/sdkmanager –licenses"
},
{
"code": null,
"e": 26874,
"s": 26859,
"text": "Flutter Users:"
},
{
"code": null,
"e": 27024,
"s": 26874,
"text": "Just type flutter doctor –android-licenses in the terminal and wait for few seconds. You will see “All SDK package licenses accepted” on your screen."
},
{
"code": null,
"e": 27079,
"s": 27026,
"text": "Step 1: In Android Studio go to Tools > SDK Manager."
},
{
"code": null,
"e": 27140,
"s": 27079,
"text": "Step 2: Go to the SDK Tools tab as shown in the below image."
},
{
"code": null,
"e": 27231,
"s": 27140,
"text": "Step 3: Select the Android SDK Command-line Tools (latest) and download by pressing Apply."
},
{
"code": null,
"e": 27285,
"s": 27231,
"text": "in Windows OS go to your sdkmanager path then execute"
},
{
"code": null,
"e": 27312,
"s": 27285,
"text": "./sdkmanager.bat –licenses"
},
{
"code": null,
"e": 27364,
"s": 27312,
"text": "You can find your sdkmanager at: \\Android\\tools\\bin"
},
{
"code": null,
"e": 27434,
"s": 27364,
"text": "IF you don’t know where is your SDK located, then follow these steps:"
},
{
"code": null,
"e": 27454,
"s": 27434,
"text": "Open Android Studio"
},
{
"code": null,
"e": 27537,
"s": 27454,
"text": "Navigate to Your Project > Files > Setting > Appearance and Behavior > Android SDK"
},
{
"code": null,
"e": 27624,
"s": 27537,
"text": "Step 1:Go to your $ANDROID_HOME/tools/bin and fire the cmd and type the below command:"
},
{
"code": null,
"e": 27647,
"s": 27624,
"text": "./sdkmanager –licenses"
},
{
"code": null,
"e": 27681,
"s": 27647,
"text": "Accept All licenses listed there."
},
{
"code": null,
"e": 27689,
"s": 27681,
"text": "Step 2:"
},
{
"code": null,
"e": 27739,
"s": 27689,
"text": "After this just go to the licenses folder in SDK."
},
{
"code": null,
"e": 27780,
"s": 27739,
"text": "Check that it’s having these five files:"
},
{
"code": null,
"e": 27800,
"s": 27780,
"text": "android-sdk-license"
},
{
"code": null,
"e": 27825,
"s": 27800,
"text": "android-googletv-license"
},
{
"code": null,
"e": 27853,
"s": 27825,
"text": "android-sdk-preview-license"
},
{
"code": null,
"e": 27872,
"s": 27853,
"text": "google-gdk-license"
},
{
"code": null,
"e": 27902,
"s": 27872,
"text": "mips-android-sysimage-license"
},
{
"code": null,
"e": 27910,
"s": 27902,
"text": "Step 3:"
},
{
"code": null,
"e": 28101,
"s": 27910,
"text": "Give a retry and build again, still, Jenkins giving ‘licenses not accepted” then you have to give full permission to your ‘SDK’ directory and all its parent directories. Here is the command:"
},
{
"code": null,
"e": 28125,
"s": 28101,
"text": "sudo chmod -R 777 /opt/"
},
{
"code": null,
"e": 28163,
"s": 28125,
"text": "If you having sdk in /opt/ directory."
},
{
"code": null,
"e": 28184,
"s": 28163,
"text": "For Windows users: "
},
{
"code": null,
"e": 28317,
"s": 28184,
"text": "Step 1: Go to the location of your sdkmanager.bat file. By default, it is at Android\\sdk\\tools\\bin inside the %LOCALAPPDATA% folder."
},
{
"code": null,
"e": 28500,
"s": 28317,
"text": "Step 2: Open a terminal window there by typing cmd into the title bar. Then go to the above path(Android\\sdk\\tools\\bin as highlighted by the white line in the below image) and type :"
},
{
"code": null,
"e": 28525,
"s": 28500,
"text": "sdkmanager.bat –licenses"
},
{
"code": null,
"e": 28555,
"s": 28525,
"text": "Accept all licenses with ‘y’."
},
{
"code": null,
"e": 28562,
"s": 28555,
"text": "Picked"
},
{
"code": null,
"e": 28570,
"s": 28562,
"text": "Android"
},
{
"code": null,
"e": 28578,
"s": 28570,
"text": "Android"
},
{
"code": null,
"e": 28676,
"s": 28578,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28685,
"s": 28676,
"text": "Comments"
},
{
"code": null,
"e": 28698,
"s": 28685,
"text": "Old Comments"
},
{
"code": null,
"e": 28737,
"s": 28698,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28787,
"s": 28737,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 28838,
"s": 28787,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 28876,
"s": 28838,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 28918,
"s": 28876,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 28973,
"s": 28918,
"text": "How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 29046,
"s": 28973,
"text": "How to Change the Background Color After Clicking the Button in Android?"
},
{
"code": null,
"e": 29115,
"s": 29046,
"text": "How to Retrieve Data from the Firebase Realtime Database in Android?"
},
{
"code": null,
"e": 29148,
"s": 29115,
"text": "GridView in Android with Example"
}
]
|
MySQL | CONVERT( ) Function - GeeksforGeeks | 19 Nov, 2019
The MySQL CONVERT() function is used for converting a value from one datatype to a different datatype. The MySQL CONVERT() function is also used for converting a value from one character set to another character set. It accepts two parameters which are the input value and the type to be converted in.
The CONVERT() function returns the value in the specified datatype or character set.
Syntax for converting datatypes:
CONVERT( input_value, data_type )
Syntax for converting character sets:
CONVERT( input_value USING character_set )
Parameters Used:
input_value – It is used to specify the input value.data_type – It is used to specify the desired datatype to be converted in.character_set – It is used to specify the desired character set to be converted in.
Return Value:The CONVERT() function returns the value in the specified datatype or character set.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
MySQL 4.0
MySQL 3.23
Example-1: Implementing CONVERT() function to convert a value to a CHAR datatype.
SELECT CONVERT(198, CHAR);
Output:
198
Example-2: Implementing CONVERT() function to convert a value to datetime datatype.
SELECT CONVERT('2019-11-19', DATETIME);
Output:
2019-11-19 00:00:00
Example-3: Implementing CONVERT() function to convert a value to UNSIGNED type.
SELECT CONVERT(2-5, UNSIGNED);
Output:
18446744073709551613
Example-4: Implementing CONVERT() function to convert a string value to utf8 character set.
SELECT CONVERT('geeksforgeeks' USING utf8);
Output:
geeksforgeeks
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates | [
{
"code": null,
"e": 23877,
"s": 23849,
"text": "\n19 Nov, 2019"
},
{
"code": null,
"e": 24179,
"s": 23877,
"text": "The MySQL CONVERT() function is used for converting a value from one datatype to a different datatype. The MySQL CONVERT() function is also used for converting a value from one character set to another character set. It accepts two parameters which are the input value and the type to be converted in."
},
{
"code": null,
"e": 24264,
"s": 24179,
"text": "The CONVERT() function returns the value in the specified datatype or character set."
},
{
"code": null,
"e": 24297,
"s": 24264,
"text": "Syntax for converting datatypes:"
},
{
"code": null,
"e": 24331,
"s": 24297,
"text": "CONVERT( input_value, data_type )"
},
{
"code": null,
"e": 24369,
"s": 24331,
"text": "Syntax for converting character sets:"
},
{
"code": null,
"e": 24412,
"s": 24369,
"text": "CONVERT( input_value USING character_set )"
},
{
"code": null,
"e": 24429,
"s": 24412,
"text": "Parameters Used:"
},
{
"code": null,
"e": 24639,
"s": 24429,
"text": "input_value – It is used to specify the input value.data_type – It is used to specify the desired datatype to be converted in.character_set – It is used to specify the desired character set to be converted in."
},
{
"code": null,
"e": 24737,
"s": 24639,
"text": "Return Value:The CONVERT() function returns the value in the specified datatype or character set."
},
{
"code": null,
"e": 24766,
"s": 24737,
"text": "Supported Versions of MySQL:"
},
{
"code": null,
"e": 24776,
"s": 24766,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 24786,
"s": 24776,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 24796,
"s": 24786,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 24806,
"s": 24796,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 24816,
"s": 24806,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 24826,
"s": 24816,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 24836,
"s": 24826,
"text": "MySQL 4.0"
},
{
"code": null,
"e": 24847,
"s": 24836,
"text": "MySQL 3.23"
},
{
"code": null,
"e": 24929,
"s": 24847,
"text": "Example-1: Implementing CONVERT() function to convert a value to a CHAR datatype."
},
{
"code": null,
"e": 24957,
"s": 24929,
"text": "SELECT CONVERT(198, CHAR); "
},
{
"code": null,
"e": 24965,
"s": 24957,
"text": "Output:"
},
{
"code": null,
"e": 24970,
"s": 24965,
"text": "198 "
},
{
"code": null,
"e": 25054,
"s": 24970,
"text": "Example-2: Implementing CONVERT() function to convert a value to datetime datatype."
},
{
"code": null,
"e": 25095,
"s": 25054,
"text": "SELECT CONVERT('2019-11-19', DATETIME); "
},
{
"code": null,
"e": 25103,
"s": 25095,
"text": "Output:"
},
{
"code": null,
"e": 25124,
"s": 25103,
"text": "2019-11-19 00:00:00 "
},
{
"code": null,
"e": 25204,
"s": 25124,
"text": "Example-3: Implementing CONVERT() function to convert a value to UNSIGNED type."
},
{
"code": null,
"e": 25236,
"s": 25204,
"text": "SELECT CONVERT(2-5, UNSIGNED); "
},
{
"code": null,
"e": 25244,
"s": 25236,
"text": "Output:"
},
{
"code": null,
"e": 25266,
"s": 25244,
"text": "18446744073709551613 "
},
{
"code": null,
"e": 25358,
"s": 25266,
"text": "Example-4: Implementing CONVERT() function to convert a string value to utf8 character set."
},
{
"code": null,
"e": 25403,
"s": 25358,
"text": "SELECT CONVERT('geeksforgeeks' USING utf8); "
},
{
"code": null,
"e": 25411,
"s": 25403,
"text": "Output:"
},
{
"code": null,
"e": 25426,
"s": 25411,
"text": "geeksforgeeks "
},
{
"code": null,
"e": 25432,
"s": 25426,
"text": "mysql"
},
{
"code": null,
"e": 25441,
"s": 25432,
"text": "SQLmysql"
},
{
"code": null,
"e": 25445,
"s": 25441,
"text": "SQL"
},
{
"code": null,
"e": 25449,
"s": 25445,
"text": "SQL"
},
{
"code": null,
"e": 25547,
"s": 25449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25556,
"s": 25547,
"text": "Comments"
},
{
"code": null,
"e": 25569,
"s": 25556,
"text": "Old Comments"
},
{
"code": null,
"e": 25635,
"s": 25569,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 25667,
"s": 25635,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 25745,
"s": 25667,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 25762,
"s": 25745,
"text": "SQL using Python"
},
{
"code": null,
"e": 25777,
"s": 25762,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 25843,
"s": 25777,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 25879,
"s": 25843,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 25914,
"s": 25879,
"text": "SQL Query to Delete Duplicate Rows"
}
]
|
Combine Vectors, Matrix or Data Frames by Rows in R Language - rbind() Function - GeeksforGeeks | 04 Jun, 2020
rbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by rows.
Syntax: rbind(x1, x2, ..., deparse.level = 1)
Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
Example 1:
# R program to illustrate# rbind function # Initializing two vectorsx <- 2:7y <- c(2, 5) # Calling rbind() functionrbind(x, y)
Output:
[, 1] [, 2] [, 3] [, 4] [, 5] [, 6]
x 2 3 4 5 6 7
y 2 5 2 5 2 5
Example 2:
# R program to illustrate# rbind function # Initializing a vectorx <- 1:5 # Calling rbind() functionrbind(x, 4)rbind(x, 5, deparse.level = 0)rbind(x, 6, deparse.level = 2)rbind(x, 4, deparse.level = 6)
Output:
[, 1] [, 2] [, 3] [, 4] [, 5]
x 1 2 3 4 5
4 4 4 4 4
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 2 3 4 5
[2, ] 5 5 5 5 5
[, 1] [, 2] [, 3] [, 4] [, 5]
x 1 2 3 4 5
6 6 6 6 6 6
[, 1] [, 2] [, 3] [, 4] [, 5]
[1, ] 1 2 3 4 5
[2, ] 4 4 4 4 4
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 24852,
"s": 24824,
"text": "\n04 Jun, 2020"
},
{
"code": null,
"e": 24950,
"s": 24852,
"text": "rbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by rows."
},
{
"code": null,
"e": 24996,
"s": 24950,
"text": "Syntax: rbind(x1, x2, ..., deparse.level = 1)"
},
{
"code": null,
"e": 25152,
"s": 24996,
"text": "Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1."
},
{
"code": null,
"e": 25163,
"s": 25152,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# rbind function # Initializing two vectorsx <- 2:7y <- c(2, 5) # Calling rbind() functionrbind(x, y)",
"e": 25292,
"s": 25163,
"text": null
},
{
"code": null,
"e": 25300,
"s": 25292,
"text": "Output:"
},
{
"code": null,
"e": 25403,
"s": 25300,
"text": " [, 1] [, 2] [, 3] [, 4] [, 5] [, 6]\nx 2 3 4 5 6 7\ny 2 5 2 5 2 5\n"
},
{
"code": null,
"e": 25414,
"s": 25403,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# rbind function # Initializing a vectorx <- 1:5 # Calling rbind() functionrbind(x, 4)rbind(x, 5, deparse.level = 0)rbind(x, 6, deparse.level = 2)rbind(x, 4, deparse.level = 6)",
"e": 25618,
"s": 25414,
"text": null
},
{
"code": null,
"e": 25626,
"s": 25618,
"text": "Output:"
},
{
"code": null,
"e": 25996,
"s": 25626,
"text": " [, 1] [, 2] [, 3] [, 4] [, 5]\nx 1 2 3 4 5\n 4 4 4 4 4\n\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] 1 2 3 4 5\n[2, ] 5 5 5 5 5\n\n [, 1] [, 2] [, 3] [, 4] [, 5]\nx 1 2 3 4 5\n6 6 6 6 6 6\n\n [, 1] [, 2] [, 3] [, 4] [, 5]\n[1, ] 1 2 3 4 5\n[2, ] 4 4 4 4 4\n"
},
{
"code": null,
"e": 26017,
"s": 25996,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 26035,
"s": 26017,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 26053,
"s": 26035,
"text": "R Object-Function"
},
{
"code": null,
"e": 26071,
"s": 26053,
"text": "R Vector-Function"
},
{
"code": null,
"e": 26082,
"s": 26071,
"text": "R Language"
},
{
"code": null,
"e": 26180,
"s": 26082,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26238,
"s": 26180,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26290,
"s": 26238,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26322,
"s": 26290,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26374,
"s": 26322,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26418,
"s": 26374,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26450,
"s": 26418,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26488,
"s": 26450,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26523,
"s": 26488,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26559,
"s": 26523,
"text": "K-Means Clustering in R Programming"
}
]
|
java.time.LocalDateTime.of() Method Example | The java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) method obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond.
Following is the declaration for java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) method.
public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
year − the year to represent, from MIN_YEAR to MAX_YEAR
year − the year to represent, from MIN_YEAR to MAX_YEAR
month − the month-of-year to represent
month − the month-of-year to represent
dayOfMonth − the day-of-month to represent, from 1 to 31
dayOfMonth − the day-of-month to represent, from 1 to 31
hour − the hour-of-day to represent, from 0 to 23
hour − the hour-of-day to represent, from 0 to 23
minute − the minute-of-hour to represent, from 0 to 59
minute − the minute-of-hour to represent, from 0 to 59
second − the second-of-minute to represent, from 0 to 59
second − the second-of-minute to represent, from 0 to 59
nanoOfSecond − the nano-of-second to represent, from 0 to 999,999,999
nanoOfSecond − the nano-of-second to represent, from 0 to 999,999,999
the local date-time, not null.
DateTimeException − if the value of any field is out of range, or if the day-of-month is invalid for the month-year.
The following example shows the usage of java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second) method.
package com.tutorialspoint;
import java.time.LocalDateTime;
import java.time.Month;
public class LocalDateTimeDemo {
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.of(2017,Month.FEBRUARY,3,6,30,40,50000);
System.out.println(date);
}
}
Let us compile and run the above program, this will produce the following result −
2017-02-03T06:30:40.000050
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2141,
"s": 1915,
"text": "The java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) method obtains an instance of LocalDateTime from year, month, day, hour, minute, second and nanosecond."
},
{
"code": null,
"e": 2300,
"s": 2141,
"text": "Following is the declaration for java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) method."
},
{
"code": null,
"e": 2423,
"s": 2300,
"text": "public static LocalDateTime of(int year, Month month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)\n"
},
{
"code": null,
"e": 2479,
"s": 2423,
"text": "year − the year to represent, from MIN_YEAR to MAX_YEAR"
},
{
"code": null,
"e": 2535,
"s": 2479,
"text": "year − the year to represent, from MIN_YEAR to MAX_YEAR"
},
{
"code": null,
"e": 2574,
"s": 2535,
"text": "month − the month-of-year to represent"
},
{
"code": null,
"e": 2613,
"s": 2574,
"text": "month − the month-of-year to represent"
},
{
"code": null,
"e": 2670,
"s": 2613,
"text": "dayOfMonth − the day-of-month to represent, from 1 to 31"
},
{
"code": null,
"e": 2727,
"s": 2670,
"text": "dayOfMonth − the day-of-month to represent, from 1 to 31"
},
{
"code": null,
"e": 2777,
"s": 2727,
"text": "hour − the hour-of-day to represent, from 0 to 23"
},
{
"code": null,
"e": 2827,
"s": 2777,
"text": "hour − the hour-of-day to represent, from 0 to 23"
},
{
"code": null,
"e": 2882,
"s": 2827,
"text": "minute − the minute-of-hour to represent, from 0 to 59"
},
{
"code": null,
"e": 2937,
"s": 2882,
"text": "minute − the minute-of-hour to represent, from 0 to 59"
},
{
"code": null,
"e": 2994,
"s": 2937,
"text": "second − the second-of-minute to represent, from 0 to 59"
},
{
"code": null,
"e": 3051,
"s": 2994,
"text": "second − the second-of-minute to represent, from 0 to 59"
},
{
"code": null,
"e": 3121,
"s": 3051,
"text": "nanoOfSecond − the nano-of-second to represent, from 0 to 999,999,999"
},
{
"code": null,
"e": 3191,
"s": 3121,
"text": "nanoOfSecond − the nano-of-second to represent, from 0 to 999,999,999"
},
{
"code": null,
"e": 3222,
"s": 3191,
"text": "the local date-time, not null."
},
{
"code": null,
"e": 3339,
"s": 3222,
"text": "DateTimeException − if the value of any field is out of range, or if the day-of-month is invalid for the month-year."
},
{
"code": null,
"e": 3488,
"s": 3339,
"text": "The following example shows the usage of java.time.LocalDateTime.of(int year, Month month, int dayOfMonth, int hour, int minute, int second) method."
},
{
"code": null,
"e": 3776,
"s": 3488,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalDateTime;\nimport java.time.Month;\n\npublic class LocalDateTimeDemo {\n public static void main(String[] args) {\n \n LocalDateTime date = LocalDateTime.of(2017,Month.FEBRUARY,3,6,30,40,50000);\n System.out.println(date); \n }\n}"
},
{
"code": null,
"e": 3859,
"s": 3776,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3887,
"s": 3859,
"text": "2017-02-03T06:30:40.000050\n"
},
{
"code": null,
"e": 3894,
"s": 3887,
"text": " Print"
},
{
"code": null,
"e": 3905,
"s": 3894,
"text": " Add Notes"
}
]
|
Determine if a String is a legal Java Identifier | To determine if a String is a legal Java Identifier, use the Character.isJavaIdentifierPart() and Character.isJavaIdentifierStart() methods.
The java.lang.Character.isJavaIdentifierPart() determines if the character (Unicode code point) may be part of a Java identifier as other than the first character.
A character may be part of a Java identifier if any of the following are true.
it is a letter
it is a currency symbol (such as '$')
it is a connecting punctuation character (such as '_')
it is a digit
it is a numeric letter (such as a Roman numeral character)
The java.lang.Character.isJavaIdentifierStart() determines if the character (Unicode code point) is permissible as the first character in a Java identifier.
A character may start a Java identifier if and only if one of the following conditions is true.
isLetter(ch) returns true
getType(ch) returns LETTER_NUMBER
the referenced character is a currency symbol (such as '$')
the referenced character is a connecting punctuation character (such as '_').
The following is an example that checks for individual characters in a string as well as an entire string. It checks whether the string can be a legal Java Identifier or not.
Live Demo
import java.util.*;
public class Demo {
public static void main(String []args) {
char ch1, ch2;
ch1 = 's';
ch2 = '_';
String str = "jkv_yu";
System.out.println("Checking characters for valid identifier status...");
boolean bool1, bool2;
bool1 = Character.isJavaIdentifierPart(ch1);
bool2 = Character.isJavaIdentifierStart(ch2);
String str1 = ch1 + " may be a part of Java identifier = " + bool2;
String str2 = ch2 + " may start a Java identifier = " + bool2;
System.out.println(str1);
System.out.println(str2);
System.out.println("\nChecking an entire string for valid identifier status...");
System.out.println("The string to be checked: "+str);
if (str.length() == 0 || !Character.isJavaIdentifierStart(str.charAt(0))) {
System.out.println("Not a valid Java Identifier");
}
for (int i = 1; i < str.length(); i++) {
if (!Character.isJavaIdentifierPart(str.charAt(i))) {
System.out.println("Not a valid Java Identifier");
}
}
System.out.println("Valid Java Identifier");
}
}
Checking characters for valid identifier status...
s may be a part of Java identifier = true
_ may start a Java identifier = true
Checking an entire string for valid identifier status...
The string to be checked: jkv_yu
Valid Java Identifier | [
{
"code": null,
"e": 1203,
"s": 1062,
"text": "To determine if a String is a legal Java Identifier, use the Character.isJavaIdentifierPart() and Character.isJavaIdentifierStart() methods."
},
{
"code": null,
"e": 1367,
"s": 1203,
"text": "The java.lang.Character.isJavaIdentifierPart() determines if the character (Unicode code point) may be part of a Java identifier as other than the first character."
},
{
"code": null,
"e": 1446,
"s": 1367,
"text": "A character may be part of a Java identifier if any of the following are true."
},
{
"code": null,
"e": 1461,
"s": 1446,
"text": "it is a letter"
},
{
"code": null,
"e": 1499,
"s": 1461,
"text": "it is a currency symbol (such as '$')"
},
{
"code": null,
"e": 1554,
"s": 1499,
"text": "it is a connecting punctuation character (such as '_')"
},
{
"code": null,
"e": 1568,
"s": 1554,
"text": "it is a digit"
},
{
"code": null,
"e": 1627,
"s": 1568,
"text": "it is a numeric letter (such as a Roman numeral character)"
},
{
"code": null,
"e": 1784,
"s": 1627,
"text": "The java.lang.Character.isJavaIdentifierStart() determines if the character (Unicode code point) is permissible as the first character in a Java identifier."
},
{
"code": null,
"e": 1880,
"s": 1784,
"text": "A character may start a Java identifier if and only if one of the following conditions is true."
},
{
"code": null,
"e": 1906,
"s": 1880,
"text": "isLetter(ch) returns true"
},
{
"code": null,
"e": 1940,
"s": 1906,
"text": "getType(ch) returns LETTER_NUMBER"
},
{
"code": null,
"e": 2000,
"s": 1940,
"text": "the referenced character is a currency symbol (such as '$')"
},
{
"code": null,
"e": 2078,
"s": 2000,
"text": "the referenced character is a connecting punctuation character (such as '_')."
},
{
"code": null,
"e": 2253,
"s": 2078,
"text": "The following is an example that checks for individual characters in a string as well as an entire string. It checks whether the string can be a legal Java Identifier or not."
},
{
"code": null,
"e": 2264,
"s": 2253,
"text": " Live Demo"
},
{
"code": null,
"e": 3398,
"s": 2264,
"text": "import java.util.*;\npublic class Demo {\n public static void main(String []args) {\n char ch1, ch2;\n ch1 = 's';\n ch2 = '_';\n String str = \"jkv_yu\";\n System.out.println(\"Checking characters for valid identifier status...\");\n boolean bool1, bool2;\n bool1 = Character.isJavaIdentifierPart(ch1);\n bool2 = Character.isJavaIdentifierStart(ch2);\n String str1 = ch1 + \" may be a part of Java identifier = \" + bool2;\n String str2 = ch2 + \" may start a Java identifier = \" + bool2;\n System.out.println(str1);\n System.out.println(str2);\n System.out.println(\"\\nChecking an entire string for valid identifier status...\");\n System.out.println(\"The string to be checked: \"+str);\n if (str.length() == 0 || !Character.isJavaIdentifierStart(str.charAt(0))) {\n System.out.println(\"Not a valid Java Identifier\");\n }\n for (int i = 1; i < str.length(); i++) {\n if (!Character.isJavaIdentifierPart(str.charAt(i))) {\n System.out.println(\"Not a valid Java Identifier\");\n }\n }\n System.out.println(\"Valid Java Identifier\");\n }\n}"
},
{
"code": null,
"e": 3641,
"s": 3398,
"text": "Checking characters for valid identifier status...\ns may be a part of Java identifier = true\n_ may start a Java identifier = true\n\nChecking an entire string for valid identifier status...\nThe string to be checked: jkv_yu\nValid Java Identifier"
}
]
|
How to validate if input in input field has boolean value using express-validator ? - GeeksforGeeks | 24 Dec, 2021
In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only boolean value i.e. true or false are allowed. We can also validate these input fields to accept only boolean values using express-validator middleware.
Command to install express-validator:
npm install express-validator
Steps to use express-validator to implement the logic:
Install express-validator middleware.
Create a validator.js file to code all the validation logic.
Validate input by validateInputField: check(input field name) and chain on the validation isBoolean() with ‘ . ‘
Use the validation name(validateInputField) in the routes as a middleware as an array of validations.
Destructure ‘validationResult’ function from express-validator to use it to find any errors.
If error occurs redirect to the same page passing the error information.
If error list is empty, give access to the user for the subsequent request.
Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql.
Example: This example illustrates how to validate an input field to accept only boolean values.
Filename – index.js
javascript
const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateCitizenship } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/data', [validateCitizenship], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {email, name, citizen} = req.body await repo.create({ email, name, 'Indian Citizen': citizen }) res.send('<strong>Data Stored successfully</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})
Filename – repository.js: This file contains all the logic to create a local database and interact with it.
javascript
// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename,'[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')
Filename – form.js: This file contains logic to show HTML form to submit the data.
javascript
const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/data' method='POST'> <div> <div> <label class='label' id='email'>Email</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id='name'>Name</label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='name'> You are citizen of India </label> </div> <input class='input' type='text' name='citizen' placeholder='true or false' for='citizen'> <p class="help is-danger"> ${getError(errors, 'citizen')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `}
Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only boolean values).
javascript
const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateCitizenship : check('citizen') // To delete leading and trailing space .trim() // Validate input field to accept only boolean values .isBoolean() .withMessage('Must be a boolean true or false')}
Filename – package.json
package.json file
Database:
Database
Output:
Invalid boolean value(true is boolean not True)
Invalid boolean value(false is boolean not False)
Invalid boolean value
Response when attempt to submit the form with invalid boolean value (In first three cases)
Valid boolean value
Valid boolean value
Response when attempt to submit the form with valid boolean(true or false) value – (In last two cases)
Database after successful submission of form:
Database after successful submission of form
Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content.
sagartomar9927
surinderdawra388
germanshephered48
Express.js
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js path.resolve() Method
Node.js crypto.createCipheriv() Method
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Node.js fs.readdir() Method
Express.js res.render() Function
Express.js express.Router() Function
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 25067,
"s": 25039,
"text": "\n24 Dec, 2021"
},
{
"code": null,
"e": 25470,
"s": 25067,
"text": "In HTML forms, we often required validation of different types. Validate existing email, validate password length, validate confirm password, validate to allow only integer inputs, these are some examples of validation. In a certain input field, only boolean value i.e. true or false are allowed. We can also validate these input fields to accept only boolean values using express-validator middleware."
},
{
"code": null,
"e": 25508,
"s": 25470,
"text": "Command to install express-validator:"
},
{
"code": null,
"e": 25538,
"s": 25508,
"text": "npm install express-validator"
},
{
"code": null,
"e": 25593,
"s": 25538,
"text": "Steps to use express-validator to implement the logic:"
},
{
"code": null,
"e": 25631,
"s": 25593,
"text": "Install express-validator middleware."
},
{
"code": null,
"e": 25692,
"s": 25631,
"text": "Create a validator.js file to code all the validation logic."
},
{
"code": null,
"e": 25805,
"s": 25692,
"text": "Validate input by validateInputField: check(input field name) and chain on the validation isBoolean() with ‘ . ‘"
},
{
"code": null,
"e": 25907,
"s": 25805,
"text": "Use the validation name(validateInputField) in the routes as a middleware as an array of validations."
},
{
"code": null,
"e": 26000,
"s": 25907,
"text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors."
},
{
"code": null,
"e": 26073,
"s": 26000,
"text": "If error occurs redirect to the same page passing the error information."
},
{
"code": null,
"e": 26149,
"s": 26073,
"text": "If error list is empty, give access to the user for the subsequent request."
},
{
"code": null,
"e": 26315,
"s": 26149,
"text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql."
},
{
"code": null,
"e": 26411,
"s": 26315,
"text": "Example: This example illustrates how to validate an input field to accept only boolean values."
},
{
"code": null,
"e": 26431,
"s": 26411,
"text": "Filename – index.js"
},
{
"code": null,
"e": 26442,
"s": 26431,
"text": "javascript"
},
{
"code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateCitizenship } = require('./validator')const formTemplet = require('./form') const app = express()const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML formapp.get('/', (req, res) => { res.send(formTemplet({}))}) // Post route to handle form submission logic andapp.post( '/data', [validateCitizenship], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(formTemplet({errors})) } const {email, name, citizen} = req.body await repo.create({ email, name, 'Indian Citizen': citizen }) res.send('<strong>Data Stored successfully</strong>')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})",
"e": 27451,
"s": 26442,
"text": null
},
{
"code": null,
"e": 27559,
"s": 27451,
"text": "Filename – repository.js: This file contains all the logic to create a local database and interact with it."
},
{
"code": null,
"e": 27570,
"s": 27559,
"text": "javascript"
},
{
"code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch(err) { // If file not exist it is created // with empty array fs.writeFileSync(this.filename,'[]') } } // Get all existing records async getAll(){ return JSON.parse( await fs.promises.readFile(this.filename, { encoding : 'utf8' }) ) } // Create new record async create(attrs){ const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')",
"e": 28606,
"s": 27570,
"text": null
},
{
"code": null,
"e": 28689,
"s": 28606,
"text": "Filename – form.js: This file contains logic to show HTML form to submit the data."
},
{
"code": null,
"e": 28700,
"s": 28689,
"text": "javascript"
},
{
"code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({errors}) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <form action='/data' method='POST'> <div> <div> <label class='label' id='email'>Email</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id='name'>Name</label> </div> <input class='input' type='text' name='name' placeholder='Name' for='name'> </div> <div> <div> <label class='label' id='name'> You are citizen of India </label> </div> <input class='input' type='text' name='citizen' placeholder='true or false' for='citizen'> <p class=\"help is-danger\"> ${getError(errors, 'citizen')} </p> </div> <div> <button class='button is-primary'> Submit </button> </div> </form> </div> </div> </div> </body> </html> `}",
"e": 30584,
"s": 28700,
"text": null
},
{
"code": null,
"e": 30716,
"s": 30584,
"text": "Filename – validator.js: This file contain all the validation logic(Logic to validate a input field to accept only boolean values)."
},
{
"code": null,
"e": 30727,
"s": 30716,
"text": "javascript"
},
{
"code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateCitizenship : check('citizen') // To delete leading and trailing space .trim() // Validate input field to accept only boolean values .isBoolean() .withMessage('Must be a boolean true or false')}",
"e": 31050,
"s": 30727,
"text": null
},
{
"code": null,
"e": 31074,
"s": 31050,
"text": "Filename – package.json"
},
{
"code": null,
"e": 31092,
"s": 31074,
"text": "package.json file"
},
{
"code": null,
"e": 31102,
"s": 31092,
"text": "Database:"
},
{
"code": null,
"e": 31111,
"s": 31102,
"text": "Database"
},
{
"code": null,
"e": 31119,
"s": 31111,
"text": "Output:"
},
{
"code": null,
"e": 31167,
"s": 31119,
"text": "Invalid boolean value(true is boolean not True)"
},
{
"code": null,
"e": 31217,
"s": 31167,
"text": "Invalid boolean value(false is boolean not False)"
},
{
"code": null,
"e": 31239,
"s": 31217,
"text": "Invalid boolean value"
},
{
"code": null,
"e": 31330,
"s": 31239,
"text": "Response when attempt to submit the form with invalid boolean value (In first three cases)"
},
{
"code": null,
"e": 31350,
"s": 31330,
"text": "Valid boolean value"
},
{
"code": null,
"e": 31370,
"s": 31350,
"text": "Valid boolean value"
},
{
"code": null,
"e": 31473,
"s": 31370,
"text": "Response when attempt to submit the form with valid boolean(true or false) value – (In last two cases)"
},
{
"code": null,
"e": 31519,
"s": 31473,
"text": "Database after successful submission of form:"
},
{
"code": null,
"e": 31564,
"s": 31519,
"text": "Database after successful submission of form"
},
{
"code": null,
"e": 31662,
"s": 31564,
"text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content."
},
{
"code": null,
"e": 31677,
"s": 31662,
"text": "sagartomar9927"
},
{
"code": null,
"e": 31694,
"s": 31677,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31712,
"s": 31694,
"text": "germanshephered48"
},
{
"code": null,
"e": 31723,
"s": 31712,
"text": "Express.js"
},
{
"code": null,
"e": 31736,
"s": 31723,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 31744,
"s": 31736,
"text": "Node.js"
},
{
"code": null,
"e": 31761,
"s": 31744,
"text": "Web Technologies"
},
{
"code": null,
"e": 31859,
"s": 31761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31868,
"s": 31859,
"text": "Comments"
},
{
"code": null,
"e": 31881,
"s": 31868,
"text": "Old Comments"
},
{
"code": null,
"e": 31911,
"s": 31881,
"text": "Node.js path.resolve() Method"
},
{
"code": null,
"e": 31950,
"s": 31911,
"text": "Node.js crypto.createCipheriv() Method"
},
{
"code": null,
"e": 32007,
"s": 31950,
"text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas"
},
{
"code": null,
"e": 32035,
"s": 32007,
"text": "Node.js fs.readdir() Method"
},
{
"code": null,
"e": 32068,
"s": 32035,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 32105,
"s": 32068,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 32150,
"s": 32105,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32210,
"s": 32150,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 32254,
"s": 32210,
"text": "Top 10 Angular Libraries For Web Developers"
}
]
|
MFC - List Box | A list box displays a list of items, such as filenames, that the user can view and select. A List box is represented by CListBox class. In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window.
AddString
Adds a string to a list box.
CharToItem
Override to provide custom WM_CHAR handling for owner-draw list boxes which don't have strings.
CompareItem
Called by the framework to determine the position of a new item in a sorted owner-draw list box.
Create
Creates the Windows list box and attaches it to the CListBox object.
DeleteItem
Called by the framework when the user deletes an item from an owner-draw list box.
DeleteString
Deletes a string from a list box.
Dir
Adds filenames, drives, or both from the current directory to a list box.
DrawItem
Called by the framework when a visualaspect of an owner-draw list box changes.
FindString
Searches for a string in a list box.
FindStringExact
Finds the first list-box string that matches a specified string.
GetAnchorIndex
Retrieves the zero-based index of the current anchor item in a list box.
GetCaretIndex
Determines the index of the item that has the focus rectangle in a multipleselection list box.
GetCount
Returns the number of strings in a list box.
GetCurSel
Returns the zero-based index of the currently selected string in a list box.
GetHorizontalExtent
Returns the width in pixels that a list box can be scrolled horizontally.
GetItemData
Returns the 32-bit value associated with the list-box item.
GetItemDataPtr
Returns a pointer to a list-box item.
GetItemHeight
Determines the height of items in a list box.
GetItemRect
Returns the bounding rectangle of the list-box item as it is currently displayed.
GetListBoxInfo
Retrieves the number of items per column.
GetLocale
Retrieves the locale identifier for a list box.
GetSel
Returns the selection state of a list-box item.
GetSelCount
Returns the number of strings currently selected in a multiple-selection list box.
GetSelItems
Returns the indices of the strings currently selected in a list box.
GetText
Copies a list-box item into a buffer.
GetTextLen
Returns the length in bytes of a list-box item.
GetTopIndex
Returns the index of the first visible string in a list box.
InitStorage
Preallocates blocks of memory for list box items and strings.
InsertString
Inserts a string at a specific location in a list box.
ItemFromPoint
Returns the index of the list-box item nearest a point.
MeasureItem
Called by the framework when an ownerdraw list box is created to determine listbox dimensions.
ResetContent
Clears all the entries from a list box.
SelectString
Searches for and selects a string in a single-selection list box.
SelItemRange
Selects or deselects a range of strings in a multiple-selection list box.
SetAnchorIndex
Sets the anchor in a multiple-selection list box to begin an extended selection.
SetCaretIndex
Sets the focus rectangle to the item at the specified index in a multipleselection list box.
SetColumnWidth
Sets the column width of a multicolumn list box.
SetCurSel
Selects a list-box string.
SetHorizontalExtent
Sets the width in pixels that a list box can be scrolled horizontally.
SetItemData
Sets the 32-bit value associated with the list-box item.
SetItemDataPtr
Sets a pointer to the list-box item.
SetItemHeight
Sets the height of items in a list box.
SetLocale
Sets the locale identifier for a list box.
SetSel
Selects or deselects a list-box item in a multiple-selection list box.
SetTabStops
Sets the tab-stop positions in a list box.
SetTopIndex
Sets the zero-based index of the first visible string in a list box.
VKeyToItem
Override to provide custom WM_KEYDOWN handling for list boxes with the LBS_WANTKEYBOARDINPUT style set.
Here are some mapping entries for Listbox −
Let us look into a simple example of List box by creating a new MFC dialog based application.
Step 1 − Once the project is created, you will see the TODO line which is the Caption of Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT.
Step 2 − Drag List Box from the Toolbox.
Step 3 − Add the control variable for the Text control.
Step 4 − Add the Value variable for the Text control.
Step 5 − Add the control variable for the List Box control.
Step 6 − Add the event handler for the List Box control.
Step 7 − Select the LBN_SELCHANGE from the message type and enter name for the event handler.
Step 8 − Add one function, which will load the list box.
void CMFCListBoxDlg::LoadListBox() {
CString str = _T("");
for (int i = 0; i<10; i++) {
str.Format(_T("Item %d"), i);
m_listBox.AddString(str);
}
}
Step 9 − Call the function from CMFCListBoxDlg::OnInitDialog() as shown in the following code.
BOOL CMFCListBoxDlg::OnInitDialog() {
CDialogEx::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
LoadListBox();
return TRUE; // return TRUE unless you set the focus to a control
}
Step 10 − Here is the event handler implementation. This will display the current selected item from the List Box.
void CMFCListBoxDlg::OnLbnSelchangeList1() {
// TODO: Add your control notification handler code here
m_listBox.GetText(m_listBox.GetCurSel(),m_strItemSelected);
UpdateData(FALSE);
}
Step 11 − When the above code is compiled and executed, you will see the following output.
Step 12 − When you select any item, it will be displayed on the Text Control.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2455,
"s": 2067,
"text": "A list box displays a list of items, such as filenames, that the user can view and select. A List box is represented by CListBox class. In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window."
},
{
"code": null,
"e": 2465,
"s": 2455,
"text": "AddString"
},
{
"code": null,
"e": 2494,
"s": 2465,
"text": "Adds a string to a list box."
},
{
"code": null,
"e": 2505,
"s": 2494,
"text": "CharToItem"
},
{
"code": null,
"e": 2601,
"s": 2505,
"text": "Override to provide custom WM_CHAR handling for owner-draw list boxes which don't have strings."
},
{
"code": null,
"e": 2613,
"s": 2601,
"text": "CompareItem"
},
{
"code": null,
"e": 2710,
"s": 2613,
"text": "Called by the framework to determine the position of a new item in a sorted owner-draw list box."
},
{
"code": null,
"e": 2717,
"s": 2710,
"text": "Create"
},
{
"code": null,
"e": 2786,
"s": 2717,
"text": "Creates the Windows list box and attaches it to the CListBox object."
},
{
"code": null,
"e": 2797,
"s": 2786,
"text": "DeleteItem"
},
{
"code": null,
"e": 2880,
"s": 2797,
"text": "Called by the framework when the user deletes an item from an owner-draw list box."
},
{
"code": null,
"e": 2893,
"s": 2880,
"text": "DeleteString"
},
{
"code": null,
"e": 2927,
"s": 2893,
"text": "Deletes a string from a list box."
},
{
"code": null,
"e": 2931,
"s": 2927,
"text": "Dir"
},
{
"code": null,
"e": 3005,
"s": 2931,
"text": "Adds filenames, drives, or both from the current directory to a list box."
},
{
"code": null,
"e": 3014,
"s": 3005,
"text": "DrawItem"
},
{
"code": null,
"e": 3093,
"s": 3014,
"text": "Called by the framework when a visualaspect of an owner-draw list box changes."
},
{
"code": null,
"e": 3104,
"s": 3093,
"text": "FindString"
},
{
"code": null,
"e": 3141,
"s": 3104,
"text": "Searches for a string in a list box."
},
{
"code": null,
"e": 3157,
"s": 3141,
"text": "FindStringExact"
},
{
"code": null,
"e": 3222,
"s": 3157,
"text": "Finds the first list-box string that matches a specified string."
},
{
"code": null,
"e": 3237,
"s": 3222,
"text": "GetAnchorIndex"
},
{
"code": null,
"e": 3310,
"s": 3237,
"text": "Retrieves the zero-based index of the current anchor item in a list box."
},
{
"code": null,
"e": 3324,
"s": 3310,
"text": "GetCaretIndex"
},
{
"code": null,
"e": 3419,
"s": 3324,
"text": "Determines the index of the item that has the focus rectangle in a multipleselection list box."
},
{
"code": null,
"e": 3428,
"s": 3419,
"text": "GetCount"
},
{
"code": null,
"e": 3473,
"s": 3428,
"text": "Returns the number of strings in a list box."
},
{
"code": null,
"e": 3483,
"s": 3473,
"text": "GetCurSel"
},
{
"code": null,
"e": 3560,
"s": 3483,
"text": "Returns the zero-based index of the currently selected string in a list box."
},
{
"code": null,
"e": 3580,
"s": 3560,
"text": "GetHorizontalExtent"
},
{
"code": null,
"e": 3654,
"s": 3580,
"text": "Returns the width in pixels that a list box can be scrolled horizontally."
},
{
"code": null,
"e": 3666,
"s": 3654,
"text": "GetItemData"
},
{
"code": null,
"e": 3726,
"s": 3666,
"text": "Returns the 32-bit value associated with the list-box item."
},
{
"code": null,
"e": 3741,
"s": 3726,
"text": "GetItemDataPtr"
},
{
"code": null,
"e": 3779,
"s": 3741,
"text": "Returns a pointer to a list-box item."
},
{
"code": null,
"e": 3793,
"s": 3779,
"text": "GetItemHeight"
},
{
"code": null,
"e": 3839,
"s": 3793,
"text": "Determines the height of items in a list box."
},
{
"code": null,
"e": 3851,
"s": 3839,
"text": "GetItemRect"
},
{
"code": null,
"e": 3933,
"s": 3851,
"text": "Returns the bounding rectangle of the list-box item as it is currently displayed."
},
{
"code": null,
"e": 3948,
"s": 3933,
"text": "GetListBoxInfo"
},
{
"code": null,
"e": 3990,
"s": 3948,
"text": "Retrieves the number of items per column."
},
{
"code": null,
"e": 4000,
"s": 3990,
"text": "GetLocale"
},
{
"code": null,
"e": 4048,
"s": 4000,
"text": "Retrieves the locale identifier for a list box."
},
{
"code": null,
"e": 4055,
"s": 4048,
"text": "GetSel"
},
{
"code": null,
"e": 4103,
"s": 4055,
"text": "Returns the selection state of a list-box item."
},
{
"code": null,
"e": 4115,
"s": 4103,
"text": "GetSelCount"
},
{
"code": null,
"e": 4198,
"s": 4115,
"text": "Returns the number of strings currently selected in a multiple-selection list box."
},
{
"code": null,
"e": 4210,
"s": 4198,
"text": "GetSelItems"
},
{
"code": null,
"e": 4279,
"s": 4210,
"text": "Returns the indices of the strings currently selected in a list box."
},
{
"code": null,
"e": 4287,
"s": 4279,
"text": "GetText"
},
{
"code": null,
"e": 4325,
"s": 4287,
"text": "Copies a list-box item into a buffer."
},
{
"code": null,
"e": 4336,
"s": 4325,
"text": "GetTextLen"
},
{
"code": null,
"e": 4384,
"s": 4336,
"text": "Returns the length in bytes of a list-box item."
},
{
"code": null,
"e": 4396,
"s": 4384,
"text": "GetTopIndex"
},
{
"code": null,
"e": 4457,
"s": 4396,
"text": "Returns the index of the first visible string in a list box."
},
{
"code": null,
"e": 4469,
"s": 4457,
"text": "InitStorage"
},
{
"code": null,
"e": 4531,
"s": 4469,
"text": "Preallocates blocks of memory for list box items and strings."
},
{
"code": null,
"e": 4544,
"s": 4531,
"text": "InsertString"
},
{
"code": null,
"e": 4599,
"s": 4544,
"text": "Inserts a string at a specific location in a list box."
},
{
"code": null,
"e": 4613,
"s": 4599,
"text": "ItemFromPoint"
},
{
"code": null,
"e": 4669,
"s": 4613,
"text": "Returns the index of the list-box item nearest a point."
},
{
"code": null,
"e": 4681,
"s": 4669,
"text": "MeasureItem"
},
{
"code": null,
"e": 4776,
"s": 4681,
"text": "Called by the framework when an ownerdraw list box is created to determine listbox dimensions."
},
{
"code": null,
"e": 4789,
"s": 4776,
"text": "ResetContent"
},
{
"code": null,
"e": 4829,
"s": 4789,
"text": "Clears all the entries from a list box."
},
{
"code": null,
"e": 4842,
"s": 4829,
"text": "SelectString"
},
{
"code": null,
"e": 4908,
"s": 4842,
"text": "Searches for and selects a string in a single-selection list box."
},
{
"code": null,
"e": 4921,
"s": 4908,
"text": "SelItemRange"
},
{
"code": null,
"e": 4995,
"s": 4921,
"text": "Selects or deselects a range of strings in a multiple-selection list box."
},
{
"code": null,
"e": 5010,
"s": 4995,
"text": "SetAnchorIndex"
},
{
"code": null,
"e": 5091,
"s": 5010,
"text": "Sets the anchor in a multiple-selection list box to begin an extended selection."
},
{
"code": null,
"e": 5105,
"s": 5091,
"text": "SetCaretIndex"
},
{
"code": null,
"e": 5198,
"s": 5105,
"text": "Sets the focus rectangle to the item at the specified index in a multipleselection list box."
},
{
"code": null,
"e": 5213,
"s": 5198,
"text": "SetColumnWidth"
},
{
"code": null,
"e": 5262,
"s": 5213,
"text": "Sets the column width of a multicolumn list box."
},
{
"code": null,
"e": 5272,
"s": 5262,
"text": "SetCurSel"
},
{
"code": null,
"e": 5299,
"s": 5272,
"text": "Selects a list-box string."
},
{
"code": null,
"e": 5319,
"s": 5299,
"text": "SetHorizontalExtent"
},
{
"code": null,
"e": 5390,
"s": 5319,
"text": "Sets the width in pixels that a list box can be scrolled horizontally."
},
{
"code": null,
"e": 5402,
"s": 5390,
"text": "SetItemData"
},
{
"code": null,
"e": 5459,
"s": 5402,
"text": "Sets the 32-bit value associated with the list-box item."
},
{
"code": null,
"e": 5474,
"s": 5459,
"text": "SetItemDataPtr"
},
{
"code": null,
"e": 5511,
"s": 5474,
"text": "Sets a pointer to the list-box item."
},
{
"code": null,
"e": 5525,
"s": 5511,
"text": "SetItemHeight"
},
{
"code": null,
"e": 5565,
"s": 5525,
"text": "Sets the height of items in a list box."
},
{
"code": null,
"e": 5575,
"s": 5565,
"text": "SetLocale"
},
{
"code": null,
"e": 5618,
"s": 5575,
"text": "Sets the locale identifier for a list box."
},
{
"code": null,
"e": 5625,
"s": 5618,
"text": "SetSel"
},
{
"code": null,
"e": 5696,
"s": 5625,
"text": "Selects or deselects a list-box item in a multiple-selection list box."
},
{
"code": null,
"e": 5708,
"s": 5696,
"text": "SetTabStops"
},
{
"code": null,
"e": 5751,
"s": 5708,
"text": "Sets the tab-stop positions in a list box."
},
{
"code": null,
"e": 5763,
"s": 5751,
"text": "SetTopIndex"
},
{
"code": null,
"e": 5832,
"s": 5763,
"text": "Sets the zero-based index of the first visible string in a list box."
},
{
"code": null,
"e": 5843,
"s": 5832,
"text": "VKeyToItem"
},
{
"code": null,
"e": 5947,
"s": 5843,
"text": "Override to provide custom WM_KEYDOWN handling for list boxes with the LBS_WANTKEYBOARDINPUT style set."
},
{
"code": null,
"e": 5991,
"s": 5947,
"text": "Here are some mapping entries for Listbox −"
},
{
"code": null,
"e": 6085,
"s": 5991,
"text": "Let us look into a simple example of List box by creating a new MFC dialog based application."
},
{
"code": null,
"e": 6241,
"s": 6085,
"text": "Step 1 − Once the project is created, you will see the TODO line which is the Caption of Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT."
},
{
"code": null,
"e": 6282,
"s": 6241,
"text": "Step 2 − Drag List Box from the Toolbox."
},
{
"code": null,
"e": 6338,
"s": 6282,
"text": "Step 3 − Add the control variable for the Text control."
},
{
"code": null,
"e": 6392,
"s": 6338,
"text": "Step 4 − Add the Value variable for the Text control."
},
{
"code": null,
"e": 6452,
"s": 6392,
"text": "Step 5 − Add the control variable for the List Box control."
},
{
"code": null,
"e": 6509,
"s": 6452,
"text": "Step 6 − Add the event handler for the List Box control."
},
{
"code": null,
"e": 6603,
"s": 6509,
"text": "Step 7 − Select the LBN_SELCHANGE from the message type and enter name for the event handler."
},
{
"code": null,
"e": 6660,
"s": 6603,
"text": "Step 8 − Add one function, which will load the list box."
},
{
"code": null,
"e": 6830,
"s": 6660,
"text": "void CMFCListBoxDlg::LoadListBox() {\n CString str = _T(\"\");\n for (int i = 0; i<10; i++) {\n\n str.Format(_T(\"Item %d\"), i);\n m_listBox.AddString(str);\n }\n}"
},
{
"code": null,
"e": 6925,
"s": 6830,
"text": "Step 9 − Call the function from CMFCListBoxDlg::OnInitDialog() as shown in the following code."
},
{
"code": null,
"e": 7357,
"s": 6925,
"text": "BOOL CMFCListBoxDlg::OnInitDialog() {\n CDialogEx::OnInitDialog();\n\n // Set the icon for this dialog. The framework does this automatically\n // when the application's main window is not a dialog\n SetIcon(m_hIcon, TRUE); // Set big icon\n SetIcon(m_hIcon, FALSE); // Set small icon\n\n // TODO: Add extra initialization here\n LoadListBox();\n return TRUE; // return TRUE unless you set the focus to a control\n}"
},
{
"code": null,
"e": 7472,
"s": 7357,
"text": "Step 10 − Here is the event handler implementation. This will display the current selected item from the List Box."
},
{
"code": null,
"e": 7664,
"s": 7472,
"text": "void CMFCListBoxDlg::OnLbnSelchangeList1() {\n // TODO: Add your control notification handler code here\n m_listBox.GetText(m_listBox.GetCurSel(),m_strItemSelected);\n UpdateData(FALSE);\n}"
},
{
"code": null,
"e": 7755,
"s": 7664,
"text": "Step 11 − When the above code is compiled and executed, you will see the following output."
},
{
"code": null,
"e": 7833,
"s": 7755,
"text": "Step 12 − When you select any item, it will be displayed on the Text Control."
},
{
"code": null,
"e": 7840,
"s": 7833,
"text": " Print"
},
{
"code": null,
"e": 7851,
"s": 7840,
"text": " Add Notes"
}
]
|
Interesting Queries | Practice | GeeksforGeeks | Given an array nums of n elements and q queries . Each query consists of two integers l and r . You task is to find the number of elements of nums[] in range [l,r] which occur atleast k times.
Example 1:
Input: nums = {1,1,2,1,3}, Queries = {{1,5},
{2,4}}, k = 1
Output: {3,2}
Explanation: For the 1st query, from l=1 to r=5
1, 2 and 3 have the frequency atleast 1.
For the second query, from l=2 to r=4, 1 and 2 have
the frequency atleast 1.
Your Task:
Your task is to complete the function solveQueries() which takes nums, Queries and k as input parameter and returns a list containg the answer for each query.
Expected Time Complexity: O(n*sqrt(n)*log(n))
Expected Space Compelxity: O(n)
Constraints:
1 <= n, no of Queries, k <= 104
1 <= nums[i] <= 103
1 <= Queries[i][0] <= Queries[i][1] <= n
0
Sachin Poonia9 months ago
Sachin Poonia
Solution in java should also be given
0
Saarth Vikram Jhaveri11 months ago
Saarth Vikram Jhaveri
i don't know whats going wrong here, my code works completely fine in my c++ compiler , whereas here it gives different answer, please fix it asap! https://p.ip.fi/MzyO
0
aditya anand1 year ago
aditya anand
Please correct python driver code, when submitting my code gives wrong ans(only problem is spaces) but gives correct ans in custom test.
0
Shreyansh Shukla1 year ago
Shreyansh Shukla
even i saw the solution none of them contained the given structure at the starting of problem!!!every one is typing a fresh code??
then why such WRONG modification for us!!such that it gives different answer!!!!
0
Shreyansh Shukla1 year ago
Shreyansh Shukla
please correct the test case of this question 2 5 310 42 22 22 22 21 1
it shows different output for expected one and different output for submit button !!!!!What the heck is this!!so irresponsible!!!@@vikranttandon:disqus
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": 433,
"s": 238,
"text": "Given an array nums of n elements and q queries . Each query consists of two integers l and r . You task is to find the number of elements of nums[] in range [l,r] which occur atleast k times.\n "
},
{
"code": null,
"e": 444,
"s": 433,
"text": "Example 1:"
},
{
"code": null,
"e": 685,
"s": 444,
"text": "Input: nums = {1,1,2,1,3}, Queries = {{1,5},\n{2,4}}, k = 1\nOutput: {3,2}\nExplanation: For the 1st query, from l=1 to r=5\n1, 2 and 3 have the frequency atleast 1.\nFor the second query, from l=2 to r=4, 1 and 2 have \nthe frequency atleast 1.\n"
},
{
"code": null,
"e": 698,
"s": 687,
"text": "Your Task:"
},
{
"code": null,
"e": 859,
"s": 698,
"text": "Your task is to complete the function solveQueries() which takes nums, Queries and k as input parameter and returns a list containg the answer for each query.\n "
},
{
"code": null,
"e": 939,
"s": 859,
"text": "Expected Time Complexity: O(n*sqrt(n)*log(n))\nExpected Space Compelxity: O(n)\n "
},
{
"code": null,
"e": 1004,
"s": 939,
"text": "Constraints:\n1 <= n, no of Queries, k <= 104\n1 <= nums[i] <= 103"
},
{
"code": null,
"e": 1045,
"s": 1004,
"text": "1 <= Queries[i][0] <= Queries[i][1] <= n"
},
{
"code": null,
"e": 1047,
"s": 1045,
"text": "0"
},
{
"code": null,
"e": 1073,
"s": 1047,
"text": "Sachin Poonia9 months ago"
},
{
"code": null,
"e": 1087,
"s": 1073,
"text": "Sachin Poonia"
},
{
"code": null,
"e": 1125,
"s": 1087,
"text": "Solution in java should also be given"
},
{
"code": null,
"e": 1127,
"s": 1125,
"text": "0"
},
{
"code": null,
"e": 1162,
"s": 1127,
"text": "Saarth Vikram Jhaveri11 months ago"
},
{
"code": null,
"e": 1184,
"s": 1162,
"text": "Saarth Vikram Jhaveri"
},
{
"code": null,
"e": 1353,
"s": 1184,
"text": "i don't know whats going wrong here, my code works completely fine in my c++ compiler , whereas here it gives different answer, please fix it asap! https://p.ip.fi/MzyO"
},
{
"code": null,
"e": 1355,
"s": 1353,
"text": "0"
},
{
"code": null,
"e": 1378,
"s": 1355,
"text": "aditya anand1 year ago"
},
{
"code": null,
"e": 1391,
"s": 1378,
"text": "aditya anand"
},
{
"code": null,
"e": 1528,
"s": 1391,
"text": "Please correct python driver code, when submitting my code gives wrong ans(only problem is spaces) but gives correct ans in custom test."
},
{
"code": null,
"e": 1530,
"s": 1528,
"text": "0"
},
{
"code": null,
"e": 1557,
"s": 1530,
"text": "Shreyansh Shukla1 year ago"
},
{
"code": null,
"e": 1574,
"s": 1557,
"text": "Shreyansh Shukla"
},
{
"code": null,
"e": 1705,
"s": 1574,
"text": "even i saw the solution none of them contained the given structure at the starting of problem!!!every one is typing a fresh code??"
},
{
"code": null,
"e": 1786,
"s": 1705,
"text": "then why such WRONG modification for us!!such that it gives different answer!!!!"
},
{
"code": null,
"e": 1788,
"s": 1786,
"text": "0"
},
{
"code": null,
"e": 1815,
"s": 1788,
"text": "Shreyansh Shukla1 year ago"
},
{
"code": null,
"e": 1832,
"s": 1815,
"text": "Shreyansh Shukla"
},
{
"code": null,
"e": 1903,
"s": 1832,
"text": "please correct the test case of this question 2 5 310 42 22 22 22 21 1"
},
{
"code": null,
"e": 2055,
"s": 1903,
"text": "it shows different output for expected one and different output for submit button !!!!!What the heck is this!!so irresponsible!!!@@vikranttandon:disqus"
},
{
"code": null,
"e": 2201,
"s": 2055,
"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": 2237,
"s": 2201,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2247,
"s": 2237,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2257,
"s": 2247,
"text": "\nContest\n"
},
{
"code": null,
"e": 2320,
"s": 2257,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2468,
"s": 2320,
"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": 2676,
"s": 2468,
"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": 2782,
"s": 2676,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
]
|
PCA Explained with Dynamic Plotly Visualizations | by Soner Yıldırım | Towards Data Science | PCA (Principal component analysis) is an unsupervised learning algorithm that finds the relations among features within a dataset. It is also widely used as a preprocessing step for supervised learning algorithms.
The aim of using PCA is to reduce the number of features by finding principal components that explain the variance within the dataset as much as possible. The principal components are linear combinations of the features of original dataset.
The advantage of PCA is that a significant amount of variance of the original dataset is retained using much smaller number of features than the original dataset. Principal components are ordered according to the amount of variance they represent.
In this post, we will first implement a PCA algorithm and then create dynamic visualizations with Plotly to explain the idea behind the PCA more clearly.
This post is more of a practical one. If you want to go deeper on how PCA actually works, here is more detailed post on the theoretical side.
Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js) and it offers a high-level API (plotly express) and a low level API (graph objects) to create dynamic and interactive visualizations. With plotly express, we can create a nice plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control on what we create.
Let’s start with importing the related libraries:
import numpy as npimport pandas as pdfrom sklearn.decomposition import PCAfrom sklearn.datasets import load_breast_cancer
I will use the breast cancer dataset which contains 30 features and a target variable indicating whether the cell is malignant or benign. To simplify the visualizations, I will randomly select 5 features.
dataset = load_breast_cancer()X, y = load_breast_cancer(return_X_y = True)df = pd.DataFrame(X, columns=dataset.feature_names)df = df.sample(n=5, axis=1)df['target'] = ydf.head()
Let’s create a scatter_matrix that displays scatter plots of feature pairs. We get an overview of how successful pairs of features are at separating the target class.
import plotly.express as pxfig = px.scatter_matrix(df, dimensions=df.columns[:-1], color='target', title='Scatter Matrix of Features', height=800)
Some features are better at differentiating the target class.
Let’s apply PCA to represent these 5 features with 2 principal components.
X = df.drop(['target'], axis=1)#Normalizefrom sklearn.preprocessing import StandardScalersc = StandardScaler()X_normalized = sc.fit_transform(X)#Principal componentspca = PCA(n_components=2)components = pca.fit_transform(X_normalized)
One attribute of the PCA class is the explained_variance_ratio_ which, as the name suggests, tells us how much of the total variance is explained by each principal component.
pca.explained_variance_ratio_array([0.69369623, 0.20978844])
%90 of the variance in the original dataset is explained by 2 principal components.
Let’s create a scatter matrix with the principal components.
labels = {str(i): f"PC {i+1} ({var:.1f}%)" for i, var in enumerate(pca.explained_variance_ratio_ * 100)}fig = px.scatter_matrix(components, labels=labels, dimensions=range(2), color=df['target'])fig.show()
Plotly also provides 3D scatter plots which can be useful when we have 3 principal components. To experiment 3D plots, we first need to apply a PCA to our dataset again to create 3 principal components.
pca = PCA(n_components=3)components = pca.fit_transform(X_normalized)
We can now create a 3D scatter plot.
var = pca.explained_variance_ratio_.sum()fig = px.scatter_3d(components, x=0, y=1, z=2, color=df['target'],title=f'Total Explained Variance: {var}',labels={'0':'PC1', '1':'PC2', '2':'PC3'})fig.show()
The total explained variance with two principal components was %90. It has increased by %7 when the third principal component is added.
We have used a subset of the breast cancer dataset for demonstration purposes. Feel free to use the entire set and see how much of the total variance is explained by the principal components.
Plotting the principal components will provide insight into the structure within the dataset and the relationships among features.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 386,
"s": 172,
"text": "PCA (Principal component analysis) is an unsupervised learning algorithm that finds the relations among features within a dataset. It is also widely used as a preprocessing step for supervised learning algorithms."
},
{
"code": null,
"e": 627,
"s": 386,
"text": "The aim of using PCA is to reduce the number of features by finding principal components that explain the variance within the dataset as much as possible. The principal components are linear combinations of the features of original dataset."
},
{
"code": null,
"e": 875,
"s": 627,
"text": "The advantage of PCA is that a significant amount of variance of the original dataset is retained using much smaller number of features than the original dataset. Principal components are ordered according to the amount of variance they represent."
},
{
"code": null,
"e": 1029,
"s": 875,
"text": "In this post, we will first implement a PCA algorithm and then create dynamic visualizations with Plotly to explain the idea behind the PCA more clearly."
},
{
"code": null,
"e": 1171,
"s": 1029,
"text": "This post is more of a practical one. If you want to go deeper on how PCA actually works, here is more detailed post on the theoretical side."
},
{
"code": null,
"e": 1587,
"s": 1171,
"text": "Plotly Python (plotly.py) is an open-source plotting library built on plotly javascript (plotly.js) and it offers a high-level API (plotly express) and a low level API (graph objects) to create dynamic and interactive visualizations. With plotly express, we can create a nice plot with very few lines of code. On the other hand, we need to write more code with graph objects but have more control on what we create."
},
{
"code": null,
"e": 1637,
"s": 1587,
"text": "Let’s start with importing the related libraries:"
},
{
"code": null,
"e": 1759,
"s": 1637,
"text": "import numpy as npimport pandas as pdfrom sklearn.decomposition import PCAfrom sklearn.datasets import load_breast_cancer"
},
{
"code": null,
"e": 1964,
"s": 1759,
"text": "I will use the breast cancer dataset which contains 30 features and a target variable indicating whether the cell is malignant or benign. To simplify the visualizations, I will randomly select 5 features."
},
{
"code": null,
"e": 2142,
"s": 1964,
"text": "dataset = load_breast_cancer()X, y = load_breast_cancer(return_X_y = True)df = pd.DataFrame(X, columns=dataset.feature_names)df = df.sample(n=5, axis=1)df['target'] = ydf.head()"
},
{
"code": null,
"e": 2309,
"s": 2142,
"text": "Let’s create a scatter_matrix that displays scatter plots of feature pairs. We get an overview of how successful pairs of features are at separating the target class."
},
{
"code": null,
"e": 2456,
"s": 2309,
"text": "import plotly.express as pxfig = px.scatter_matrix(df, dimensions=df.columns[:-1], color='target', title='Scatter Matrix of Features', height=800)"
},
{
"code": null,
"e": 2518,
"s": 2456,
"text": "Some features are better at differentiating the target class."
},
{
"code": null,
"e": 2593,
"s": 2518,
"text": "Let’s apply PCA to represent these 5 features with 2 principal components."
},
{
"code": null,
"e": 2828,
"s": 2593,
"text": "X = df.drop(['target'], axis=1)#Normalizefrom sklearn.preprocessing import StandardScalersc = StandardScaler()X_normalized = sc.fit_transform(X)#Principal componentspca = PCA(n_components=2)components = pca.fit_transform(X_normalized)"
},
{
"code": null,
"e": 3003,
"s": 2828,
"text": "One attribute of the PCA class is the explained_variance_ratio_ which, as the name suggests, tells us how much of the total variance is explained by each principal component."
},
{
"code": null,
"e": 3064,
"s": 3003,
"text": "pca.explained_variance_ratio_array([0.69369623, 0.20978844])"
},
{
"code": null,
"e": 3148,
"s": 3064,
"text": "%90 of the variance in the original dataset is explained by 2 principal components."
},
{
"code": null,
"e": 3209,
"s": 3148,
"text": "Let’s create a scatter matrix with the principal components."
},
{
"code": null,
"e": 3415,
"s": 3209,
"text": "labels = {str(i): f\"PC {i+1} ({var:.1f}%)\" for i, var in enumerate(pca.explained_variance_ratio_ * 100)}fig = px.scatter_matrix(components, labels=labels, dimensions=range(2), color=df['target'])fig.show()"
},
{
"code": null,
"e": 3618,
"s": 3415,
"text": "Plotly also provides 3D scatter plots which can be useful when we have 3 principal components. To experiment 3D plots, we first need to apply a PCA to our dataset again to create 3 principal components."
},
{
"code": null,
"e": 3688,
"s": 3618,
"text": "pca = PCA(n_components=3)components = pca.fit_transform(X_normalized)"
},
{
"code": null,
"e": 3725,
"s": 3688,
"text": "We can now create a 3D scatter plot."
},
{
"code": null,
"e": 3925,
"s": 3725,
"text": "var = pca.explained_variance_ratio_.sum()fig = px.scatter_3d(components, x=0, y=1, z=2, color=df['target'],title=f'Total Explained Variance: {var}',labels={'0':'PC1', '1':'PC2', '2':'PC3'})fig.show()"
},
{
"code": null,
"e": 4061,
"s": 3925,
"text": "The total explained variance with two principal components was %90. It has increased by %7 when the third principal component is added."
},
{
"code": null,
"e": 4253,
"s": 4061,
"text": "We have used a subset of the breast cancer dataset for demonstration purposes. Feel free to use the entire set and see how much of the total variance is explained by the principal components."
},
{
"code": null,
"e": 4384,
"s": 4253,
"text": "Plotting the principal components will provide insight into the structure within the dataset and the relationships among features."
}
]
|
A guide to an efficient way to build neural network architectures- Part II: Hyper-parameter selection and tuning for Convolutional Neural Networks using Hyperas on Fashion-MNIST | by Shashank Ramesh | Towards Data Science | This article is a continuation to the article linked below which deals with the need for hyper-parameter optimization and how to do hyper-parameter selection and optimization using Hyperas for Dense Neural Networks (Multi-Layer Perceptrons)
medium.com
In the current article we will continue from where we left off in part-I and would try to solve the same problem, the image classification task of the Fashion-MNIST data-set using Convolutional Neural Networks(CNN).
The CNNs have several different filters/kernels consisting of trainable parameters which can convolve on a given image spatially to detect features like edges and shapes. These high number of filters essentially learn to capture spatial features from the image based on the learned weights through back propagation and stacked layers of filters can be used to detect complex spatial shapes from the spatial features at every subsequent level. Hence they can successfully boil down a given image into a highly abstracted representation which is easy for predicting.
In Dense networks we try to find patterns in pixel values given as input for eg. if pixel number 25 and 26 are greater than a certain value it might belong to a certain class and a few complex variations of the same. This might easily fail if we can have objects anywhere in the image and not necessarily centered like in the MNIST or to a certain extent also in the Fashion-MNIST data.
RNNs on the other hand find sequences in data and an edge or a shape too can be thought of as a sequence of pixel values but the problem lies in the fact that they have only a single weight matrix which is used by all the recurrent units which does not help in finding many spatial features and shapes. Whereas a CNN can have multiple kernels/filters in a layer enabling them to find many features and build upon that to form shapes every subsequent layer. RNNs would require a lot of layers and hell lot of time to mimic the same as they can find only few sequences at a single layer.
So lets take our quest forward with convolutional networks and see how well could a deeper hyper-parameter optimized version of this do, but before that lets have a look at the additional hyper-parameters in a convolutional neural net.
Here we will speak about the additional parameters present in CNNs, please refer part-I(link at the start) to learn about hyper-parameters in dense layers as they also are part of the CNN architecture.
Kernel/Filter Size: A filter is a matrix of weights with which we convolve on the input. The filter on convolution, provides a measure for how close a patch of input resembles a feature. A feature may be vertical edge or an arch,or any shape. The weights in the filter matrix are derived while training the data. Smaller filters collect as much local information as possible, bigger filters represent more global, high-level and representative information. If you think that a big amount of pixels are necessary for the network to recognize the object you will use large filters (as 11x11 or 9x9). If you think what differentiates objects are some small and local features you should use small filters (3x3 or 5x5). Note in general we use filters with odd sizes.Padding: Padding is generally used to add columns and rows of zeroes to keep the spatial sizes constant after convolution, doing this might improve performance as it retains the information at the borders. Parameters for the padding function in Keras are Same- output size is the same as input size by padding evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right.Valid- Output size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer, No padding occurs.Stride: It is generally the number of pixels you wish to skip while traversing the input horizontally and vertically during convolution after each element-wise multiplication of the input weights with those in the filter. It is used to decrease the input image size considerably as after the convolution operation the size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer.Number of Channels: It is the equal to the number of color channels for the input but in later stages is equal to the number of filters we use for the convolution operation. The more the number of channels,more the number of filters used, more are the features learnt, and more is the chances to over-fit and vice-versa.Pooling-layer Parameters: Pooling layers too have the same parameters as a convolution layer. Max-Pooling is generally used among all the pooling options. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality by keeping the max value(activated features) in the sub-regions binned.
Kernel/Filter Size: A filter is a matrix of weights with which we convolve on the input. The filter on convolution, provides a measure for how close a patch of input resembles a feature. A feature may be vertical edge or an arch,or any shape. The weights in the filter matrix are derived while training the data. Smaller filters collect as much local information as possible, bigger filters represent more global, high-level and representative information. If you think that a big amount of pixels are necessary for the network to recognize the object you will use large filters (as 11x11 or 9x9). If you think what differentiates objects are some small and local features you should use small filters (3x3 or 5x5). Note in general we use filters with odd sizes.
Padding: Padding is generally used to add columns and rows of zeroes to keep the spatial sizes constant after convolution, doing this might improve performance as it retains the information at the borders. Parameters for the padding function in Keras are Same- output size is the same as input size by padding evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right.Valid- Output size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer, No padding occurs.
Stride: It is generally the number of pixels you wish to skip while traversing the input horizontally and vertically during convolution after each element-wise multiplication of the input weights with those in the filter. It is used to decrease the input image size considerably as after the convolution operation the size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer.
Number of Channels: It is the equal to the number of color channels for the input but in later stages is equal to the number of filters we use for the convolution operation. The more the number of channels,more the number of filters used, more are the features learnt, and more is the chances to over-fit and vice-versa.
Pooling-layer Parameters: Pooling layers too have the same parameters as a convolution layer. Max-Pooling is generally used among all the pooling options. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality by keeping the max value(activated features) in the sub-regions binned.
Introducing Batch Normalization:- Generally in deep neural network architectures the normalized input after passing through various adjustments in intermediate layers becomes too big or too small while it reaches far away layers which causes a problem of internal co-variate shift which impacts learning to solve this we add a batch normalization layer to standardize (mean centering and variance scaling) the input given to the later layers. This layer must generally be placed in the architecture after passing it through the layer containing activation function and before the Dropout layer(if any) . An exception is for the sigmoid activation function wherein you need to place the batch normalization layer before the activation to ensure that the values lie in linear region of sigmoid before the function is applied.
The basic principle followed in building a convolutional neural network is to ‘keep the feature space wide and shallow in the initial stages of the network, and the make it narrower and deeper towards the end.’
Keeping the above principle in mind we lay down a few conventions to be followed to guide you while building your CNN architecture
1.Always start by using smaller filters is to collect as much local information as possible, and then gradually increase the filter width to reduce the generated feature space width to represent more global, high-level and representative information
2. Following the principle, the number of channels should be low in the beginning such that it detects low-level features which are combined to form many complex shapes(by increasing the number of channels) which help distinguish between classes.
The number of filters is increased to increase the depth of the feature space thus helping in learning more levels of global abstract structures. One more utility of making the feature space deeper and narrower is to shrink the feature space for input to the dense networks.
By convention the number of channels generally increase or stay the same while we progress through layers in our convolutional neural net architecture
3. General filter sizes used are 3x3, 5x5 and 7x7 for the convolutional layer for a moderate or small-sized images and for Max-Pooling parameters we use 2x2 or 3x3 filter sizes with a stride of 2. Larger filter sizes and strides may be used to shrink a large image to a moderate size and then go further with the convention stated.
4. Try using padding = same when you feel the border’s of the image might be important or just to help elongate your network architecture as padding keeps the dimensions same even after the convolution operation and therefore you can perform more convolutions without shrinking size.
5. Keep adding layers until you over-fit. As once we achieved a considerable accuracy in our validation set we can use regularization components like l1/l2 regularization, dropout, batch norm, data augmentation etc. to reduce over-fitting
5. Always use classic networks like LeNet, AlexNet, VGG-16, VGG-19 etc. as an inspiration while building the architectures for your models. By inspiration i mean follow the trend used in the architectures for example trend in the layers Conv-Pool-Conv-Pool or Conv-Conv-Pool-Conv-Conv-Pool or trend in the Number of channels 32–64–128 or 32–32-64–64 or trend in filter sizes, Max-pooling parameters etc.
Hyper-parameter tuning of CNNs are a tad bit difficult than tuning of dense networks due to the above conventions. This is because the Hyperas uses random search for the best possible model which in-turn may lead to disobeying few conventions, to prevent this from happening we need to design CNN architectures and then fine-tune hyper-parameters in Hyperas to get our best model.
The approach used with Hyperas while tuning dense networks,wherein we give a set a values for all the hyperparameters and let the module decide which is best won’t work for tuning CNN. This is because at each layer the input dimensions decrease due to operations like convolution and max-pooling hence if we give a range of values for hyperparameters like stride,filter-size etc. there always exists a chance that Hyperas chooses a module which ends up in a negative dimension exception and stops before completion.
So how to build the architecture you ask? lets begin. But before that i would like to recap that on using a Convolution or Pooling layer we reduce the dimensions of the input image of dimensions N to (N-f+1)/s where where ‘f’ is the filter size and ‘s’ the stride length this will be very helpful to us during the process.
The first example on how to build a CNN architecture is shown below which takes inspiration from the LeNet-5 architecture
Step-1 is to make a sheet containing the dimensions ,activation shapes and sizes for the architecture just as shown below
Please refer the video by AndrewNg for more reference- https://www.youtube.com/watch?v=w2sRcGha9nM&t=485s
Here we calculate the Activation shape after every convolution or pooling operation is (ceil(N+f-1)/s,ceil(N+f-1)/s,Number of filters) wherever the padding value is ‘valid’ and dimensions are (N,N,Number of filters) where the padding used is ‘same’ ,here ’N’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. The Activation value is computed by multiplying all values in the dimensions of Activation Shape.
For second stage N=28,f=3,s=1,Number of filters=8 and padding is valid hence we get Activation shape as (28,28,8). Activation Value= 28x28x8=6272
For third stage Max-Pool Layer we get ceil((28–2+1)/2)=ceil(13.5)=14 therefore dimensions are (14,14,8). The last dimension does not change on using a pooling layer. Activation Value= 14x14x8=1568
For fourth stage N=14,f=5,s=1,Number of filters=8 and padding is valid hence we get Activation shape as ((14–5+1)/2,(14–5+1)/2,16)= (10,10,16)
Flatten makes the input into a one-dimensional list for input to the dense layers therefore Activation shape is (400,1). Activation Value= 400x1=400
Dense Activation shape (64,1) states 64 hidden units are used in the dense layer.Activation Value= 64x1=64
This computation tells us if we are choosing the right parameters while building our CNN architecture as the architecture must not end up with negative dimensions by going overboard with usage of high values of stride length and filter-sizes
It is very important to ensure that you choose your values such that there is a general decreasing trend in the Activation values and there ain’t any very abrupt changes in Activation values
Next we convert the model architecture to keras code.
cnn1 = Sequential([ Conv2D(8, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(16, kernel_size=(5, 5), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(120, activation='relu'), Dense(84, activation='relu'), Dense(10, activation='softmax')])
After converting to keras code to check if the conversion is correct and dimensions are the ones you desire you can use <model name>.summary the Output shape column gives you the output dimensions
Using Adam optimizer with learning rate of 0.001 generally does well for CNNs, so with we train the architecture using the same to get accuracy values as shown below
Train loss: 0.18204240553701917Train accuracy: 0.932125-------------------------------Validation loss: 0.24995902764300507Validation accuracy: 0.9090833333333334-------------------------------
We repeat the same procedure for more CNN architectures
Next we use a Conv-Pool-Conv-Pool kind of architecture with doubling the number of filters every stage. The architecture is shown below
Convert to Keras
cnn1 = Sequential([ Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=input_shape), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(64, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(128, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(64, activation='relu'), Dense(10, activation='softmax')])
Using Adam optimizer with learning rate of 0.001 we train the architecture to get accuracy values as shown below
Train loss: 0.18507329044366877Train accuracy: 0.9320625-------------------------------Validation loss: 0.287726696540912Validation accuracy: 0.8989166666666667-------------------------------
Finally we also train a vgg like model with the trend Conv-Conv-Pool-Conv-Conv-Pool
Convert to keras
cnn1 = Sequential([ Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same'), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(32, kernel_size=(3, 3), activation='relu'), Conv2D(32, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(512, activation='relu'), Dense(10, activation='softmax')])
Get the accuracy values
Train loss: 0.05137992699308476Train accuracy: 0.9810625-------------------------------Validation loss: 0.30437974256711703Validation accuracy: 0.923-------------------------------
Step 2- Choose the architecture(s) for which you wish to do hyper-parameter optmization
Among all the models look at the one which has the highest validation set score use it as your base architecture
Among our models the vgg like model has the highest value of accuracy on the validation set hence we choose the base architecture as the one shown below
cnn1 = Sequential([ Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same'), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(32, kernel_size=(3, 3), activation='relu'), Conv2D(32, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(512, activation='relu'), Dense(10, activation='softmax')])
Step 3- Hyper-parameter optimization
The train loss in the model is very low as compared to the validation set loss which tells us that the model has over-fit. Therefore we need to tune the hyper-parameters such that we get a low loss and yet don’t over-fit for this we will use Hyperas.
We now optimize hyperparameters using Hyperas similiar to the way we have done in Part-I. Please refer to Part-I for more details
To optimize we need 3 code blocks
Data Function
Data Function
The function which directly loads train and validation data from the source or if pre-processing is done it is recommended to store the data after pre-processing in a pickle/numpy/hdf5/csv file and write code in the data function to access data from that file.
def data(): (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data() X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=12345) X_train = X_train.astype('float32') X_val = X_val.astype('float32') X_train /= 255 X_val /= 255 nb_classes = 10 Y_train = np_utils.to_categorical(y_train, nb_classes) Y_val = np_utils.to_categorical(y_val, nb_classes) return X_train, Y_train, X_val, Y_val
Debugging Tip:- If in case you get any error related to the data function just try to rerun the code block or add import statements of the functions or packages used in the data function again at the beginning of the function
2. Model Function
def model(X_train, Y_train, X_val, Y_val): model = Sequential() model_choice = {{choice(['one', 'two'])}} if model_choice == 'one': model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) elif model_choice == 'two': model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Flatten()) model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}})) choiceval = {{choice(['one', 'two'])}} if choiceval == 'two': model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}})) model.add(Dense(10, activation='softmax')) adam = keras.optimizers.Adam(lr=0.001) model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer=adam) model.fit(X_train, Y_train, batch_size=256, nb_epoch=15, verbose=2, validation_data=(X_val, Y_val)) score, acc = model.evaluate(X_val, Y_val, verbose=0) print('Val accuracy:', acc) return {'loss': -acc, 'status': STATUS_OK, 'model': model}
Note the positioning of the Dropout layer it is placed after the Max-Pool layer. The placement is done in this way uphold the definition of Dropout which while learning removes high dependency on small set of features. If placed before the Max-Pool layer the values removed by Dropout may not affect the output of the Max-Pool layer as it picks the maximum from a set of values, therefore only when the maximum value is removed can it be thought of removing a feature dependency. Batch Normalization layer as stated is placed after the activation function is applied.
In the model function we can choose the hyperparameters we need to optimize. In the above code block we are optimizing for the
Number of Hidden Units and Number of layers either one or two for the Dense Network
Number of Hidden Units and Number of layers either one or two for the Dense Network
model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}})) choiceval = {{choice(['one', 'two'])}} if choiceval == 'two': model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}}))
The value of ‘choiceval’ decides we use a two layer dense network or a single layer
2. Dropout values
model.add(Dropout({{uniform(0, 1)}}))
3. Number of Channels in the architecture
if model_choice == 'one': model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) elif model_choice == 'two': model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}}))
The value of ‘model_choice’ decides whether we choose the architecture with initial layers as Conv(16)-Conv(16)-Pool-Conv(32)-Conv(32)-Pool or Conv(32)-Conv(32)-Pool-Conv(64)-Conv(64)-Pool. (the number in the bracket is representative of the number of filters in the layer.)
3. Excecute and Interpret
We begin the optimization using the above data and model functions
X_train, Y_train, X_val, Y_val = data()best_run, best_model = optim.minimize(model=model, data=data, algo=tpe.suggest, max_evals=30, trials=Trials(), notebook_name='Fashion_MNIST')
On executing the above snippet we get the below framework in our output. We use this to match the values of the hyper-parameters tuned.
model = Sequential()model_choice = space['model_choice']if model_choice == 'one': model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout'])) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout_1']))elif model_choice == 'two': model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout_2'])) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout_3'])) model.add(Flatten()) model.add(Dense(space['Dense'], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(space['Dropout_4'])) choiceval = space['model_choice_1'] if choiceval == 'two': model.add(Dense(space['Dense_1'], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(space['Dropout_5'])) model.add(Dense(10, activation='softmax'))adam = keras.optimizers.Adam(lr=0.001)
Now we need to get our values from the parameter indexes in the print(best_run) output
{'Dense': 1, 'Dense_1': 2, 'Dropout': 0.2799579955710103, 'Dropout_1': 0.8593089514091055, 'Dropout_2': 0.17434082481320767, 'Dropout_3': 0.2839296185815494, 'Dropout_4': 0.7087321230411557, 'Dropout_5': 0.3273210014856124, 'model_choice': 1, 'model_choice_1': 0}
On interpreting the above by matching the values with their position in the framework we get the the best architecture to be
cnn1 = Sequential([ Conv2D(32, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), Conv2D(32, kernel_size=(3, 3), activation='relu',padding='same'), MaxPooling2D(pool_size=(2, 2),strides=2), Dropout(0.2), Conv2D(64, kernel_size=(3, 3), activation='relu'), Conv2D(64, kernel_size=(3, 3), activation='relu'), BatchNormalization(), MaxPooling2D(pool_size=(2, 2),strides=2), Dropout(0.3), Flatten(), Dense(256, activation='relu'), BatchNormalization(), Dropout(0.7), Dense(10, activation='softmax')])
The accuracy and loss values for the above architecture are
Train loss: 0.14321659112690638Train accuracy: 0.9463333333333334-------------------------------Validation loss: 0.17808779059847196Validation accuracy: 0.93525-------------------------------Test loss: 0.20868439328074456Test accuracy: 0.9227
So finally we end up with 92.27% accuracy on our test set which is better than our optimized dense network architecture which gave us an accuracy of 88% on test set. But most importantly our model is not over-fitting and hence will generalize well to unseen points unlike other architecture which may achieve higher accuracy but over-fit to training set.
We can improve this accuracy further by using data augmentation techniques but that i’ll leave it to you for experimentation.
Hope the article was of help and that you learned how to make an efficient CNN architecture through this article.
For more information do checkout the blog post on https://neptune.ai/blog/optuna-vs-hyperopt
Thank you for reading! | [
{
"code": null,
"e": 412,
"s": 171,
"text": "This article is a continuation to the article linked below which deals with the need for hyper-parameter optimization and how to do hyper-parameter selection and optimization using Hyperas for Dense Neural Networks (Multi-Layer Perceptrons)"
},
{
"code": null,
"e": 423,
"s": 412,
"text": "medium.com"
},
{
"code": null,
"e": 639,
"s": 423,
"text": "In the current article we will continue from where we left off in part-I and would try to solve the same problem, the image classification task of the Fashion-MNIST data-set using Convolutional Neural Networks(CNN)."
},
{
"code": null,
"e": 1204,
"s": 639,
"text": "The CNNs have several different filters/kernels consisting of trainable parameters which can convolve on a given image spatially to detect features like edges and shapes. These high number of filters essentially learn to capture spatial features from the image based on the learned weights through back propagation and stacked layers of filters can be used to detect complex spatial shapes from the spatial features at every subsequent level. Hence they can successfully boil down a given image into a highly abstracted representation which is easy for predicting."
},
{
"code": null,
"e": 1591,
"s": 1204,
"text": "In Dense networks we try to find patterns in pixel values given as input for eg. if pixel number 25 and 26 are greater than a certain value it might belong to a certain class and a few complex variations of the same. This might easily fail if we can have objects anywhere in the image and not necessarily centered like in the MNIST or to a certain extent also in the Fashion-MNIST data."
},
{
"code": null,
"e": 2177,
"s": 1591,
"text": "RNNs on the other hand find sequences in data and an edge or a shape too can be thought of as a sequence of pixel values but the problem lies in the fact that they have only a single weight matrix which is used by all the recurrent units which does not help in finding many spatial features and shapes. Whereas a CNN can have multiple kernels/filters in a layer enabling them to find many features and build upon that to form shapes every subsequent layer. RNNs would require a lot of layers and hell lot of time to mimic the same as they can find only few sequences at a single layer."
},
{
"code": null,
"e": 2413,
"s": 2177,
"text": "So lets take our quest forward with convolutional networks and see how well could a deeper hyper-parameter optimized version of this do, but before that lets have a look at the additional hyper-parameters in a convolutional neural net."
},
{
"code": null,
"e": 2615,
"s": 2413,
"text": "Here we will speak about the additional parameters present in CNNs, please refer part-I(link at the start) to learn about hyper-parameters in dense layers as they also are part of the CNN architecture."
},
{
"code": null,
"e": 5154,
"s": 2615,
"text": "Kernel/Filter Size: A filter is a matrix of weights with which we convolve on the input. The filter on convolution, provides a measure for how close a patch of input resembles a feature. A feature may be vertical edge or an arch,or any shape. The weights in the filter matrix are derived while training the data. Smaller filters collect as much local information as possible, bigger filters represent more global, high-level and representative information. If you think that a big amount of pixels are necessary for the network to recognize the object you will use large filters (as 11x11 or 9x9). If you think what differentiates objects are some small and local features you should use small filters (3x3 or 5x5). Note in general we use filters with odd sizes.Padding: Padding is generally used to add columns and rows of zeroes to keep the spatial sizes constant after convolution, doing this might improve performance as it retains the information at the borders. Parameters for the padding function in Keras are Same- output size is the same as input size by padding evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right.Valid- Output size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer, No padding occurs.Stride: It is generally the number of pixels you wish to skip while traversing the input horizontally and vertically during convolution after each element-wise multiplication of the input weights with those in the filter. It is used to decrease the input image size considerably as after the convolution operation the size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer.Number of Channels: It is the equal to the number of color channels for the input but in later stages is equal to the number of filters we use for the convolution operation. The more the number of channels,more the number of filters used, more are the features learnt, and more is the chances to over-fit and vice-versa.Pooling-layer Parameters: Pooling layers too have the same parameters as a convolution layer. Max-Pooling is generally used among all the pooling options. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality by keeping the max value(activated features) in the sub-regions binned."
},
{
"code": null,
"e": 5917,
"s": 5154,
"text": "Kernel/Filter Size: A filter is a matrix of weights with which we convolve on the input. The filter on convolution, provides a measure for how close a patch of input resembles a feature. A feature may be vertical edge or an arch,or any shape. The weights in the filter matrix are derived while training the data. Smaller filters collect as much local information as possible, bigger filters represent more global, high-level and representative information. If you think that a big amount of pixels are necessary for the network to recognize the object you will use large filters (as 11x11 or 9x9). If you think what differentiates objects are some small and local features you should use small filters (3x3 or 5x5). Note in general we use filters with odd sizes."
},
{
"code": null,
"e": 6539,
"s": 5917,
"text": "Padding: Padding is generally used to add columns and rows of zeroes to keep the spatial sizes constant after convolution, doing this might improve performance as it retains the information at the borders. Parameters for the padding function in Keras are Same- output size is the same as input size by padding evenly left and right, but if the amount of columns to be added is odd, it will add the extra column to the right.Valid- Output size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer, No padding occurs."
},
{
"code": null,
"e": 7022,
"s": 6539,
"text": "Stride: It is generally the number of pixels you wish to skip while traversing the input horizontally and vertically during convolution after each element-wise multiplication of the input weights with those in the filter. It is used to decrease the input image size considerably as after the convolution operation the size shrinks to ceil((n+f-1)/s) where ’n’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. ceil rounds off the decimal to the closet higher integer."
},
{
"code": null,
"e": 7343,
"s": 7022,
"text": "Number of Channels: It is the equal to the number of color channels for the input but in later stages is equal to the number of filters we use for the convolution operation. The more the number of channels,more the number of filters used, more are the features learnt, and more is the chances to over-fit and vice-versa."
},
{
"code": null,
"e": 7697,
"s": 7343,
"text": "Pooling-layer Parameters: Pooling layers too have the same parameters as a convolution layer. Max-Pooling is generally used among all the pooling options. The objective is to down-sample an input representation (image, hidden-layer output matrix, etc.), reducing its dimensionality by keeping the max value(activated features) in the sub-regions binned."
},
{
"code": null,
"e": 8521,
"s": 7697,
"text": "Introducing Batch Normalization:- Generally in deep neural network architectures the normalized input after passing through various adjustments in intermediate layers becomes too big or too small while it reaches far away layers which causes a problem of internal co-variate shift which impacts learning to solve this we add a batch normalization layer to standardize (mean centering and variance scaling) the input given to the later layers. This layer must generally be placed in the architecture after passing it through the layer containing activation function and before the Dropout layer(if any) . An exception is for the sigmoid activation function wherein you need to place the batch normalization layer before the activation to ensure that the values lie in linear region of sigmoid before the function is applied."
},
{
"code": null,
"e": 8732,
"s": 8521,
"text": "The basic principle followed in building a convolutional neural network is to ‘keep the feature space wide and shallow in the initial stages of the network, and the make it narrower and deeper towards the end.’"
},
{
"code": null,
"e": 8863,
"s": 8732,
"text": "Keeping the above principle in mind we lay down a few conventions to be followed to guide you while building your CNN architecture"
},
{
"code": null,
"e": 9113,
"s": 8863,
"text": "1.Always start by using smaller filters is to collect as much local information as possible, and then gradually increase the filter width to reduce the generated feature space width to represent more global, high-level and representative information"
},
{
"code": null,
"e": 9360,
"s": 9113,
"text": "2. Following the principle, the number of channels should be low in the beginning such that it detects low-level features which are combined to form many complex shapes(by increasing the number of channels) which help distinguish between classes."
},
{
"code": null,
"e": 9635,
"s": 9360,
"text": "The number of filters is increased to increase the depth of the feature space thus helping in learning more levels of global abstract structures. One more utility of making the feature space deeper and narrower is to shrink the feature space for input to the dense networks."
},
{
"code": null,
"e": 9786,
"s": 9635,
"text": "By convention the number of channels generally increase or stay the same while we progress through layers in our convolutional neural net architecture"
},
{
"code": null,
"e": 10118,
"s": 9786,
"text": "3. General filter sizes used are 3x3, 5x5 and 7x7 for the convolutional layer for a moderate or small-sized images and for Max-Pooling parameters we use 2x2 or 3x3 filter sizes with a stride of 2. Larger filter sizes and strides may be used to shrink a large image to a moderate size and then go further with the convention stated."
},
{
"code": null,
"e": 10402,
"s": 10118,
"text": "4. Try using padding = same when you feel the border’s of the image might be important or just to help elongate your network architecture as padding keeps the dimensions same even after the convolution operation and therefore you can perform more convolutions without shrinking size."
},
{
"code": null,
"e": 10641,
"s": 10402,
"text": "5. Keep adding layers until you over-fit. As once we achieved a considerable accuracy in our validation set we can use regularization components like l1/l2 regularization, dropout, batch norm, data augmentation etc. to reduce over-fitting"
},
{
"code": null,
"e": 11045,
"s": 10641,
"text": "5. Always use classic networks like LeNet, AlexNet, VGG-16, VGG-19 etc. as an inspiration while building the architectures for your models. By inspiration i mean follow the trend used in the architectures for example trend in the layers Conv-Pool-Conv-Pool or Conv-Conv-Pool-Conv-Conv-Pool or trend in the Number of channels 32–64–128 or 32–32-64–64 or trend in filter sizes, Max-pooling parameters etc."
},
{
"code": null,
"e": 11426,
"s": 11045,
"text": "Hyper-parameter tuning of CNNs are a tad bit difficult than tuning of dense networks due to the above conventions. This is because the Hyperas uses random search for the best possible model which in-turn may lead to disobeying few conventions, to prevent this from happening we need to design CNN architectures and then fine-tune hyper-parameters in Hyperas to get our best model."
},
{
"code": null,
"e": 11942,
"s": 11426,
"text": "The approach used with Hyperas while tuning dense networks,wherein we give a set a values for all the hyperparameters and let the module decide which is best won’t work for tuning CNN. This is because at each layer the input dimensions decrease due to operations like convolution and max-pooling hence if we give a range of values for hyperparameters like stride,filter-size etc. there always exists a chance that Hyperas chooses a module which ends up in a negative dimension exception and stops before completion."
},
{
"code": null,
"e": 12265,
"s": 11942,
"text": "So how to build the architecture you ask? lets begin. But before that i would like to recap that on using a Convolution or Pooling layer we reduce the dimensions of the input image of dimensions N to (N-f+1)/s where where ‘f’ is the filter size and ‘s’ the stride length this will be very helpful to us during the process."
},
{
"code": null,
"e": 12387,
"s": 12265,
"text": "The first example on how to build a CNN architecture is shown below which takes inspiration from the LeNet-5 architecture"
},
{
"code": null,
"e": 12509,
"s": 12387,
"text": "Step-1 is to make a sheet containing the dimensions ,activation shapes and sizes for the architecture just as shown below"
},
{
"code": null,
"e": 12615,
"s": 12509,
"text": "Please refer the video by AndrewNg for more reference- https://www.youtube.com/watch?v=w2sRcGha9nM&t=485s"
},
{
"code": null,
"e": 13037,
"s": 12615,
"text": "Here we calculate the Activation shape after every convolution or pooling operation is (ceil(N+f-1)/s,ceil(N+f-1)/s,Number of filters) wherever the padding value is ‘valid’ and dimensions are (N,N,Number of filters) where the padding used is ‘same’ ,here ’N’ is input dimensions ‘f’ is filter size and ‘s’ is stride length. The Activation value is computed by multiplying all values in the dimensions of Activation Shape."
},
{
"code": null,
"e": 13183,
"s": 13037,
"text": "For second stage N=28,f=3,s=1,Number of filters=8 and padding is valid hence we get Activation shape as (28,28,8). Activation Value= 28x28x8=6272"
},
{
"code": null,
"e": 13380,
"s": 13183,
"text": "For third stage Max-Pool Layer we get ceil((28–2+1)/2)=ceil(13.5)=14 therefore dimensions are (14,14,8). The last dimension does not change on using a pooling layer. Activation Value= 14x14x8=1568"
},
{
"code": null,
"e": 13523,
"s": 13380,
"text": "For fourth stage N=14,f=5,s=1,Number of filters=8 and padding is valid hence we get Activation shape as ((14–5+1)/2,(14–5+1)/2,16)= (10,10,16)"
},
{
"code": null,
"e": 13672,
"s": 13523,
"text": "Flatten makes the input into a one-dimensional list for input to the dense layers therefore Activation shape is (400,1). Activation Value= 400x1=400"
},
{
"code": null,
"e": 13779,
"s": 13672,
"text": "Dense Activation shape (64,1) states 64 hidden units are used in the dense layer.Activation Value= 64x1=64"
},
{
"code": null,
"e": 14021,
"s": 13779,
"text": "This computation tells us if we are choosing the right parameters while building our CNN architecture as the architecture must not end up with negative dimensions by going overboard with usage of high values of stride length and filter-sizes"
},
{
"code": null,
"e": 14212,
"s": 14021,
"text": "It is very important to ensure that you choose your values such that there is a general decreasing trend in the Activation values and there ain’t any very abrupt changes in Activation values"
},
{
"code": null,
"e": 14266,
"s": 14212,
"text": "Next we convert the model architecture to keras code."
},
{
"code": null,
"e": 14640,
"s": 14266,
"text": "cnn1 = Sequential([ Conv2D(8, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(16, kernel_size=(5, 5), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(120, activation='relu'), Dense(84, activation='relu'), Dense(10, activation='softmax')])"
},
{
"code": null,
"e": 14837,
"s": 14640,
"text": "After converting to keras code to check if the conversion is correct and dimensions are the ones you desire you can use <model name>.summary the Output shape column gives you the output dimensions"
},
{
"code": null,
"e": 15003,
"s": 14837,
"text": "Using Adam optimizer with learning rate of 0.001 generally does well for CNNs, so with we train the architecture using the same to get accuracy values as shown below"
},
{
"code": null,
"e": 15196,
"s": 15003,
"text": "Train loss: 0.18204240553701917Train accuracy: 0.932125-------------------------------Validation loss: 0.24995902764300507Validation accuracy: 0.9090833333333334-------------------------------"
},
{
"code": null,
"e": 15252,
"s": 15196,
"text": "We repeat the same procedure for more CNN architectures"
},
{
"code": null,
"e": 15388,
"s": 15252,
"text": "Next we use a Conv-Pool-Conv-Pool kind of architecture with doubling the number of filters every stage. The architecture is shown below"
},
{
"code": null,
"e": 15405,
"s": 15388,
"text": "Convert to Keras"
},
{
"code": null,
"e": 15831,
"s": 15405,
"text": "cnn1 = Sequential([ Conv2D(32, kernel_size=(3, 3), activation='relu',input_shape=input_shape), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(64, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(128, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(64, activation='relu'), Dense(10, activation='softmax')])"
},
{
"code": null,
"e": 15944,
"s": 15831,
"text": "Using Adam optimizer with learning rate of 0.001 we train the architecture to get accuracy values as shown below"
},
{
"code": null,
"e": 16136,
"s": 15944,
"text": "Train loss: 0.18507329044366877Train accuracy: 0.9320625-------------------------------Validation loss: 0.287726696540912Validation accuracy: 0.8989166666666667-------------------------------"
},
{
"code": null,
"e": 16220,
"s": 16136,
"text": "Finally we also train a vgg like model with the trend Conv-Conv-Pool-Conv-Conv-Pool"
},
{
"code": null,
"e": 16237,
"s": 16220,
"text": "Convert to keras"
},
{
"code": null,
"e": 16702,
"s": 16237,
"text": "cnn1 = Sequential([ Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same'), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(32, kernel_size=(3, 3), activation='relu'), Conv2D(32, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(512, activation='relu'), Dense(10, activation='softmax')])"
},
{
"code": null,
"e": 16726,
"s": 16702,
"text": "Get the accuracy values"
},
{
"code": null,
"e": 16907,
"s": 16726,
"text": "Train loss: 0.05137992699308476Train accuracy: 0.9810625-------------------------------Validation loss: 0.30437974256711703Validation accuracy: 0.923-------------------------------"
},
{
"code": null,
"e": 16995,
"s": 16907,
"text": "Step 2- Choose the architecture(s) for which you wish to do hyper-parameter optmization"
},
{
"code": null,
"e": 17108,
"s": 16995,
"text": "Among all the models look at the one which has the highest validation set score use it as your base architecture"
},
{
"code": null,
"e": 17261,
"s": 17108,
"text": "Among our models the vgg like model has the highest value of accuracy on the validation set hence we choose the base architecture as the one shown below"
},
{
"code": null,
"e": 17726,
"s": 17261,
"text": "cnn1 = Sequential([ Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), Conv2D(16, kernel_size=(3, 3), activation='relu',padding='same'), MaxPooling2D(pool_size=(2, 2),strides=2), Conv2D(32, kernel_size=(3, 3), activation='relu'), Conv2D(32, kernel_size=(3, 3), activation='relu'), MaxPooling2D(pool_size=(2, 2),strides=2), Flatten(), Dense(512, activation='relu'), Dense(10, activation='softmax')])"
},
{
"code": null,
"e": 17763,
"s": 17726,
"text": "Step 3- Hyper-parameter optimization"
},
{
"code": null,
"e": 18014,
"s": 17763,
"text": "The train loss in the model is very low as compared to the validation set loss which tells us that the model has over-fit. Therefore we need to tune the hyper-parameters such that we get a low loss and yet don’t over-fit for this we will use Hyperas."
},
{
"code": null,
"e": 18144,
"s": 18014,
"text": "We now optimize hyperparameters using Hyperas similiar to the way we have done in Part-I. Please refer to Part-I for more details"
},
{
"code": null,
"e": 18178,
"s": 18144,
"text": "To optimize we need 3 code blocks"
},
{
"code": null,
"e": 18192,
"s": 18178,
"text": "Data Function"
},
{
"code": null,
"e": 18206,
"s": 18192,
"text": "Data Function"
},
{
"code": null,
"e": 18467,
"s": 18206,
"text": "The function which directly loads train and validation data from the source or if pre-processing is done it is recommended to store the data after pre-processing in a pickle/numpy/hdf5/csv file and write code in the data function to access data from that file."
},
{
"code": null,
"e": 18933,
"s": 18467,
"text": "def data(): (X_train, y_train), (X_test, y_test) = fashion_mnist.load_data() X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=12345) X_train = X_train.astype('float32') X_val = X_val.astype('float32') X_train /= 255 X_val /= 255 nb_classes = 10 Y_train = np_utils.to_categorical(y_train, nb_classes) Y_val = np_utils.to_categorical(y_val, nb_classes) return X_train, Y_train, X_val, Y_val"
},
{
"code": null,
"e": 19159,
"s": 18933,
"text": "Debugging Tip:- If in case you get any error related to the data function just try to rerun the code block or add import statements of the functions or packages used in the data function again at the beginning of the function"
},
{
"code": null,
"e": 19177,
"s": 19159,
"text": "2. Model Function"
},
{
"code": null,
"e": 21402,
"s": 19177,
"text": "def model(X_train, Y_train, X_val, Y_val): model = Sequential() model_choice = {{choice(['one', 'two'])}} if model_choice == 'one': model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) elif model_choice == 'two': model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Flatten()) model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}})) choiceval = {{choice(['one', 'two'])}} if choiceval == 'two': model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}})) model.add(Dense(10, activation='softmax')) adam = keras.optimizers.Adam(lr=0.001) model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer=adam) model.fit(X_train, Y_train, batch_size=256, nb_epoch=15, verbose=2, validation_data=(X_val, Y_val)) score, acc = model.evaluate(X_val, Y_val, verbose=0) print('Val accuracy:', acc) return {'loss': -acc, 'status': STATUS_OK, 'model': model}"
},
{
"code": null,
"e": 21970,
"s": 21402,
"text": "Note the positioning of the Dropout layer it is placed after the Max-Pool layer. The placement is done in this way uphold the definition of Dropout which while learning removes high dependency on small set of features. If placed before the Max-Pool layer the values removed by Dropout may not affect the output of the Max-Pool layer as it picks the maximum from a set of values, therefore only when the maximum value is removed can it be thought of removing a feature dependency. Batch Normalization layer as stated is placed after the activation function is applied."
},
{
"code": null,
"e": 22097,
"s": 21970,
"text": "In the model function we can choose the hyperparameters we need to optimize. In the above code block we are optimizing for the"
},
{
"code": null,
"e": 22181,
"s": 22097,
"text": "Number of Hidden Units and Number of layers either one or two for the Dense Network"
},
{
"code": null,
"e": 22265,
"s": 22181,
"text": "Number of Hidden Units and Number of layers either one or two for the Dense Network"
},
{
"code": null,
"e": 22634,
"s": 22265,
"text": " model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}})) choiceval = {{choice(['one', 'two'])}} if choiceval == 'two': model.add(Dense({{choice([256, 512,1024])}}, activation='relu')) model.add(BatchNormalization()) model.add(Dropout({{uniform(0, 1)}}))"
},
{
"code": null,
"e": 22718,
"s": 22634,
"text": "The value of ‘choiceval’ decides we use a two layer dense network or a single layer"
},
{
"code": null,
"e": 22736,
"s": 22718,
"text": "2. Dropout values"
},
{
"code": null,
"e": 22774,
"s": 22736,
"text": "model.add(Dropout({{uniform(0, 1)}}))"
},
{
"code": null,
"e": 22816,
"s": 22774,
"text": "3. Number of Channels in the architecture"
},
{
"code": null,
"e": 24017,
"s": 22816,
"text": "if model_choice == 'one': model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) elif model_choice == 'two': model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}})) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout({{uniform(0, 1)}}))"
},
{
"code": null,
"e": 24292,
"s": 24017,
"text": "The value of ‘model_choice’ decides whether we choose the architecture with initial layers as Conv(16)-Conv(16)-Pool-Conv(32)-Conv(32)-Pool or Conv(32)-Conv(32)-Pool-Conv(64)-Conv(64)-Pool. (the number in the bracket is representative of the number of filters in the layer.)"
},
{
"code": null,
"e": 24318,
"s": 24292,
"text": "3. Excecute and Interpret"
},
{
"code": null,
"e": 24385,
"s": 24318,
"text": "We begin the optimization using the above data and model functions"
},
{
"code": null,
"e": 24751,
"s": 24385,
"text": "X_train, Y_train, X_val, Y_val = data()best_run, best_model = optim.minimize(model=model, data=data, algo=tpe.suggest, max_evals=30, trials=Trials(), notebook_name='Fashion_MNIST')"
},
{
"code": null,
"e": 24887,
"s": 24751,
"text": "On executing the above snippet we get the below framework in our output. We use this to match the values of the hyper-parameters tuned."
},
{
"code": null,
"e": 26475,
"s": 24887,
"text": "model = Sequential()model_choice = space['model_choice']if model_choice == 'one': model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(16, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout'])) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(Conv2D(32, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout_1']))elif model_choice == 'two': model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same', input_shape=(1,28,28), data_format='channels_first')) model.add(Conv2D(32, kernel_size=3, activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout_2'])) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(Conv2D(64, kernel_size=3, activation='relu')) model.add(BatchNormalization()) model.add(MaxPooling2D(pool_size=2,strides=2)) model.add(Dropout(space['Dropout_3'])) model.add(Flatten()) model.add(Dense(space['Dense'], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(space['Dropout_4'])) choiceval = space['model_choice_1'] if choiceval == 'two': model.add(Dense(space['Dense_1'], activation='relu')) model.add(BatchNormalization()) model.add(Dropout(space['Dropout_5'])) model.add(Dense(10, activation='softmax'))adam = keras.optimizers.Adam(lr=0.001)"
},
{
"code": null,
"e": 26562,
"s": 26475,
"text": "Now we need to get our values from the parameter indexes in the print(best_run) output"
},
{
"code": null,
"e": 26826,
"s": 26562,
"text": "{'Dense': 1, 'Dense_1': 2, 'Dropout': 0.2799579955710103, 'Dropout_1': 0.8593089514091055, 'Dropout_2': 0.17434082481320767, 'Dropout_3': 0.2839296185815494, 'Dropout_4': 0.7087321230411557, 'Dropout_5': 0.3273210014856124, 'model_choice': 1, 'model_choice_1': 0}"
},
{
"code": null,
"e": 26951,
"s": 26826,
"text": "On interpreting the above by matching the values with their position in the framework we get the the best architecture to be"
},
{
"code": null,
"e": 27517,
"s": 26951,
"text": "cnn1 = Sequential([ Conv2D(32, kernel_size=(3, 3), activation='relu',padding='same',input_shape=input_shape), Conv2D(32, kernel_size=(3, 3), activation='relu',padding='same'), MaxPooling2D(pool_size=(2, 2),strides=2), Dropout(0.2), Conv2D(64, kernel_size=(3, 3), activation='relu'), Conv2D(64, kernel_size=(3, 3), activation='relu'), BatchNormalization(), MaxPooling2D(pool_size=(2, 2),strides=2), Dropout(0.3), Flatten(), Dense(256, activation='relu'), BatchNormalization(), Dropout(0.7), Dense(10, activation='softmax')])"
},
{
"code": null,
"e": 27577,
"s": 27517,
"text": "The accuracy and loss values for the above architecture are"
},
{
"code": null,
"e": 27820,
"s": 27577,
"text": "Train loss: 0.14321659112690638Train accuracy: 0.9463333333333334-------------------------------Validation loss: 0.17808779059847196Validation accuracy: 0.93525-------------------------------Test loss: 0.20868439328074456Test accuracy: 0.9227"
},
{
"code": null,
"e": 28175,
"s": 27820,
"text": "So finally we end up with 92.27% accuracy on our test set which is better than our optimized dense network architecture which gave us an accuracy of 88% on test set. But most importantly our model is not over-fitting and hence will generalize well to unseen points unlike other architecture which may achieve higher accuracy but over-fit to training set."
},
{
"code": null,
"e": 28301,
"s": 28175,
"text": "We can improve this accuracy further by using data augmentation techniques but that i’ll leave it to you for experimentation."
},
{
"code": null,
"e": 28415,
"s": 28301,
"text": "Hope the article was of help and that you learned how to make an efficient CNN architecture through this article."
},
{
"code": null,
"e": 28508,
"s": 28415,
"text": "For more information do checkout the blog post on https://neptune.ai/blog/optuna-vs-hyperopt"
}
]
|
What is tilde (~) operator in Python? | The bitwise operator ~ (pronounced as tilde) is a complement operator. It takes one bit operand and returns its complement. If the operand is 1, it returns 0, and if it is 0, it returns 1
For example if a=60 (0011 1100 in binary) its complement is -61 (-0011 1101) stored in 2's complement
>>> a=60
>>> bin(a)
'0b111100'
>>> b=~a
>>> a
60
>>>
>>> b
-61
>>> bin(b)
'-0b111101 | [
{
"code": null,
"e": 1250,
"s": 1062,
"text": "The bitwise operator ~ (pronounced as tilde) is a complement operator. It takes one bit operand and returns its complement. If the operand is 1, it returns 0, and if it is 0, it returns 1"
},
{
"code": null,
"e": 1352,
"s": 1250,
"text": "For example if a=60 (0011 1100 in binary) its complement is -61 (-0011 1101) stored in 2's complement"
},
{
"code": null,
"e": 1437,
"s": 1352,
"text": ">>> a=60\n>>> bin(a)\n'0b111100'\n>>> b=~a\n>>> a\n60\n>>>\n>>> b\n-61\n>>> bin(b)\n'-0b111101"
}
]
|
How and Why to use f strings in Python3 | by Rahul Agarwal | Towards Data Science | Python provides us with many styles of coding.
And with time, Python has regularly come up with new coding standards and tools that adhere even more to the coding standards in the Zen of Python.
Beautiful is better than ugly.
In this series of posts named Python Shorts, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work.
This post is specifically about using f strings in Python that was introduced in Python 3.6.
Let me explain this with a simple example. Suppose you have some variables, and you want to print them within a statement.
name = 'Andy'age = 20print(?)----------------------------------------------------------------Output: I am Andy. I am 20 years old
You can do this in various ways:
a) Concatenate: A very naive way to do is to simply use + for concatenation within the print function. But that is clumsy. We would need to convert our numeric variables to string and keep care of the spaces while concatenating. And it doesn’t look good as the code readability suffers a little when we use it.
name = 'Andy'age = 20print("I am " + name + ". I am " + str(age) + " years old")----------------------------------------------------------------I am Andy. I am 20 years old
b) % Format: The second option is to use % formatting. But it also has its problems. For one, it is not readable. You would need to look at the first %s and try to find the corresponding variable in the list at the end. And imagine if you have a long list of variables that you may want to print.
print("I am %s. I am %s years old" % (name, age))
c) str.format(): Next comes the way that has been used in most Python 3 codes and has become the standard of printing in Python. Using str.format()
print("I am {}. I am {} years old".format(name, age))
Here we use {} to denote the placeholder of the object in the list. It still has the same problem of readability, but we can also use str.format :
print("I am {name}. I am {age} years old".format(name = name, age = age))
If this seems a little too repetitive, we can use dictionaries too:
data = {'name':'Andy','age':20}print("I am {name}. I am {age} years old".format(**data))
Since Python 3.6, we have a new formatting option, which makes it even more trivial. We could simply use:
print(f"I am {name}. I am {age} years old")
We just append f at the start of the string and use {} to include our variable name, and we get the required results.
An added functionality that f string provides is that we can put expressions in the {} brackets. For Example:
num1 = 4num2 = 5print(f"The sum of {num1} and {num2} is {num1+num2}.")---------------------------------------------------------------The sum of 4 and 5 is 9.
This is quite useful as you can use any sort of expression inside these brackets. The expression can contain dictionaries or functions. A simple example:
def totalFruits(apples,oranges): return apples+orangesdata = {'name':'Andy','age':20}apples = 20oranges = 30print(f"{data['name']} has {totalFruits(apples,oranges)} fruits")----------------------------------------------------------------Andy has 50 fruits
Also, you can use ’’’ to use multiline strings.
num1 = 4num2 = 5print(f'''The sum of {num1} and {num2} is {num1+num2}.''')---------------------------------------------------------------The sum of 4 and 5 is 9.
An everyday use case while formatting strings is to format floats. You can do that using f string as following
numFloat = 10.23456678print(f'Printing Float with 2 decimals: {numFloat:.2f}')-----------------------------------------------------------------Printing Float with 2 decimals: 10.23
Until recently, I had been using Python 2 for all my work, and so was not able to check out this new feature.
But now, as I am shifting to Python 3, f strings has become my go-to syntax to format strings. It is easy to write and read with the ability to incorporate arbitrary expressions as well. In a way, this new function adheres to at least 3 PEP concepts —
Beautiful is better than ugly, Simple is better than complex and Readability counts.
If you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out.
I am going to be writing more of such posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz.
Also, a small disclaimer — There might be some affiliate links in this post to relevant resources, as sharing knowledge is never a bad idea. | [
{
"code": null,
"e": 218,
"s": 171,
"text": "Python provides us with many styles of coding."
},
{
"code": null,
"e": 366,
"s": 218,
"text": "And with time, Python has regularly come up with new coding standards and tools that adhere even more to the coding standards in the Zen of Python."
},
{
"code": null,
"e": 397,
"s": 366,
"text": "Beautiful is better than ugly."
},
{
"code": null,
"e": 606,
"s": 397,
"text": "In this series of posts named Python Shorts, I will explain some simple but very useful constructs provided by Python, some essential tips, and some use cases I come up with regularly in my Data Science work."
},
{
"code": null,
"e": 699,
"s": 606,
"text": "This post is specifically about using f strings in Python that was introduced in Python 3.6."
},
{
"code": null,
"e": 822,
"s": 699,
"text": "Let me explain this with a simple example. Suppose you have some variables, and you want to print them within a statement."
},
{
"code": null,
"e": 952,
"s": 822,
"text": "name = 'Andy'age = 20print(?)----------------------------------------------------------------Output: I am Andy. I am 20 years old"
},
{
"code": null,
"e": 985,
"s": 952,
"text": "You can do this in various ways:"
},
{
"code": null,
"e": 1296,
"s": 985,
"text": "a) Concatenate: A very naive way to do is to simply use + for concatenation within the print function. But that is clumsy. We would need to convert our numeric variables to string and keep care of the spaces while concatenating. And it doesn’t look good as the code readability suffers a little when we use it."
},
{
"code": null,
"e": 1469,
"s": 1296,
"text": "name = 'Andy'age = 20print(\"I am \" + name + \". I am \" + str(age) + \" years old\")----------------------------------------------------------------I am Andy. I am 20 years old"
},
{
"code": null,
"e": 1766,
"s": 1469,
"text": "b) % Format: The second option is to use % formatting. But it also has its problems. For one, it is not readable. You would need to look at the first %s and try to find the corresponding variable in the list at the end. And imagine if you have a long list of variables that you may want to print."
},
{
"code": null,
"e": 1816,
"s": 1766,
"text": "print(\"I am %s. I am %s years old\" % (name, age))"
},
{
"code": null,
"e": 1964,
"s": 1816,
"text": "c) str.format(): Next comes the way that has been used in most Python 3 codes and has become the standard of printing in Python. Using str.format()"
},
{
"code": null,
"e": 2018,
"s": 1964,
"text": "print(\"I am {}. I am {} years old\".format(name, age))"
},
{
"code": null,
"e": 2165,
"s": 2018,
"text": "Here we use {} to denote the placeholder of the object in the list. It still has the same problem of readability, but we can also use str.format :"
},
{
"code": null,
"e": 2239,
"s": 2165,
"text": "print(\"I am {name}. I am {age} years old\".format(name = name, age = age))"
},
{
"code": null,
"e": 2307,
"s": 2239,
"text": "If this seems a little too repetitive, we can use dictionaries too:"
},
{
"code": null,
"e": 2396,
"s": 2307,
"text": "data = {'name':'Andy','age':20}print(\"I am {name}. I am {age} years old\".format(**data))"
},
{
"code": null,
"e": 2502,
"s": 2396,
"text": "Since Python 3.6, we have a new formatting option, which makes it even more trivial. We could simply use:"
},
{
"code": null,
"e": 2546,
"s": 2502,
"text": "print(f\"I am {name}. I am {age} years old\")"
},
{
"code": null,
"e": 2664,
"s": 2546,
"text": "We just append f at the start of the string and use {} to include our variable name, and we get the required results."
},
{
"code": null,
"e": 2774,
"s": 2664,
"text": "An added functionality that f string provides is that we can put expressions in the {} brackets. For Example:"
},
{
"code": null,
"e": 2932,
"s": 2774,
"text": "num1 = 4num2 = 5print(f\"The sum of {num1} and {num2} is {num1+num2}.\")---------------------------------------------------------------The sum of 4 and 5 is 9."
},
{
"code": null,
"e": 3086,
"s": 2932,
"text": "This is quite useful as you can use any sort of expression inside these brackets. The expression can contain dictionaries or functions. A simple example:"
},
{
"code": null,
"e": 3345,
"s": 3086,
"text": "def totalFruits(apples,oranges): return apples+orangesdata = {'name':'Andy','age':20}apples = 20oranges = 30print(f\"{data['name']} has {totalFruits(apples,oranges)} fruits\")----------------------------------------------------------------Andy has 50 fruits"
},
{
"code": null,
"e": 3393,
"s": 3345,
"text": "Also, you can use ’’’ to use multiline strings."
},
{
"code": null,
"e": 3555,
"s": 3393,
"text": "num1 = 4num2 = 5print(f'''The sum of {num1} and {num2} is {num1+num2}.''')---------------------------------------------------------------The sum of 4 and 5 is 9."
},
{
"code": null,
"e": 3666,
"s": 3555,
"text": "An everyday use case while formatting strings is to format floats. You can do that using f string as following"
},
{
"code": null,
"e": 3847,
"s": 3666,
"text": "numFloat = 10.23456678print(f'Printing Float with 2 decimals: {numFloat:.2f}')-----------------------------------------------------------------Printing Float with 2 decimals: 10.23"
},
{
"code": null,
"e": 3957,
"s": 3847,
"text": "Until recently, I had been using Python 2 for all my work, and so was not able to check out this new feature."
},
{
"code": null,
"e": 4209,
"s": 3957,
"text": "But now, as I am shifting to Python 3, f strings has become my go-to syntax to format strings. It is easy to write and read with the ability to incorporate arbitrary expressions as well. In a way, this new function adheres to at least 3 PEP concepts —"
},
{
"code": null,
"e": 4294,
"s": 4209,
"text": "Beautiful is better than ugly, Simple is better than complex and Readability counts."
},
{
"code": null,
"e": 4466,
"s": 4294,
"text": "If you want to learn more about Python 3, I would like to call out an excellent course on Learn Intermediate level Python from the University of Michigan. Do check it out."
},
{
"code": null,
"e": 4744,
"s": 4466,
"text": "I am going to be writing more of such posts in the future too. Let me know what you think about the series. Follow me up at Medium or Subscribe to my blog to be informed about them. As always, I welcome feedback and constructive criticism and can be reached on Twitter @mlwhiz."
}
]
|
Matplotlib.pyplot.hlines() in Python - GeeksforGeeks | 19 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The Matplotlib.pyplot.hlines() is used to draw horizontal lines in a graph at each y from xmin to xmax.
Syntax: matplotlib.pyplot.hlines(y, xmin, xmax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs
Parameters:The Matplotlib.pyplot.hlines() accepts the below-described parameters:
y : It is a required parameter for this method. This parameter describes that in the graph the line is to be drawn. Its value is a scalar or sequence of scalars, in other words, it is the y-indexes where the line is to be plotted.
xmin: It is a required parameter that has either a scalar value or a 1D array-like value that sets the beginning of each line. If scalars are provided all the lines will have the same length.
colors: As the name suggests it is used to set the color of the line to be plotted. This parameter is optional in nature and its default value is ‘k’
linestyles: It is also an optional parameter that accepts four values namely ‘solid’, ‘dashed’, ‘dashdot’ and ‘dotted’. It is responsible for setting the style of the line to be plotted.
label: It is an optional parameter used to describe information about the plotted line in the same line. This accepts a string whose default value is an empty string.
**kwargs: This parameter is used to make use of LineCollection properties in the plotted line.
Note: In addition to the above-mentioned parameters, this method can take a data keyword argument. It is also important to note that the object passed as data must support item access and membership test.
from matplotlib import pyplot as plt plt.hlines(y = 1, xmin = 1, xmax = 4) plt.hlines(y = 1.6, xmin = 1.5, xmax = 4.5) plt.hlines(y = 2, xmin = 2, xmax = 5)
Output :
Example 2:
from matplotlib import pyplot as plt plt.hlines(y = 1, xmin = 1, xmax = 4, label ="black line") plt.hlines(y = 1.6, xmin = 1.5, xmax = 4.5, color ='r')plt.text(1, 1.6, 'Red line', ha ='left', va ='center') plt.hlines(y = 2, xmin = 2, xmax = 5)
Output :
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python | [
{
"code": null,
"e": 24463,
"s": 24435,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 24675,
"s": 24463,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack."
},
{
"code": null,
"e": 24779,
"s": 24675,
"text": "The Matplotlib.pyplot.hlines() is used to draw horizontal lines in a graph at each y from xmin to xmax."
},
{
"code": null,
"e": 24891,
"s": 24779,
"text": "Syntax: matplotlib.pyplot.hlines(y, xmin, xmax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs"
},
{
"code": null,
"e": 24973,
"s": 24891,
"text": "Parameters:The Matplotlib.pyplot.hlines() accepts the below-described parameters:"
},
{
"code": null,
"e": 25204,
"s": 24973,
"text": "y : It is a required parameter for this method. This parameter describes that in the graph the line is to be drawn. Its value is a scalar or sequence of scalars, in other words, it is the y-indexes where the line is to be plotted."
},
{
"code": null,
"e": 25396,
"s": 25204,
"text": "xmin: It is a required parameter that has either a scalar value or a 1D array-like value that sets the beginning of each line. If scalars are provided all the lines will have the same length."
},
{
"code": null,
"e": 25546,
"s": 25396,
"text": "colors: As the name suggests it is used to set the color of the line to be plotted. This parameter is optional in nature and its default value is ‘k’"
},
{
"code": null,
"e": 25733,
"s": 25546,
"text": "linestyles: It is also an optional parameter that accepts four values namely ‘solid’, ‘dashed’, ‘dashdot’ and ‘dotted’. It is responsible for setting the style of the line to be plotted."
},
{
"code": null,
"e": 25900,
"s": 25733,
"text": "label: It is an optional parameter used to describe information about the plotted line in the same line. This accepts a string whose default value is an empty string."
},
{
"code": null,
"e": 25995,
"s": 25900,
"text": "**kwargs: This parameter is used to make use of LineCollection properties in the plotted line."
},
{
"code": null,
"e": 26200,
"s": 25995,
"text": "Note: In addition to the above-mentioned parameters, this method can take a data keyword argument. It is also important to note that the object passed as data must support item access and membership test."
},
{
"code": "from matplotlib import pyplot as plt plt.hlines(y = 1, xmin = 1, xmax = 4) plt.hlines(y = 1.6, xmin = 1.5, xmax = 4.5) plt.hlines(y = 2, xmin = 2, xmax = 5)",
"e": 26360,
"s": 26200,
"text": null
},
{
"code": null,
"e": 26369,
"s": 26360,
"text": "Output :"
},
{
"code": null,
"e": 26380,
"s": 26369,
"text": "Example 2:"
},
{
"code": "from matplotlib import pyplot as plt plt.hlines(y = 1, xmin = 1, xmax = 4, label =\"black line\") plt.hlines(y = 1.6, xmin = 1.5, xmax = 4.5, color ='r')plt.text(1, 1.6, 'Red line', ha ='left', va ='center') plt.hlines(y = 2, xmin = 2, xmax = 5)",
"e": 26627,
"s": 26380,
"text": null
},
{
"code": null,
"e": 26636,
"s": 26627,
"text": "Output :"
},
{
"code": null,
"e": 26654,
"s": 26636,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 26661,
"s": 26654,
"text": "Python"
},
{
"code": null,
"e": 26677,
"s": 26661,
"text": "Write From Home"
},
{
"code": null,
"e": 26775,
"s": 26677,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26784,
"s": 26775,
"text": "Comments"
},
{
"code": null,
"e": 26797,
"s": 26784,
"text": "Old Comments"
},
{
"code": null,
"e": 26834,
"s": 26797,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26852,
"s": 26834,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26875,
"s": 26852,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 26897,
"s": 26875,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26936,
"s": 26897,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26972,
"s": 26936,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 27008,
"s": 26972,
"text": "Convert string to integer in Python"
},
{
"code": null,
"e": 27024,
"s": 27008,
"text": "Python infinity"
},
{
"code": null,
"e": 27085,
"s": 27024,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
]
|
Python Blockchain - Creating Miners | For enabling mining, we need to develop a mining function. The mining functionality needs to generate a digest on a given message string and provide a proof-of-work. Let us discuss this in this chapter.
We will write a utility function called sha256 for creating a digest on a given message −
def sha256(message):
return hashlib.sha256(message.encode('ascii')).hexdigest()
The sha256 function takes a message as a parameter, encodes it to ASCII, generates a hexadecimal digest and returns the value to the caller.
We now develop the mine function that implements our own mining strategy. Our strategy in this case would be to generate a hash on the given message that is prefixed with a given number of 1’s. The given number of 1’s is specified as a parameter to mine function specified as the difficulty level.
For example, if you specify a difficulty level of 2, the generated hash on a given message should start with two 1’s - like 11xxxxxxxx. If the difficulty level is 3, the generated hash should start with three 1’s - like 111xxxxxxxx. Given these requirements, we will now develop the mining function as shown in the steps given below.
The mining function takes two parameters - the message and the difficulty level.
def mine(message, difficulty=1):
The difficulty level needs to be greater or equal to 1, we ensure this with the following assert statement −
assert difficulty >= 1
We create a prefix variable using the set difficulty level.
prefix = '1' * difficulty
Note if the difficulty level is 2 the prefix would be “11” and if the difficulty level is 3, the prefix would be “111”, and so on. We will check if this prefix exists in the generated digest of the message. To digest the message itself, we use the following two lines of code −
for i in range(1000):
digest = sha256(str(hash(message)) + str(i))
We keep on adding a new number i to the message hash in each iteration and generate a new digest on the combined message. As the input to the sha256 function changes in every iteration, the digest value would also change. We check if this digest value has above-set prefix.
if digest.startswith(prefix):
If the condition is satisfied, we will terminate the for loop and return the digest value to the caller.
The entire mine code is shown here −
def mine(message, difficulty=1):
assert difficulty >= 1
prefix = '1' * difficulty
for i in range(1000):
digest = sha256(str(hash(message)) + str(i))
if digest.startswith(prefix):
print ("after " + str(i) + " iterations found nonce: "+ digest)
return digest
For your understanding, we have added the print statement that prints the digest value and the number of iterations it took to meet the condition before returning from the function.
To test our mining function, simply execute the following statement −
mine ("test message", 2)
When you run the above code, you will see the output similar to the one below −
after 138 iterations found nonce:
11008a740eb2fa6bf8d55baecda42a41993ca65ce66b2d3889477e6bfad1484c
Note that the generated digest starts with “11”. If you change the difficulty level to 3, the generated digest will start with “111”, and of course, it will probably require more number of iterations. As you can see, a miner with more processing power will be able to mine a given message earlier. That’s how the miners compete with each other for earning their revenues.
Now, we are ready to add more blocks to our blockchain. Let us learn this in our next chapter.
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": 2198,
"s": 1995,
"text": "For enabling mining, we need to develop a mining function. The mining functionality needs to generate a digest on a given message string and provide a proof-of-work. Let us discuss this in this chapter."
},
{
"code": null,
"e": 2288,
"s": 2198,
"text": "We will write a utility function called sha256 for creating a digest on a given message −"
},
{
"code": null,
"e": 2369,
"s": 2288,
"text": "def sha256(message):\nreturn hashlib.sha256(message.encode('ascii')).hexdigest()\n"
},
{
"code": null,
"e": 2510,
"s": 2369,
"text": "The sha256 function takes a message as a parameter, encodes it to ASCII, generates a hexadecimal digest and returns the value to the caller."
},
{
"code": null,
"e": 2808,
"s": 2510,
"text": "We now develop the mine function that implements our own mining strategy. Our strategy in this case would be to generate a hash on the given message that is prefixed with a given number of 1’s. The given number of 1’s is specified as a parameter to mine function specified as the difficulty level."
},
{
"code": null,
"e": 3142,
"s": 2808,
"text": "For example, if you specify a difficulty level of 2, the generated hash on a given message should start with two 1’s - like 11xxxxxxxx. If the difficulty level is 3, the generated hash should start with three 1’s - like 111xxxxxxxx. Given these requirements, we will now develop the mining function as shown in the steps given below."
},
{
"code": null,
"e": 3223,
"s": 3142,
"text": "The mining function takes two parameters - the message and the difficulty level."
},
{
"code": null,
"e": 3257,
"s": 3223,
"text": "def mine(message, difficulty=1):\n"
},
{
"code": null,
"e": 3366,
"s": 3257,
"text": "The difficulty level needs to be greater or equal to 1, we ensure this with the following assert statement −"
},
{
"code": null,
"e": 3390,
"s": 3366,
"text": "assert difficulty >= 1\n"
},
{
"code": null,
"e": 3450,
"s": 3390,
"text": "We create a prefix variable using the set difficulty level."
},
{
"code": null,
"e": 3477,
"s": 3450,
"text": "prefix = '1' * difficulty\n"
},
{
"code": null,
"e": 3755,
"s": 3477,
"text": "Note if the difficulty level is 2 the prefix would be “11” and if the difficulty level is 3, the prefix would be “111”, and so on. We will check if this prefix exists in the generated digest of the message. To digest the message itself, we use the following two lines of code −"
},
{
"code": null,
"e": 3826,
"s": 3755,
"text": "for i in range(1000):\n digest = sha256(str(hash(message)) + str(i))\n"
},
{
"code": null,
"e": 4100,
"s": 3826,
"text": "We keep on adding a new number i to the message hash in each iteration and generate a new digest on the combined message. As the input to the sha256 function changes in every iteration, the digest value would also change. We check if this digest value has above-set prefix."
},
{
"code": null,
"e": 4131,
"s": 4100,
"text": "if digest.startswith(prefix):\n"
},
{
"code": null,
"e": 4236,
"s": 4131,
"text": "If the condition is satisfied, we will terminate the for loop and return the digest value to the caller."
},
{
"code": null,
"e": 4273,
"s": 4236,
"text": "The entire mine code is shown here −"
},
{
"code": null,
"e": 4567,
"s": 4273,
"text": "def mine(message, difficulty=1):\n assert difficulty >= 1\n prefix = '1' * difficulty\n for i in range(1000):\n digest = sha256(str(hash(message)) + str(i))\n if digest.startswith(prefix):\n print (\"after \" + str(i) + \" iterations found nonce: \"+ digest)\n return digest\n"
},
{
"code": null,
"e": 4749,
"s": 4567,
"text": "For your understanding, we have added the print statement that prints the digest value and the number of iterations it took to meet the condition before returning from the function."
},
{
"code": null,
"e": 4819,
"s": 4749,
"text": "To test our mining function, simply execute the following statement −"
},
{
"code": null,
"e": 4845,
"s": 4819,
"text": "mine (\"test message\", 2)\n"
},
{
"code": null,
"e": 4925,
"s": 4845,
"text": "When you run the above code, you will see the output similar to the one below −"
},
{
"code": null,
"e": 5025,
"s": 4925,
"text": "after 138 iterations found nonce:\n11008a740eb2fa6bf8d55baecda42a41993ca65ce66b2d3889477e6bfad1484c\n"
},
{
"code": null,
"e": 5397,
"s": 5025,
"text": "Note that the generated digest starts with “11”. If you change the difficulty level to 3, the generated digest will start with “111”, and of course, it will probably require more number of iterations. As you can see, a miner with more processing power will be able to mine a given message earlier. That’s how the miners compete with each other for earning their revenues."
},
{
"code": null,
"e": 5492,
"s": 5397,
"text": "Now, we are ready to add more blocks to our blockchain. Let us learn this in our next chapter."
},
{
"code": null,
"e": 5529,
"s": 5492,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5545,
"s": 5529,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5578,
"s": 5545,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5597,
"s": 5578,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5632,
"s": 5597,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5654,
"s": 5632,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 5688,
"s": 5654,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 5716,
"s": 5688,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 5751,
"s": 5716,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 5765,
"s": 5751,
"text": " Lets Kode It"
},
{
"code": null,
"e": 5798,
"s": 5765,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 5815,
"s": 5798,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 5822,
"s": 5815,
"text": " Print"
},
{
"code": null,
"e": 5833,
"s": 5822,
"text": " Add Notes"
}
]
|
Area of a n-sided regular polygon with given side length in C++ | In this problem for finding the area of an n-sided regular polygon with a given side, we will derive the formula for the area of the figure and create a program based on it. But before that let's revise the basics to understand the topic easily.
An N-sided regular polygon is a polygon of n side in which all sides are equal. For example regular pentagon, regular hexagon, etc.
The area is the quantitative representation of the extent of any two-dimensional figure.
To find the area of this figure we need to find the area of individual triangles in the figure and multiply it by the number of sides it has. Since we are given n sided.
Now, from the above figure, we can create a formula for the area.
Each side of the regular polygon can create one triangle of side a (side of a polygon) and angle 180 / n (n is a number of sides of a polygon). So, the area can be found using the formula,
Area of triangle = 1⁄2 * b * h
Now, h = a * tan(180/n)
So , area = 1⁄2 * a * a / 2 * tan(180/n)
= a * a / (4 * tan(180/n))
Using this formula for an individual triangle of the polygon, we can create the area of the whole polygon,
Area of n-sided regular polygon = n * (a * a / (4 * tan(180 /n)))
Step 1 : calculate the value of angle using (180 / n)
Step 2 : Calculate the area of regular polygon using n * (a * a / (4 * tan(180 /n))) .
Step 3 : Print the area of polygon.
Live Demo
#include<iostream>
#include<math.h>
using namespace std;
int main(){
float a = 12, n = 9;
float area=(a * a * n) / (4 * tan((180 / n) * 3.14159 / 180));
cout<<"The area of "<<n<<" sided regular polygon of side "<<a<<" is "<<area;
return 0;
}
The area of 9 sided regular polygon of side 12 is 890.183 | [
{
"code": null,
"e": 1308,
"s": 1062,
"text": "In this problem for finding the area of an n-sided regular polygon with a given side, we will derive the formula for the area of the figure and create a program based on it. But before that let's revise the basics to understand the topic easily."
},
{
"code": null,
"e": 1440,
"s": 1308,
"text": "An N-sided regular polygon is a polygon of n side in which all sides are equal. For example regular pentagon, regular hexagon, etc."
},
{
"code": null,
"e": 1529,
"s": 1440,
"text": "The area is the quantitative representation of the extent of any two-dimensional figure."
},
{
"code": null,
"e": 1699,
"s": 1529,
"text": "To find the area of this figure we need to find the area of individual triangles in the figure and multiply it by the number of sides it has. Since we are given n sided."
},
{
"code": null,
"e": 1765,
"s": 1699,
"text": "Now, from the above figure, we can create a formula for the area."
},
{
"code": null,
"e": 1954,
"s": 1765,
"text": "Each side of the regular polygon can create one triangle of side a (side of a polygon) and angle 180 / n (n is a number of sides of a polygon). So, the area can be found using the formula,"
},
{
"code": null,
"e": 1985,
"s": 1954,
"text": "Area of triangle = 1⁄2 * b * h"
},
{
"code": null,
"e": 2009,
"s": 1985,
"text": "Now, h = a * tan(180/n)"
},
{
"code": null,
"e": 2077,
"s": 2009,
"text": "So , area = 1⁄2 * a * a / 2 * tan(180/n)\n= a * a / (4 * tan(180/n))"
},
{
"code": null,
"e": 2184,
"s": 2077,
"text": "Using this formula for an individual triangle of the polygon, we can create the area of the whole polygon,"
},
{
"code": null,
"e": 2250,
"s": 2184,
"text": "Area of n-sided regular polygon = n * (a * a / (4 * tan(180 /n)))"
},
{
"code": null,
"e": 2427,
"s": 2250,
"text": "Step 1 : calculate the value of angle using (180 / n)\nStep 2 : Calculate the area of regular polygon using n * (a * a / (4 * tan(180 /n))) .\nStep 3 : Print the area of polygon."
},
{
"code": null,
"e": 2438,
"s": 2427,
"text": " Live Demo"
},
{
"code": null,
"e": 2692,
"s": 2438,
"text": "#include<iostream>\n#include<math.h>\nusing namespace std;\nint main(){\n float a = 12, n = 9;\n float area=(a * a * n) / (4 * tan((180 / n) * 3.14159 / 180));\n cout<<\"The area of \"<<n<<\" sided regular polygon of side \"<<a<<\" is \"<<area;\n return 0;\n}"
},
{
"code": null,
"e": 2750,
"s": 2692,
"text": "The area of 9 sided regular polygon of side 12 is 890.183"
}
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.