title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
C# | Math.Abs() Method | Set - 1 - GeeksforGeeks
01 Feb, 2019 In C#, Abs() is a Math class method which is used to return the absolute value of a specified number. This method can be overload by passing the different type of parameters to it. Math.Abs(Decimal)Math.Abs(Double)Math.Abs(Int16)Math.Abs(Int32)Math.Abs(Int64)Math.Abs(SByte)Math.Abs(Single)Math.Abs(Decimal)This method is used to return the absolute value of a Decimal number.Syntax:public static decimal Abs (decimal val);Parameter:val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal.Return Type: It returns a decimal number say r, such that 0 ≀ r ≀ Decimal.MaxValue.Example:// C# Program to illlustrate the// Math.Abs(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking decimal values decimal[] deci = {Decimal.MinValue, 45.14M, 0M, -17.47M, Decimal.MaxValue}; // using foreach loop foreach(decimal value in deci) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335 Absolute value of 45.14 = 45.14 Absolute value of 0 = 0 Absolute value of -17.47 = 17.47 Absolute value of 79228162514264337593543950335 = 79228162514264337593543950335 Math.Abs(Double)This method is used to return the absolute value of a double-precision floating-point number.Syntax:public static double Abs (double val);Parameter:val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double.Return Type: It returns a double-precision floating-point number say r, such that 0 ≀ r ≀ Double.MaxValue.Note:If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity.If the val is equal to NaN then return value will be NaN.Example:// C# Program to illlustrate the// Math.Abs(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking a NaN Double nan = Double.NaN; // Taking double values double[] doub = {Double.MinValue, 27.58, 0.0, 56.48e10, nan, Double.MaxValue}; // using foreach loop foreach(double value in doub) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308 Absolute value of 27.58 = 27.58 Absolute value of 0 = 0 Absolute value of 564800000000 = 564800000000 Absolute value of NaN = NaN Absolute value of 1.79769313486232E+308 = 1.79769313486232E+308 Math.Abs(Int16)This method is used to return the absolute value of a 16-bit signed integer.Syntax:public static short Abs (short val);Parameter:val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16.Return Type: It returns 16-bit signed integer say r, such that 0 ≀ r ≀ Int16.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int16) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking short values short[] sh = {Int16.MaxValue, 1482, -142, 0 }; // using foreach loop foreach(short value in sh) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of 32767 = 32767 Absolute value of 1482 = 1482 Absolute value of -142 = 142 Absolute value of 0 = 0 Math.Abs(Int32)This method is used to return the absolute value of a 32-bit signed integer.Syntax:public static int Abs (int val);Parameter:val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32.Return Type: It returns 32-bit signed integer say r, such that 0 ≀ r ≀ Int32.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int32) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking int values int[] int_val = {Int32.MaxValue, 13482, -65525, 0}; // using foreach loop foreach(int value in int_val) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of 2147483647 = 2147483647 Absolute value of 13482 = 13482 Absolute value of -65525 = 65525 Absolute value of 0 = 0 There are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2My Personal Notes arrow_drop_upSave Math.Abs(Decimal) Math.Abs(Double) Math.Abs(Int16) Math.Abs(Int32) Math.Abs(Int64) Math.Abs(SByte) Math.Abs(Single)Math.Abs(Decimal)This method is used to return the absolute value of a Decimal number.Syntax:public static decimal Abs (decimal val);Parameter:val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal.Return Type: It returns a decimal number say r, such that 0 ≀ r ≀ Decimal.MaxValue.Example:// C# Program to illlustrate the// Math.Abs(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking decimal values decimal[] deci = {Decimal.MinValue, 45.14M, 0M, -17.47M, Decimal.MaxValue}; // using foreach loop foreach(decimal value in deci) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335 Absolute value of 45.14 = 45.14 Absolute value of 0 = 0 Absolute value of -17.47 = 17.47 Absolute value of 79228162514264337593543950335 = 79228162514264337593543950335 Math.Abs(Double)This method is used to return the absolute value of a double-precision floating-point number.Syntax:public static double Abs (double val);Parameter:val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double.Return Type: It returns a double-precision floating-point number say r, such that 0 ≀ r ≀ Double.MaxValue.Note:If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity.If the val is equal to NaN then return value will be NaN.Example:// C# Program to illlustrate the// Math.Abs(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking a NaN Double nan = Double.NaN; // Taking double values double[] doub = {Double.MinValue, 27.58, 0.0, 56.48e10, nan, Double.MaxValue}; // using foreach loop foreach(double value in doub) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308 Absolute value of 27.58 = 27.58 Absolute value of 0 = 0 Absolute value of 564800000000 = 564800000000 Absolute value of NaN = NaN Absolute value of 1.79769313486232E+308 = 1.79769313486232E+308 Math.Abs(Int16)This method is used to return the absolute value of a 16-bit signed integer.Syntax:public static short Abs (short val);Parameter:val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16.Return Type: It returns 16-bit signed integer say r, such that 0 ≀ r ≀ Int16.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int16) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking short values short[] sh = {Int16.MaxValue, 1482, -142, 0 }; // using foreach loop foreach(short value in sh) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of 32767 = 32767 Absolute value of 1482 = 1482 Absolute value of -142 = 142 Absolute value of 0 = 0 Math.Abs(Int32)This method is used to return the absolute value of a 32-bit signed integer.Syntax:public static int Abs (int val);Parameter:val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32.Return Type: It returns 32-bit signed integer say r, such that 0 ≀ r ≀ Int32.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int32) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking int values int[] int_val = {Int32.MaxValue, 13482, -65525, 0}; // using foreach loop foreach(int value in int_val) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }}Output:Absolute value of 2147483647 = 2147483647 Absolute value of 13482 = 13482 Absolute value of -65525 = 65525 Absolute value of 0 = 0 There are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2My Personal Notes arrow_drop_upSave This method is used to return the absolute value of a Decimal number. Syntax: public static decimal Abs (decimal val); Parameter: val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal. Return Type: It returns a decimal number say r, such that 0 ≀ r ≀ Decimal.MaxValue. Example: // C# Program to illlustrate the// Math.Abs(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking decimal values decimal[] deci = {Decimal.MinValue, 45.14M, 0M, -17.47M, Decimal.MaxValue}; // using foreach loop foreach(decimal value in deci) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }} Output: Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335 Absolute value of 45.14 = 45.14 Absolute value of 0 = 0 Absolute value of -17.47 = 17.47 Absolute value of 79228162514264337593543950335 = 79228162514264337593543950335 This method is used to return the absolute value of a double-precision floating-point number. Syntax: public static double Abs (double val); Parameter: val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double. Return Type: It returns a double-precision floating-point number say r, such that 0 ≀ r ≀ Double.MaxValue. Note: If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity. If the val is equal to NaN then return value will be NaN. Example: // C# Program to illlustrate the// Math.Abs(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking a NaN Double nan = Double.NaN; // Taking double values double[] doub = {Double.MinValue, 27.58, 0.0, 56.48e10, nan, Double.MaxValue}; // using foreach loop foreach(double value in doub) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }} Output: Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308 Absolute value of 27.58 = 27.58 Absolute value of 0 = 0 Absolute value of 564800000000 = 564800000000 Absolute value of NaN = NaN Absolute value of 1.79769313486232E+308 = 1.79769313486232E+308 This method is used to return the absolute value of a 16-bit signed integer. Syntax: public static short Abs (short val); Parameter: val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16. Return Type: It returns 16-bit signed integer say r, such that 0 ≀ r ≀ Int16.MaxValue. Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue. Example: // C# Program to illlustrate the// Math.Abs(Int16) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking short values short[] sh = {Int16.MaxValue, 1482, -142, 0 }; // using foreach loop foreach(short value in sh) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }} Output: Absolute value of 32767 = 32767 Absolute value of 1482 = 1482 Absolute value of -142 = 142 Absolute value of 0 = 0 This method is used to return the absolute value of a 32-bit signed integer. Syntax: public static int Abs (int val); Parameter: val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32. Return Type: It returns 32-bit signed integer say r, such that 0 ≀ r ≀ Int32.MaxValue. Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue. Example: // C# Program to illlustrate the// Math.Abs(Int32) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking int values int[] int_val = {Int32.MaxValue, 13482, -65525, 0}; // using foreach loop foreach(int value in int_val) // Displaying the result Console.WriteLine("Absolute value of {0} = {1}", value, Math.Abs(value)); }} Output: Absolute value of 2147483647 = 2147483647 Absolute value of 13482 = 13482 Absolute value of -65525 = 65525 Absolute value of 0 = 0 There are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2 CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | Constructors C# | String.IndexOf( ) Method | Set - 1
[ { "code": null, "e": 25777, "s": 25749, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25958, "s": 25777, "text": "In C#, Abs() is a Math class method which is used to return the absolute value of a specified number. This method can be overload by passing the different type of parameters to it." }, { "code": null, "e": 31051, "s": 25958, "text": "Math.Abs(Decimal)Math.Abs(Double)Math.Abs(Int16)Math.Abs(Int32)Math.Abs(Int64)Math.Abs(SByte)Math.Abs(Single)Math.Abs(Decimal)This method is used to return the absolute value of a Decimal number.Syntax:public static decimal Abs (decimal val);Parameter:val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal.Return Type: It returns a decimal number say r, such that 0 ≀ r ≀ Decimal.MaxValue.Example:// C# Program to illlustrate the// Math.Abs(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking decimal values decimal[] deci = {Decimal.MinValue, 45.14M, 0M, -17.47M, Decimal.MaxValue}; // using foreach loop foreach(decimal value in deci) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335\nAbsolute value of 45.14 = 45.14\nAbsolute value of 0 = 0\nAbsolute value of -17.47 = 17.47\nAbsolute value of 79228162514264337593543950335 = 79228162514264337593543950335\nMath.Abs(Double)This method is used to return the absolute value of a double-precision floating-point number.Syntax:public static double Abs (double val);Parameter:val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double.Return Type: It returns a double-precision floating-point number say r, such that 0 ≀ r ≀ Double.MaxValue.Note:If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity.If the val is equal to NaN then return value will be NaN.Example:// C# Program to illlustrate the// Math.Abs(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking a NaN Double nan = Double.NaN; // Taking double values double[] doub = {Double.MinValue, 27.58, 0.0, 56.48e10, nan, Double.MaxValue}; // using foreach loop foreach(double value in doub) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308\nAbsolute value of 27.58 = 27.58\nAbsolute value of 0 = 0\nAbsolute value of 564800000000 = 564800000000\nAbsolute value of NaN = NaN\nAbsolute value of 1.79769313486232E+308 = 1.79769313486232E+308\nMath.Abs(Int16)This method is used to return the absolute value of a 16-bit signed integer.Syntax:public static short Abs (short val);Parameter:val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16.Return Type: It returns 16-bit signed integer say r, such that 0 ≀ r ≀ Int16.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int16) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking short values short[] sh = {Int16.MaxValue, 1482, -142, 0 }; // using foreach loop foreach(short value in sh) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of 32767 = 32767\nAbsolute value of 1482 = 1482\nAbsolute value of -142 = 142\nAbsolute value of 0 = 0\nMath.Abs(Int32)This method is used to return the absolute value of a 32-bit signed integer.Syntax:public static int Abs (int val);Parameter:val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32.Return Type: It returns 32-bit signed integer say r, such that 0 ≀ r ≀ Int32.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int32) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking int values int[] int_val = {Int32.MaxValue, 13482, -65525, 0}; // using foreach loop foreach(int value in int_val) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of 2147483647 = 2147483647\nAbsolute value of 13482 = 13482\nAbsolute value of -65525 = 65525\nAbsolute value of 0 = 0\nThere are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 31069, "s": 31051, "text": "Math.Abs(Decimal)" }, { "code": null, "e": 31086, "s": 31069, "text": "Math.Abs(Double)" }, { "code": null, "e": 31102, "s": 31086, "text": "Math.Abs(Int16)" }, { "code": null, "e": 31118, "s": 31102, "text": "Math.Abs(Int32)" }, { "code": null, "e": 31134, "s": 31118, "text": "Math.Abs(Int64)" }, { "code": null, "e": 31150, "s": 31134, "text": "Math.Abs(SByte)" }, { "code": null, "e": 36150, "s": 31150, "text": "Math.Abs(Single)Math.Abs(Decimal)This method is used to return the absolute value of a Decimal number.Syntax:public static decimal Abs (decimal val);Parameter:val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal.Return Type: It returns a decimal number say r, such that 0 ≀ r ≀ Decimal.MaxValue.Example:// C# Program to illlustrate the// Math.Abs(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking decimal values decimal[] deci = {Decimal.MinValue, 45.14M, 0M, -17.47M, Decimal.MaxValue}; // using foreach loop foreach(decimal value in deci) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335\nAbsolute value of 45.14 = 45.14\nAbsolute value of 0 = 0\nAbsolute value of -17.47 = 17.47\nAbsolute value of 79228162514264337593543950335 = 79228162514264337593543950335\nMath.Abs(Double)This method is used to return the absolute value of a double-precision floating-point number.Syntax:public static double Abs (double val);Parameter:val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double.Return Type: It returns a double-precision floating-point number say r, such that 0 ≀ r ≀ Double.MaxValue.Note:If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity.If the val is equal to NaN then return value will be NaN.Example:// C# Program to illlustrate the// Math.Abs(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking a NaN Double nan = Double.NaN; // Taking double values double[] doub = {Double.MinValue, 27.58, 0.0, 56.48e10, nan, Double.MaxValue}; // using foreach loop foreach(double value in doub) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308\nAbsolute value of 27.58 = 27.58\nAbsolute value of 0 = 0\nAbsolute value of 564800000000 = 564800000000\nAbsolute value of NaN = NaN\nAbsolute value of 1.79769313486232E+308 = 1.79769313486232E+308\nMath.Abs(Int16)This method is used to return the absolute value of a 16-bit signed integer.Syntax:public static short Abs (short val);Parameter:val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16.Return Type: It returns 16-bit signed integer say r, such that 0 ≀ r ≀ Int16.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int16) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking short values short[] sh = {Int16.MaxValue, 1482, -142, 0 }; // using foreach loop foreach(short value in sh) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of 32767 = 32767\nAbsolute value of 1482 = 1482\nAbsolute value of -142 = 142\nAbsolute value of 0 = 0\nMath.Abs(Int32)This method is used to return the absolute value of a 32-bit signed integer.Syntax:public static int Abs (int val);Parameter:val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32.Return Type: It returns 32-bit signed integer say r, such that 0 ≀ r ≀ Int32.MaxValue.Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue.Example:// C# Program to illlustrate the// Math.Abs(Int32) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking int values int[] int_val = {Int32.MaxValue, 13482, -65525, 0}; // using foreach loop foreach(int value in int_val) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}Output:Absolute value of 2147483647 = 2147483647\nAbsolute value of 13482 = 13482\nAbsolute value of -65525 = 65525\nAbsolute value of 0 = 0\nThere are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 36220, "s": 36150, "text": "This method is used to return the absolute value of a Decimal number." }, { "code": null, "e": 36228, "s": 36220, "text": "Syntax:" }, { "code": null, "e": 36269, "s": 36228, "text": "public static decimal Abs (decimal val);" }, { "code": null, "e": 36280, "s": 36269, "text": "Parameter:" }, { "code": null, "e": 36430, "s": 36280, "text": "val: It is the required number which is greater than or equal to Decimal.MinValue, but less than or equal to Decimal.MaxValue of type System.Decimal." }, { "code": null, "e": 36514, "s": 36430, "text": "Return Type: It returns a decimal number say r, such that 0 ≀ r ≀ Decimal.MaxValue." }, { "code": null, "e": 36523, "s": 36514, "text": "Example:" }, { "code": "// C# Program to illlustrate the// Math.Abs(Decimal) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking decimal values decimal[] deci = {Decimal.MinValue, 45.14M, 0M, -17.47M, Decimal.MaxValue}; // using foreach loop foreach(decimal value in deci) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}", "e": 37042, "s": 36523, "text": null }, { "code": null, "e": 37050, "s": 37042, "text": "Output:" }, { "code": null, "e": 37301, "s": 37050, "text": "Absolute value of -79228162514264337593543950335 = 79228162514264337593543950335\nAbsolute value of 45.14 = 45.14\nAbsolute value of 0 = 0\nAbsolute value of -17.47 = 17.47\nAbsolute value of 79228162514264337593543950335 = 79228162514264337593543950335\n" }, { "code": null, "e": 37395, "s": 37301, "text": "This method is used to return the absolute value of a double-precision floating-point number." }, { "code": null, "e": 37403, "s": 37395, "text": "Syntax:" }, { "code": null, "e": 37442, "s": 37403, "text": "public static double Abs (double val);" }, { "code": null, "e": 37453, "s": 37442, "text": "Parameter:" }, { "code": null, "e": 37600, "s": 37453, "text": "val: It is the required number which is greater than or equal to Double.MinValue, but less than or equal to Double.MaxValue of type System.Double." }, { "code": null, "e": 37707, "s": 37600, "text": "Return Type: It returns a double-precision floating-point number say r, such that 0 ≀ r ≀ Double.MaxValue." }, { "code": null, "e": 37713, "s": 37707, "text": "Note:" }, { "code": null, "e": 37813, "s": 37713, "text": "If val is equal to NegativeInfinity or PositiveInfinity, the return value will be PositiveInfinity." }, { "code": null, "e": 37871, "s": 37813, "text": "If the val is equal to NaN then return value will be NaN." }, { "code": null, "e": 37880, "s": 37871, "text": "Example:" }, { "code": "// C# Program to illlustrate the// Math.Abs(Double) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking a NaN Double nan = Double.NaN; // Taking double values double[] doub = {Double.MinValue, 27.58, 0.0, 56.48e10, nan, Double.MaxValue}; // using foreach loop foreach(double value in doub) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}", "e": 38452, "s": 37880, "text": null }, { "code": null, "e": 38460, "s": 38452, "text": "Output:" }, { "code": null, "e": 38720, "s": 38460, "text": "Absolute value of -1.79769313486232E+308 = 1.79769313486232E+308\nAbsolute value of 27.58 = 27.58\nAbsolute value of 0 = 0\nAbsolute value of 564800000000 = 564800000000\nAbsolute value of NaN = NaN\nAbsolute value of 1.79769313486232E+308 = 1.79769313486232E+308\n" }, { "code": null, "e": 38797, "s": 38720, "text": "This method is used to return the absolute value of a 16-bit signed integer." }, { "code": null, "e": 38805, "s": 38797, "text": "Syntax:" }, { "code": null, "e": 38842, "s": 38805, "text": "public static short Abs (short val);" }, { "code": null, "e": 38853, "s": 38842, "text": "Parameter:" }, { "code": null, "e": 38985, "s": 38853, "text": "val: It is the required number which is greater than Int16.MinValue, but less than or equal to Int16.MaxValue of type System.Int16." }, { "code": null, "e": 39072, "s": 38985, "text": "Return Type: It returns 16-bit signed integer say r, such that 0 ≀ r ≀ Int16.MaxValue." }, { "code": null, "e": 39172, "s": 39072, "text": "Exception: This method will give OverflowException if the value of val is equals to Int16.MinValue." }, { "code": null, "e": 39181, "s": 39172, "text": "Example:" }, { "code": "// C# Program to illlustrate the// Math.Abs(Int16) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking short values short[] sh = {Int16.MaxValue, 1482, -142, 0 }; // using foreach loop foreach(short value in sh) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}", "e": 39636, "s": 39181, "text": null }, { "code": null, "e": 39644, "s": 39636, "text": "Output:" }, { "code": null, "e": 39760, "s": 39644, "text": "Absolute value of 32767 = 32767\nAbsolute value of 1482 = 1482\nAbsolute value of -142 = 142\nAbsolute value of 0 = 0\n" }, { "code": null, "e": 39837, "s": 39760, "text": "This method is used to return the absolute value of a 32-bit signed integer." }, { "code": null, "e": 39845, "s": 39837, "text": "Syntax:" }, { "code": null, "e": 39878, "s": 39845, "text": "public static int Abs (int val);" }, { "code": null, "e": 39889, "s": 39878, "text": "Parameter:" }, { "code": null, "e": 40021, "s": 39889, "text": "val: It is the required number which is greater than Int32.MinValue, but less than or equal to Int32.MaxValue of type System.Int32." }, { "code": null, "e": 40108, "s": 40021, "text": "Return Type: It returns 32-bit signed integer say r, such that 0 ≀ r ≀ Int32.MaxValue." }, { "code": null, "e": 40208, "s": 40108, "text": "Exception: This method will give OverflowException if the value of val is equals to Int32.MinValue." }, { "code": null, "e": 40217, "s": 40208, "text": "Example:" }, { "code": "// C# Program to illlustrate the// Math.Abs(Int32) Methodusing System; class Geeks { // Main Method public static void Main() { // Taking int values int[] int_val = {Int32.MaxValue, 13482, -65525, 0}; // using foreach loop foreach(int value in int_val) // Displaying the result Console.WriteLine(\"Absolute value of {0} = {1}\", value, Math.Abs(value)); }}", "e": 40678, "s": 40217, "text": null }, { "code": null, "e": 40686, "s": 40678, "text": "Output:" }, { "code": null, "e": 40818, "s": 40686, "text": "Absolute value of 2147483647 = 2147483647\nAbsolute value of 13482 = 13482\nAbsolute value of -65525 = 65525\nAbsolute value of 0 = 0\n" }, { "code": null, "e": 40987, "s": 40818, "text": "There are total 7 methods in its overload list. Here we will discuss only the first 4 methods and remaining 3 methods are discussed in C# | Math.Abs() Method | Set – 2." }, { "code": null, "e": 41082, "s": 40987, "text": "Reference: https://docs.microsoft.com/en-us/dotnet/api/system.math.abs?view=netframework-4.7.2" }, { "code": null, "e": 41094, "s": 41082, "text": "CSharp-Math" }, { "code": null, "e": 41108, "s": 41094, "text": "CSharp-method" }, { "code": null, "e": 41111, "s": 41108, "text": "C#" }, { "code": null, "e": 41209, "s": 41111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41237, "s": 41209, "text": "C# Dictionary with examples" }, { "code": null, "e": 41252, "s": 41237, "text": "C# | Delegates" }, { "code": null, "e": 41275, "s": 41252, "text": "C# | Method Overriding" }, { "code": null, "e": 41297, "s": 41275, "text": "C# | Abstract Classes" }, { "code": null, "e": 41343, "s": 41297, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 41366, "s": 41343, "text": "Extension Method in C#" }, { "code": null, "e": 41388, "s": 41366, "text": "C# | Class and Object" }, { "code": null, "e": 41410, "s": 41388, "text": "C# | Replace() Method" }, { "code": null, "e": 41428, "s": 41410, "text": "C# | Constructors" } ]
strrev() function in PHP
The strrev() function is used to reverse a string. It returns the reversed string. strrev(str) str βˆ’ The string to be reversed str βˆ’ The string to be reversed The strrev() function returns the reversed string. The following is an example βˆ’ Live Demo <?php echo strrev("Jack"); ?> The following is the output βˆ’ kcaJ Let us see another example βˆ’ Live Demo <?php $val = 7837; echo strrev($val); ?> The following is the output βˆ’ 7387
[ { "code": null, "e": 1145, "s": 1062, "text": "The strrev() function is used to reverse a string. It returns the reversed string." }, { "code": null, "e": 1157, "s": 1145, "text": "strrev(str)" }, { "code": null, "e": 1189, "s": 1157, "text": "str βˆ’ The string to be reversed" }, { "code": null, "e": 1221, "s": 1189, "text": "str βˆ’ The string to be reversed" }, { "code": null, "e": 1272, "s": 1221, "text": "The strrev() function returns the reversed string." }, { "code": null, "e": 1302, "s": 1272, "text": "The following is an example βˆ’" }, { "code": null, "e": 1313, "s": 1302, "text": " Live Demo" }, { "code": null, "e": 1346, "s": 1313, "text": "<?php\n echo strrev(\"Jack\");\n?>" }, { "code": null, "e": 1376, "s": 1346, "text": "The following is the output βˆ’" }, { "code": null, "e": 1381, "s": 1376, "text": "kcaJ" }, { "code": null, "e": 1410, "s": 1381, "text": "Let us see another example βˆ’" }, { "code": null, "e": 1421, "s": 1410, "text": " Live Demo" }, { "code": null, "e": 1468, "s": 1421, "text": "<?php\n $val = 7837;\n echo strrev($val);\n?>" }, { "code": null, "e": 1498, "s": 1468, "text": "The following is the output βˆ’" }, { "code": null, "e": 1503, "s": 1498, "text": "7387" } ]
Merge two arrays using C# AddRange() method
Firstly, set two arrays βˆ’ int[] arr1 = { 15, 20, 27, 56 }; int[] arr2 = { 62, 69, 76, 92 }; Now create a new list and use AddRange() method to merge βˆ’ var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2); After that, convert the merged collection to an array βˆ’ int[] arr3 = myList.ToArray() Let us see the complete code Live Demo using System; using System.Collections.Generic; class Demo { static void Main() { int[] arr1 = { 15, 20, 27, 56 }; int[] arr2 = { 62, 69, 76, 92 }; // displaying array1 Console.WriteLine("Array 1..."); foreach(int ele in arr1) { Console.WriteLine(ele); } // displaying array2 Console.WriteLine("Array 2..."); foreach(int ele in arr2) { Console.WriteLine(ele); } var myList = new List<int>(); myList.AddRange(arr1); myList.AddRange(arr2); int[] arr3 = myList.ToArray(); Console.WriteLine("Merged array.."); foreach (int res in arr3) { Console.WriteLine(res); } } } Array 1... 15 20 27 56 Array 2... 62 69 76 92 Merged array.. 15 20 27 56 62 69 76 92
[ { "code": null, "e": 1088, "s": 1062, "text": "Firstly, set two arrays βˆ’" }, { "code": null, "e": 1154, "s": 1088, "text": "int[] arr1 = { 15, 20, 27, 56 };\nint[] arr2 = { 62, 69, 76, 92 };" }, { "code": null, "e": 1213, "s": 1154, "text": "Now create a new list and use AddRange() method to merge βˆ’" }, { "code": null, "e": 1289, "s": 1213, "text": "var myList = new List<int>();\nmyList.AddRange(arr1);\nmyList.AddRange(arr2);" }, { "code": null, "e": 1345, "s": 1289, "text": "After that, convert the merged collection to an array βˆ’" }, { "code": null, "e": 1375, "s": 1345, "text": "int[] arr3 = myList.ToArray()" }, { "code": null, "e": 1404, "s": 1375, "text": "Let us see the complete code" }, { "code": null, "e": 1415, "s": 1404, "text": " Live Demo" }, { "code": null, "e": 2114, "s": 1415, "text": "using System;\nusing System.Collections.Generic;\nclass Demo {\n static void Main() {\n int[] arr1 = { 15, 20, 27, 56 };\n int[] arr2 = { 62, 69, 76, 92 };\n // displaying array1\n Console.WriteLine(\"Array 1...\");\n foreach(int ele in arr1) {\n Console.WriteLine(ele);\n }\n // displaying array2\n Console.WriteLine(\"Array 2...\");\n foreach(int ele in arr2) {\n Console.WriteLine(ele);\n }\n var myList = new List<int>();\n myList.AddRange(arr1);\n myList.AddRange(arr2);\n int[] arr3 = myList.ToArray();\n Console.WriteLine(\"Merged array..\");\n foreach (int res in arr3) {\n Console.WriteLine(res);\n }\n }\n}" }, { "code": null, "e": 2199, "s": 2114, "text": "Array 1...\n15\n20\n27\n56\nArray 2...\n62\n69\n76\n92\nMerged array..\n15\n20\n27\n56\n62\n69\n76\n92" } ]
Hyperparameters of Decision Trees Explained with Visualizations | by Soner YΔ±ldΔ±rΔ±m | Towards Data Science
Decision tree is a widely-used supervised learning algorithm which is suitable for both classification and regression tasks. Decision trees serve as building blocks for some prominent ensemble learning algorithms such as random forests, GBDT, and XGBOOST. A decision tree builds upon iteratively asking questions to partition data. For instance, the following figure represents a decision tree used as a model to predict customer churn. Decision trees are prevalent in the field of machine learning due to their success as well as being straightforward. Some of the features that make them highly efficient: Easy to understand and interpret Can handle both numerical and categorical data Requires little or no preprocessing such as normalization or dummy encoding On the downside, decision trees are prone to overfitting. They can easily become over-complex which prevents them from generalizing well to the structure in the dataset. In that case, the model is likely to end up overfitting which is a serious issue in machine learning. To overcome this issue, we need to carefully adjust the hyperparameters of decision trees. In this post, we will try to gain a comprehensive understanding of these hyperparameters using tree visualizations. We will use one of the built-in datasets of scikit-learn. The wine dataset contains 13 features (i.e.columns) on three different wine classes. There are 178 samples (i.e. rows) in the dataset. import numpy as npimport pandas as pdfrom sklearn.datasets import load_wineX, y = load_wine(return_X_y = True) Let’s start with a decision tree classifier without any hyperparameter tuning. from sklearn import treeclf = tree.DecisionTreeClassifier()clf.fit(X, y) All of the hyperparameters are set with the default settings. We can plot our model using plot_tree function. import matplotlib.pyplot as plt%matplotlib inlineplt.figure(figsize=(24,14))tree.plot_tree(clf, filled=True, fontsize=14) The model keeps splitting the nodes until all the nodes are pure (i.e. contain samples from only one class). Let’s first understand what the information in a box tells us. The first line indicates the name of the feature (i.e. column). Since we did not name the columns, the index of the column is shown. Samples indicates the number of observations (i.e. rows) and value shows the distribution of these samples according to the target variable. Gini is a measure of impurity. As stated on wikipedia, β€œGini impurity is a measure of how often a randomly chosen element from the set would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset”. It basically means that impurity increases with randomness. For instance, let’s say we have a box with ten balls in it. If all the balls are same color, we have no randomness and impurity is zero. However, if we have 5 blue balls and 5 red balls, impurity is 1. If you take a look the leaf nodes (the nodes at the end of tree), you will see that gini is equal to zero. The other function to evaluate the quality of a split is entropy which is a measure of uncertainty or randomness. The more randomness a variable has, the higher the entropy is. We can select gini or impurity using criterion parameter. The default value is gini. We usually do not want a tree with all pure leaf nodes. It would be too specific and likely to overfit. When the algorithm performs a split, the main goal is to decrease impurity as much as possible. The more the impurity decreases, the more informative power that split gains. As the tree gets deeper, the amount of impurity decrease becomes lower. We can use this to prevent the tree from doing further splits. The hyperparameter for this task is min_impurity_decrease. It is set to zero by default. Let’s change it and see the difference. clf = tree.DecisionTreeClassifier(min_impurity_decrease=0.2)clf.fit(X, y)plt.figure(figsize=(18,10))tree.plot_tree(clf, filled=True, fontsize=14) We now have a much smaller tree. Consider the green node at the bottom. It contains 65 samples and 61 of them belong to one class. There is no need to further split that node because we can afford to have 4 misclassified samples out of 65. If we keep splitting that node, the model will probably be overfitting. Min_impurity_split parameter can be used to control the tree based on impurity values. It sets a threshold on gini. For instance, if min_impurity_split is set to 0.3, a node needs to have a gini value that is more then 0.3 to be further splitted. Another hyperparameter to control the depth of a tree is max_depth. It does not make any calculations regarding impurity or sample ratio. The model stops splitting when max_depth is reached. clf = tree.DecisionTreeClassifier(max_depth=3)clf.fit(X, y)plt.figure(figsize=(20,10))tree.plot_tree(clf, filled=True, fontsize=14) Max_depth is less flexible compared to min_impurity_decrease. For instance, we probably should not make the split on the left. It only distinguishes 2 samples and decreases the impurity by less than 0.1. This actually brings us to another hyperparameter which is min_samples_leaf. It indicates the minimum number of samples required to be at a leaf node. We need to be careful when using hyperparameters together. For instance, if we set min_samples_leaf to 3 in the previous tree, the split that separates 2 samples will not occur because we cannot have a leaf node with less than 3 samples. Well, it’s not quite right. Let’s see what really happens. clf = tree.DecisionTreeClassifier(max_depth=3,min_samples_leaf=3)clf.fit(X, y)plt.figure(figsize=(20,10))tree.plot_tree(clf, filled=True, fontsize=14) In this case, min_samples_leaf is actually harmful for the model. It did not prevent the model from doing that final split. Furthermore, it caused extra misclassifications. Thus, it is not wise to use min_samples_leaf in this way. We can also limit the number of leaf nodes using max_leaf_nodes parameter which grows the tree in best-first fashion until max_leaf_nodes reached. The best split is decided based on impurity decrease. clf = tree.DecisionTreeClassifier(max_leaf_nodes=5)clf.fit(X, y)plt.figure(figsize=(20,10))tree.plot_tree(clf, filled=True, fontsize=14) We end up having a tree with 5 leaf nodes. Another important hyperparameter of decision trees is max_features which is the number of features to consider when looking for the best split. If not specified, the model considers all of the features. There are 13 features in our dataset. If we set max_features as 5, the model randomly selects 5 features to decide on the next split. Max_features parameter also helps preventing the model from overfitting but it is not enough just to use max_features. If we let the model to become too deep, it will end up using all the features anyway. The hyperparameters need to be carefully adjusted in order to have a robust decision tree with a high out-of-sample accuracy. We do not have to use all of them. Depending on the task and the dataset, a couple of them could be enough. Please pay extra attention if you use multiple hyperparameters together because one may negatively effect the other. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 428, "s": 172, "text": "Decision tree is a widely-used supervised learning algorithm which is suitable for both classification and regression tasks. Decision trees serve as building blocks for some prominent ensemble learning algorithms such as random forests, GBDT, and XGBOOST." }, { "code": null, "e": 609, "s": 428, "text": "A decision tree builds upon iteratively asking questions to partition data. For instance, the following figure represents a decision tree used as a model to predict customer churn." }, { "code": null, "e": 780, "s": 609, "text": "Decision trees are prevalent in the field of machine learning due to their success as well as being straightforward. Some of the features that make them highly efficient:" }, { "code": null, "e": 813, "s": 780, "text": "Easy to understand and interpret" }, { "code": null, "e": 860, "s": 813, "text": "Can handle both numerical and categorical data" }, { "code": null, "e": 936, "s": 860, "text": "Requires little or no preprocessing such as normalization or dummy encoding" }, { "code": null, "e": 1208, "s": 936, "text": "On the downside, decision trees are prone to overfitting. They can easily become over-complex which prevents them from generalizing well to the structure in the dataset. In that case, the model is likely to end up overfitting which is a serious issue in machine learning." }, { "code": null, "e": 1415, "s": 1208, "text": "To overcome this issue, we need to carefully adjust the hyperparameters of decision trees. In this post, we will try to gain a comprehensive understanding of these hyperparameters using tree visualizations." }, { "code": null, "e": 1608, "s": 1415, "text": "We will use one of the built-in datasets of scikit-learn. The wine dataset contains 13 features (i.e.columns) on three different wine classes. There are 178 samples (i.e. rows) in the dataset." }, { "code": null, "e": 1719, "s": 1608, "text": "import numpy as npimport pandas as pdfrom sklearn.datasets import load_wineX, y = load_wine(return_X_y = True)" }, { "code": null, "e": 1798, "s": 1719, "text": "Let’s start with a decision tree classifier without any hyperparameter tuning." }, { "code": null, "e": 1871, "s": 1798, "text": "from sklearn import treeclf = tree.DecisionTreeClassifier()clf.fit(X, y)" }, { "code": null, "e": 1981, "s": 1871, "text": "All of the hyperparameters are set with the default settings. We can plot our model using plot_tree function." }, { "code": null, "e": 2103, "s": 1981, "text": "import matplotlib.pyplot as plt%matplotlib inlineplt.figure(figsize=(24,14))tree.plot_tree(clf, filled=True, fontsize=14)" }, { "code": null, "e": 2261, "s": 2103, "text": "The model keeps splitting the nodes until all the nodes are pure (i.e. contain samples from only one class). Let’s first understand what the information in a" }, { "code": null, "e": 2549, "s": 2261, "text": "box tells us. The first line indicates the name of the feature (i.e. column). Since we did not name the columns, the index of the column is shown. Samples indicates the number of observations (i.e. rows) and value shows the distribution of these samples according to the target variable." }, { "code": null, "e": 3165, "s": 2549, "text": "Gini is a measure of impurity. As stated on wikipedia, β€œGini impurity is a measure of how often a randomly chosen element from the set would be incorrectly labeled if it was randomly labeled according to the distribution of labels in the subset”. It basically means that impurity increases with randomness. For instance, let’s say we have a box with ten balls in it. If all the balls are same color, we have no randomness and impurity is zero. However, if we have 5 blue balls and 5 red balls, impurity is 1. If you take a look the leaf nodes (the nodes at the end of tree), you will see that gini is equal to zero." }, { "code": null, "e": 3342, "s": 3165, "text": "The other function to evaluate the quality of a split is entropy which is a measure of uncertainty or randomness. The more randomness a variable has, the higher the entropy is." }, { "code": null, "e": 3427, "s": 3342, "text": "We can select gini or impurity using criterion parameter. The default value is gini." }, { "code": null, "e": 3531, "s": 3427, "text": "We usually do not want a tree with all pure leaf nodes. It would be too specific and likely to overfit." }, { "code": null, "e": 3969, "s": 3531, "text": "When the algorithm performs a split, the main goal is to decrease impurity as much as possible. The more the impurity decreases, the more informative power that split gains. As the tree gets deeper, the amount of impurity decrease becomes lower. We can use this to prevent the tree from doing further splits. The hyperparameter for this task is min_impurity_decrease. It is set to zero by default. Let’s change it and see the difference." }, { "code": null, "e": 4115, "s": 3969, "text": "clf = tree.DecisionTreeClassifier(min_impurity_decrease=0.2)clf.fit(X, y)plt.figure(figsize=(18,10))tree.plot_tree(clf, filled=True, fontsize=14)" }, { "code": null, "e": 4674, "s": 4115, "text": "We now have a much smaller tree. Consider the green node at the bottom. It contains 65 samples and 61 of them belong to one class. There is no need to further split that node because we can afford to have 4 misclassified samples out of 65. If we keep splitting that node, the model will probably be overfitting. Min_impurity_split parameter can be used to control the tree based on impurity values. It sets a threshold on gini. For instance, if min_impurity_split is set to 0.3, a node needs to have a gini value that is more then 0.3 to be further splitted." }, { "code": null, "e": 4865, "s": 4674, "text": "Another hyperparameter to control the depth of a tree is max_depth. It does not make any calculations regarding impurity or sample ratio. The model stops splitting when max_depth is reached." }, { "code": null, "e": 4997, "s": 4865, "text": "clf = tree.DecisionTreeClassifier(max_depth=3)clf.fit(X, y)plt.figure(figsize=(20,10))tree.plot_tree(clf, filled=True, fontsize=14)" }, { "code": null, "e": 5073, "s": 4997, "text": "Max_depth is less flexible compared to min_impurity_decrease. For instance," }, { "code": null, "e": 5649, "s": 5073, "text": "we probably should not make the split on the left. It only distinguishes 2 samples and decreases the impurity by less than 0.1. This actually brings us to another hyperparameter which is min_samples_leaf. It indicates the minimum number of samples required to be at a leaf node. We need to be careful when using hyperparameters together. For instance, if we set min_samples_leaf to 3 in the previous tree, the split that separates 2 samples will not occur because we cannot have a leaf node with less than 3 samples. Well, it’s not quite right. Let’s see what really happens." }, { "code": null, "e": 5800, "s": 5649, "text": "clf = tree.DecisionTreeClassifier(max_depth=3,min_samples_leaf=3)clf.fit(X, y)plt.figure(figsize=(20,10))tree.plot_tree(clf, filled=True, fontsize=14)" }, { "code": null, "e": 6031, "s": 5800, "text": "In this case, min_samples_leaf is actually harmful for the model. It did not prevent the model from doing that final split. Furthermore, it caused extra misclassifications. Thus, it is not wise to use min_samples_leaf in this way." }, { "code": null, "e": 6232, "s": 6031, "text": "We can also limit the number of leaf nodes using max_leaf_nodes parameter which grows the tree in best-first fashion until max_leaf_nodes reached. The best split is decided based on impurity decrease." }, { "code": null, "e": 6369, "s": 6232, "text": "clf = tree.DecisionTreeClassifier(max_leaf_nodes=5)clf.fit(X, y)plt.figure(figsize=(20,10))tree.plot_tree(clf, filled=True, fontsize=14)" }, { "code": null, "e": 6412, "s": 6369, "text": "We end up having a tree with 5 leaf nodes." }, { "code": null, "e": 6954, "s": 6412, "text": "Another important hyperparameter of decision trees is max_features which is the number of features to consider when looking for the best split. If not specified, the model considers all of the features. There are 13 features in our dataset. If we set max_features as 5, the model randomly selects 5 features to decide on the next split. Max_features parameter also helps preventing the model from overfitting but it is not enough just to use max_features. If we let the model to become too deep, it will end up using all the features anyway." }, { "code": null, "e": 7305, "s": 6954, "text": "The hyperparameters need to be carefully adjusted in order to have a robust decision tree with a high out-of-sample accuracy. We do not have to use all of them. Depending on the task and the dataset, a couple of them could be enough. Please pay extra attention if you use multiple hyperparameters together because one may negatively effect the other." } ]
How to convert Decimal to Hexadecimal in Java
To convert decimal to hexadecimal, use any of the two methods i.e. Integer.toHexString() βˆ’ It returns a string representation of the integer argument as an unsigned integer in base 16. Integer.toHexString() βˆ’ It returns a string representation of the integer argument as an unsigned integer in base 16. Integer.parseInt() βˆ’ It allows you to set the radix as well, for example, for hexadecimal set it as 16. Integer.parseInt() βˆ’ It allows you to set the radix as well, for example, for hexadecimal set it as 16. Let us see an example now to convert decimal to hexadecimal using Integer.toHexString() method. Live Demo public class Demo { public static void main( String args[] ) { int dec = 158; System.out.println(Integer.toHexString(dec)); } } 9e Let us see an example now to convert decimal to hexadecimal using Integer.parseInt() method. Live Demo public class Demo { public static void main( String args[] ) { String str = "3d8"; System.out.println(Integer.parseInt(str, 16)); } } 984
[ { "code": null, "e": 1129, "s": 1062, "text": "To convert decimal to hexadecimal, use any of the two methods i.e." }, { "code": null, "e": 1247, "s": 1129, "text": "Integer.toHexString() βˆ’ It returns a string representation of the integer argument as an unsigned integer in base 16." }, { "code": null, "e": 1365, "s": 1247, "text": "Integer.toHexString() βˆ’ It returns a string representation of the integer argument as an unsigned integer in base 16." }, { "code": null, "e": 1469, "s": 1365, "text": "Integer.parseInt() βˆ’ It allows you to set the radix as well, for example, for hexadecimal set it as 16." }, { "code": null, "e": 1573, "s": 1469, "text": "Integer.parseInt() βˆ’ It allows you to set the radix as well, for example, for hexadecimal set it as 16." }, { "code": null, "e": 1669, "s": 1573, "text": "Let us see an example now to convert decimal to hexadecimal using Integer.toHexString() method." }, { "code": null, "e": 1680, "s": 1669, "text": " Live Demo" }, { "code": null, "e": 1826, "s": 1680, "text": "public class Demo {\n public static void main( String args[] ) {\n int dec = 158;\n System.out.println(Integer.toHexString(dec));\n }\n}" }, { "code": null, "e": 1829, "s": 1826, "text": "9e" }, { "code": null, "e": 1922, "s": 1829, "text": "Let us see an example now to convert decimal to hexadecimal using Integer.parseInt() method." }, { "code": null, "e": 1933, "s": 1922, "text": " Live Demo" }, { "code": null, "e": 2085, "s": 1933, "text": "public class Demo {\n public static void main( String args[] ) {\n String str = \"3d8\";\n System.out.println(Integer.parseInt(str, 16));\n }\n}" }, { "code": null, "e": 2089, "s": 2085, "text": "984" } ]
Create Reusable ML Modules with MLflow Projects & Docker | by George Novack | Towards Data Science
Let’s face it, getting a Machine Learning model into production isn’t easy. From pulling together data from disparate sources to tuning hyperparameters and evaluating model performance, there are so many different steps from sandbox to production that, if we’re not careful, can and will end up scattered across a number of interdependent notebooks or scripts that all must be run in the correct order to recreate the model. And to make matters worse, as we iterate and evaluate new versions of our model, it’s easy to neglect to document each combination of hyperparameters and each resulting metric, so that we often lose track of the lessons learned during the iterative model building process. And remember those notebooks that we strung together to produce version 1 of the model? Well, by the time we’re finished building version 2, those notebooks have been tweaked and altered so much that we’d be hopeless to recreate version 1 if we ever needed to. In this article, I’ll show how you can use MLflow and Docker to create ML Projects that are modular, reusable, and that allows you to easily recreate old versions of your model and tune parameters to build and evaluate new ones. MLflow is an open-source suite of tools that help manage the ML model development lifecycle from early experimentation and discovery, all the way to registering the model in a central repository and deploying it as a REST endpoint to perform real-time inference. We won’t be covering the model registry or model deployment tools in this article. Our focus will be on MLflow Tracking, which allows us to evaluate and record model results as we quickly iterate through different versions of the model, and MLflow Projects, which we will use to package our model development workflow into a reusable, parameterized module. In this article, we’ll use TensorFlow and the CelebA dataset to build a basic Convolutional Neural Network to predict whether or not the subject of a given image is smiling or not. We’ll create a Docker image that will act as our training environment and will contain all the dependencies required to train the model. Next, we’ll package the model training code as an MLflow Project, and finally, we’ll create a simple driver program that will kick off multiple runs of the Project asynchronously using different hyperparameter values. In order to follow along, you’ll need Python 3, Docker, and MLflow installed locally. You can install MLflow using pip pip install mlflow Since our focus is on MLflow, I won’t go into great detail on the actual model, but I will briefly go over some code examples and include links to a working end-to-end project at the end of this article. The first order of business is to load the CelebA dataset. We’ll do this using TensorFlow Datasets. The dataset loaded from tfds doesn’t contain explicit target values. Each record is just an image and a set of attributes about the image (e.g. whether or not the person in the image is smiling, is wearing a hat, has a mustache, etc.), so the data_generator() function is used to format the data in a way that can be passed into a model. The function returns a generator that yields each record as a tuple of the following format: (image, 1 if subject is smiling else 0) We’ll create the training and validation datasets for the model by using tf.data.from_generator and passing in the data_generator() function. Next, we’ll build and train a CNN using the training and validation datasets. MLflow Projects allows you to define environments in three different ways: Conda, Docker Container, or Local system. We’ll be using a Docker Container for our project environment. Here’s the Dockerfile for our simple project environment: The requirements.txt file contains the packages needed to run the project: mlflow, tensorflow, and tensorflow-datasets. And the load_data.py script simply loads the CelebA dataset from TensorFlow and stores the results in the /app/data directory. Note: In a real-world scenario, you would probably not store the training/validation data along with the project environment. Instead, your environment would just include the configuration and libraries needed to access the data wherever it is stored (e.g. an on-prem database or a cloud storage account). I’m only doing this here to avoid downloading the dataset from TensorFlow every time the project is run. We’ll now package the model training code from earlier into an MLflow Project. An MLflow Project is simply a directory with an MLproject file that defines a few things about the project: The environment in which the project will run. For us, this is the Docker image that we just created. The project entry point. This will be the python script that builds and trains the model. The parameters that can be passed into the project. We’ll define a few of these below. The first step is to create an MLproject file. It is in this file that we reference the Docker image that will be used as the project environment. We’ll also define any parameters that can be passed into the project. As you can see, our project will use the gnovack/celebs-cnn image as the project environment (this is the Docker image created in the previous section) and will accept a number of parameters: the batch size, number of epochs, number of convolution layers, number of training and validation samples, and a boolean indicating whether or not to perform some random transformations on the input images during training. Next, we’ll modify the model training code to use the parameters passed in and to log training progress using MLflow Tracking. We’ll discuss MLflow Tracking shortly, but for now just know it consists of a Tracking Server, which tracks parameters and metrics during model training runs (which MLflow calls Experiment runs), and a GUI that allows us to view all of our runs and visualize the performance metrics of each run. We can access the project input parameters using argparse like we would with any command-line arguments. Then we can use these parameters to construct the CNN dynamically. We’ll also wrap the model training in an MLflow run using mlflow.start_run()to tell MLflow to track our model training as an MLflow Experiment run. A few notes about the above code: mlflow.tensorflow.autolog() enables automatic logging of parameters, metrics, and models for TensorFlow. MLflow supports automatic logging for several Machine Learning frameworks. See the full list here: https://mlflow.org/docs/latest/tracking.html#automatic-logging. The RandomFlip layer, which randomly rotates the images during training to help prevent overfitting, is now added to the model conditionally based on the value of the randomize-images parameter. The number of convolution layers in the model is now dependent on the value of the convolutions parameter. A Custom Callback has been added to the model.fit call. The MLFlowCallback is a simple Keras Callback class that sends model performance metrics to the MLflow tracking server after each training epoch using mlflow.log_metrics() With our Docker environment defined and our MLflow project created, we can now write a driver program to execute a few runs of the project asynchronously, allowing us to evaluate different combinations of hyperparameters and neural network architectures. Before running the project, we’ll need to start the MLflow tracking server. For this example, we’ll just use your local machine as the tracking server, but in an environment where you are working on a team of engineers and/or data scientists, you would probably want to stand up a shared tracking server that’s always running for all team members to share. Some cloud services like Databricks and Azure Machine Learning even have a built-in MLflow tracking server. To run a local tracking server and open the MLflow GUI, run the following command: mlflow ui We’ll use the mlflow.projects.run() method with a link to the MLflow project in Github, https://github.com/gnovack/celeb-cnn-project, to run the project (you could also use a relative file path to a local directory containing the MLflow Project). The driver script runs the project three times asynchronously with different parameters. We specify synchronous=False so that we can execute all three runs in parallel, and backend='local' indicates that the project will execute on your local machine. MLflow also supports executing Projects on Databricks, or on a Kubernetes cluster. After executing the driver program, go to http://localhost:5000/ to see the three active runs in the MLflow tracking UI. By drilling into each run you can view model performance metrics, which, thanks to the MLFlowCallback we created, are updated after each training epoch, allowing us to plot these metrics over time while our model is still being trained. As you can see from the accuracy numbers, our model isn’t going to win any awards after just a few epochs of training with a small set of data, but you can start to see trends in the performance of the different models (e.g. the top model, which used no convolution layers, seems to be overfitting the data, as the training accuracy is rising steadily while the validation accuracy is remaining fairly static). Once each run finishes, it will output the trained model object as an artifact that can be downloaded from the tracking server, which means that, with MLflow Tracking, we not only have access to the parameters and metrics of historical training runs, but we have access to the trained models as well. When working with more complex models and larger sets of training data, the training process can easily take several hours or days to complete, so being able to view these metrics in real-time allows us to determine which combinations of parameters might or might not yield production-quality models, and gives us the opportunity to stop runs once we start seeing trends like overfitting in the performance metrics. In this article, we’ve seen how we can use MLflow projects to package the development and training of machine learning models into an encapsulated and reusable module, allowing us to train several versions of the model in parallel and compare their performance in real-time during training. MLflow also gives us the ability to keep track of the parameters, metrics, and models associated with each historical project run, which means that we can easily reproduce any previous version of the model if needed. It’s also worth noting that although we used TensorFlow exclusively in this article, MLflow Tracking and MLflow Projects work with all the major ML frameworks. Thanks for reading! I’ll leave links to repositories containing the end-to-end project described in this article, as well as a few helpful documents I referenced while working on this. Feel free to reach out with any questions or comments. Repository containing the code needed to build the Docker environment: https://github.com/gnovack/celeb-cnn-base-image. The resulting image is stored in Docker Hub: https://hub.docker.com/repository/docker/gnovack/celebs-cnn The MLflow Project repository containing the MLproject file and the TensorFlow model code: https://github.com/gnovack/celeb-cnn-project The Driver program that executes parallel runs of the MLflow Project: https://github.com/gnovack/celeb-cnn-driver
[ { "code": null, "e": 870, "s": 172, "text": "Let’s face it, getting a Machine Learning model into production isn’t easy. From pulling together data from disparate sources to tuning hyperparameters and evaluating model performance, there are so many different steps from sandbox to production that, if we’re not careful, can and will end up scattered across a number of interdependent notebooks or scripts that all must be run in the correct order to recreate the model. And to make matters worse, as we iterate and evaluate new versions of our model, it’s easy to neglect to document each combination of hyperparameters and each resulting metric, so that we often lose track of the lessons learned during the iterative model building process." }, { "code": null, "e": 1131, "s": 870, "text": "And remember those notebooks that we strung together to produce version 1 of the model? Well, by the time we’re finished building version 2, those notebooks have been tweaked and altered so much that we’d be hopeless to recreate version 1 if we ever needed to." }, { "code": null, "e": 1360, "s": 1131, "text": "In this article, I’ll show how you can use MLflow and Docker to create ML Projects that are modular, reusable, and that allows you to easily recreate old versions of your model and tune parameters to build and evaluate new ones." }, { "code": null, "e": 1980, "s": 1360, "text": "MLflow is an open-source suite of tools that help manage the ML model development lifecycle from early experimentation and discovery, all the way to registering the model in a central repository and deploying it as a REST endpoint to perform real-time inference. We won’t be covering the model registry or model deployment tools in this article. Our focus will be on MLflow Tracking, which allows us to evaluate and record model results as we quickly iterate through different versions of the model, and MLflow Projects, which we will use to package our model development workflow into a reusable, parameterized module." }, { "code": null, "e": 2516, "s": 1980, "text": "In this article, we’ll use TensorFlow and the CelebA dataset to build a basic Convolutional Neural Network to predict whether or not the subject of a given image is smiling or not. We’ll create a Docker image that will act as our training environment and will contain all the dependencies required to train the model. Next, we’ll package the model training code as an MLflow Project, and finally, we’ll create a simple driver program that will kick off multiple runs of the Project asynchronously using different hyperparameter values." }, { "code": null, "e": 2635, "s": 2516, "text": "In order to follow along, you’ll need Python 3, Docker, and MLflow installed locally. You can install MLflow using pip" }, { "code": null, "e": 2654, "s": 2635, "text": "pip install mlflow" }, { "code": null, "e": 2858, "s": 2654, "text": "Since our focus is on MLflow, I won’t go into great detail on the actual model, but I will briefly go over some code examples and include links to a working end-to-end project at the end of this article." }, { "code": null, "e": 2958, "s": 2858, "text": "The first order of business is to load the CelebA dataset. We’ll do this using TensorFlow Datasets." }, { "code": null, "e": 3389, "s": 2958, "text": "The dataset loaded from tfds doesn’t contain explicit target values. Each record is just an image and a set of attributes about the image (e.g. whether or not the person in the image is smiling, is wearing a hat, has a mustache, etc.), so the data_generator() function is used to format the data in a way that can be passed into a model. The function returns a generator that yields each record as a tuple of the following format:" }, { "code": null, "e": 3430, "s": 3389, "text": "(image, 1 if subject is smiling else 0) " }, { "code": null, "e": 3572, "s": 3430, "text": "We’ll create the training and validation datasets for the model by using tf.data.from_generator and passing in the data_generator() function." }, { "code": null, "e": 3650, "s": 3572, "text": "Next, we’ll build and train a CNN using the training and validation datasets." }, { "code": null, "e": 3830, "s": 3650, "text": "MLflow Projects allows you to define environments in three different ways: Conda, Docker Container, or Local system. We’ll be using a Docker Container for our project environment." }, { "code": null, "e": 3888, "s": 3830, "text": "Here’s the Dockerfile for our simple project environment:" }, { "code": null, "e": 4135, "s": 3888, "text": "The requirements.txt file contains the packages needed to run the project: mlflow, tensorflow, and tensorflow-datasets. And the load_data.py script simply loads the CelebA dataset from TensorFlow and stores the results in the /app/data directory." }, { "code": null, "e": 4546, "s": 4135, "text": "Note: In a real-world scenario, you would probably not store the training/validation data along with the project environment. Instead, your environment would just include the configuration and libraries needed to access the data wherever it is stored (e.g. an on-prem database or a cloud storage account). I’m only doing this here to avoid downloading the dataset from TensorFlow every time the project is run." }, { "code": null, "e": 4733, "s": 4546, "text": "We’ll now package the model training code from earlier into an MLflow Project. An MLflow Project is simply a directory with an MLproject file that defines a few things about the project:" }, { "code": null, "e": 4835, "s": 4733, "text": "The environment in which the project will run. For us, this is the Docker image that we just created." }, { "code": null, "e": 4925, "s": 4835, "text": "The project entry point. This will be the python script that builds and trains the model." }, { "code": null, "e": 5012, "s": 4925, "text": "The parameters that can be passed into the project. We’ll define a few of these below." }, { "code": null, "e": 5229, "s": 5012, "text": "The first step is to create an MLproject file. It is in this file that we reference the Docker image that will be used as the project environment. We’ll also define any parameters that can be passed into the project." }, { "code": null, "e": 5644, "s": 5229, "text": "As you can see, our project will use the gnovack/celebs-cnn image as the project environment (this is the Docker image created in the previous section) and will accept a number of parameters: the batch size, number of epochs, number of convolution layers, number of training and validation samples, and a boolean indicating whether or not to perform some random transformations on the input images during training." }, { "code": null, "e": 6067, "s": 5644, "text": "Next, we’ll modify the model training code to use the parameters passed in and to log training progress using MLflow Tracking. We’ll discuss MLflow Tracking shortly, but for now just know it consists of a Tracking Server, which tracks parameters and metrics during model training runs (which MLflow calls Experiment runs), and a GUI that allows us to view all of our runs and visualize the performance metrics of each run." }, { "code": null, "e": 6172, "s": 6067, "text": "We can access the project input parameters using argparse like we would with any command-line arguments." }, { "code": null, "e": 6387, "s": 6172, "text": "Then we can use these parameters to construct the CNN dynamically. We’ll also wrap the model training in an MLflow run using mlflow.start_run()to tell MLflow to track our model training as an MLflow Experiment run." }, { "code": null, "e": 6421, "s": 6387, "text": "A few notes about the above code:" }, { "code": null, "e": 6689, "s": 6421, "text": "mlflow.tensorflow.autolog() enables automatic logging of parameters, metrics, and models for TensorFlow. MLflow supports automatic logging for several Machine Learning frameworks. See the full list here: https://mlflow.org/docs/latest/tracking.html#automatic-logging." }, { "code": null, "e": 6884, "s": 6689, "text": "The RandomFlip layer, which randomly rotates the images during training to help prevent overfitting, is now added to the model conditionally based on the value of the randomize-images parameter." }, { "code": null, "e": 6991, "s": 6884, "text": "The number of convolution layers in the model is now dependent on the value of the convolutions parameter." }, { "code": null, "e": 7219, "s": 6991, "text": "A Custom Callback has been added to the model.fit call. The MLFlowCallback is a simple Keras Callback class that sends model performance metrics to the MLflow tracking server after each training epoch using mlflow.log_metrics()" }, { "code": null, "e": 7474, "s": 7219, "text": "With our Docker environment defined and our MLflow project created, we can now write a driver program to execute a few runs of the project asynchronously, allowing us to evaluate different combinations of hyperparameters and neural network architectures." }, { "code": null, "e": 7939, "s": 7474, "text": "Before running the project, we’ll need to start the MLflow tracking server. For this example, we’ll just use your local machine as the tracking server, but in an environment where you are working on a team of engineers and/or data scientists, you would probably want to stand up a shared tracking server that’s always running for all team members to share. Some cloud services like Databricks and Azure Machine Learning even have a built-in MLflow tracking server." }, { "code": null, "e": 8022, "s": 7939, "text": "To run a local tracking server and open the MLflow GUI, run the following command:" }, { "code": null, "e": 8032, "s": 8022, "text": "mlflow ui" }, { "code": null, "e": 8368, "s": 8032, "text": "We’ll use the mlflow.projects.run() method with a link to the MLflow project in Github, https://github.com/gnovack/celeb-cnn-project, to run the project (you could also use a relative file path to a local directory containing the MLflow Project). The driver script runs the project three times asynchronously with different parameters." }, { "code": null, "e": 8614, "s": 8368, "text": "We specify synchronous=False so that we can execute all three runs in parallel, and backend='local' indicates that the project will execute on your local machine. MLflow also supports executing Projects on Databricks, or on a Kubernetes cluster." }, { "code": null, "e": 8735, "s": 8614, "text": "After executing the driver program, go to http://localhost:5000/ to see the three active runs in the MLflow tracking UI." }, { "code": null, "e": 8972, "s": 8735, "text": "By drilling into each run you can view model performance metrics, which, thanks to the MLFlowCallback we created, are updated after each training epoch, allowing us to plot these metrics over time while our model is still being trained." }, { "code": null, "e": 9684, "s": 8972, "text": "As you can see from the accuracy numbers, our model isn’t going to win any awards after just a few epochs of training with a small set of data, but you can start to see trends in the performance of the different models (e.g. the top model, which used no convolution layers, seems to be overfitting the data, as the training accuracy is rising steadily while the validation accuracy is remaining fairly static). Once each run finishes, it will output the trained model object as an artifact that can be downloaded from the tracking server, which means that, with MLflow Tracking, we not only have access to the parameters and metrics of historical training runs, but we have access to the trained models as well." }, { "code": null, "e": 10100, "s": 9684, "text": "When working with more complex models and larger sets of training data, the training process can easily take several hours or days to complete, so being able to view these metrics in real-time allows us to determine which combinations of parameters might or might not yield production-quality models, and gives us the opportunity to stop runs once we start seeing trends like overfitting in the performance metrics." }, { "code": null, "e": 10768, "s": 10100, "text": "In this article, we’ve seen how we can use MLflow projects to package the development and training of machine learning models into an encapsulated and reusable module, allowing us to train several versions of the model in parallel and compare their performance in real-time during training. MLflow also gives us the ability to keep track of the parameters, metrics, and models associated with each historical project run, which means that we can easily reproduce any previous version of the model if needed. It’s also worth noting that although we used TensorFlow exclusively in this article, MLflow Tracking and MLflow Projects work with all the major ML frameworks." }, { "code": null, "e": 11008, "s": 10768, "text": "Thanks for reading! I’ll leave links to repositories containing the end-to-end project described in this article, as well as a few helpful documents I referenced while working on this. Feel free to reach out with any questions or comments." }, { "code": null, "e": 11128, "s": 11008, "text": "Repository containing the code needed to build the Docker environment: https://github.com/gnovack/celeb-cnn-base-image." }, { "code": null, "e": 11233, "s": 11128, "text": "The resulting image is stored in Docker Hub: https://hub.docker.com/repository/docker/gnovack/celebs-cnn" }, { "code": null, "e": 11369, "s": 11233, "text": "The MLflow Project repository containing the MLproject file and the TensorFlow model code: https://github.com/gnovack/celeb-cnn-project" } ]
Batch Script - Reading from the Registry
Reading from the registry is done via the REG QUERY command. This command can be used to retrieve values of any key from within the registry. REG QUERY [ROOT\]RegKey /v ValueName [/s] REG QUERY [ROOT\]RegKey /ve --This returns the (default) value Where RegKey is the key which needs to be searched for in the registry. @echo off REG QUERY HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ The above command will query all the keys and their respective values under the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ The output will display all the keys and values under the registry key. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\ This location in the registry has some key information about the windows system such as the System Directory location. HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows Directory REG_EXPAND_SZ %SystemRoot% SystemDirectory REG_EXPAND_SZ %SystemRoot%\system32 NoInteractiveServices REG_DWORD 0x1 CSDBuildNumber REG_DWORD 0x4000 ShellErrorMode REG_DWORD 0x1 ComponentizedBuild REG_DWORD 0x1 CSDVersion REG_DWORD 0x0 ErrorMode REG_DWORD 0x0 CSDReleaseType REG_DWORD 0x0 ShutdownTime REG_BINARY 3AFEF5D05D46D101 Print Add Notes Bookmark this page
[ { "code": null, "e": 2311, "s": 2169, "text": "Reading from the registry is done via the REG QUERY command. This command can be used to retrieve values of any key from within the registry." }, { "code": null, "e": 2418, "s": 2311, "text": "REG QUERY [ROOT\\]RegKey /v ValueName [/s] \nREG QUERY [ROOT\\]RegKey /ve --This returns the (default) value\n" }, { "code": null, "e": 2490, "s": 2418, "text": "Where RegKey is the key which needs to be searched for in the registry." }, { "code": null, "e": 2572, "s": 2490, "text": "@echo off \nREG QUERY HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Windows\\" }, { "code": null, "e": 2726, "s": 2572, "text": "The above command will query all the keys and their respective values under the registry key HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Windows\\" }, { "code": null, "e": 2798, "s": 2726, "text": "The output will display all the keys and values under the registry key." }, { "code": null, "e": 2860, "s": 2798, "text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Windows\\\n" }, { "code": null, "e": 2979, "s": 2860, "text": "This location in the registry has some key information about the windows system such as the System Directory location." }, { "code": null, "e": 3409, "s": 2979, "text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Windows\n Directory REG_EXPAND_SZ %SystemRoot%\n SystemDirectory REG_EXPAND_SZ %SystemRoot%\\system32\n NoInteractiveServices REG_DWORD 0x1\n CSDBuildNumber REG_DWORD 0x4000\n ShellErrorMode REG_DWORD 0x1\n ComponentizedBuild REG_DWORD 0x1\n CSDVersion REG_DWORD 0x0\n ErrorMode REG_DWORD 0x0\n CSDReleaseType REG_DWORD 0x0\n ShutdownTime REG_BINARY 3AFEF5D05D46D101\t\n" }, { "code": null, "e": 3416, "s": 3409, "text": " Print" }, { "code": null, "e": 3427, "s": 3416, "text": " Add Notes" } ]
Aptitude - Arithmetic Online Quiz
Following quiz provides Multiple Choice Questions (MCQs) related to Basic Arithmetic. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz. Q 1 - If an A.P. have 4th term as 14 and 12th term as 70. What will be its first term? A - -10 B - -7 C - 7 D - 10 Let's have first term as a, common difference is d then a + 3d = 14 ... (i) a + 11d = 70 ... (ii) Subtracting (i) from (ii) => 8d = 56 => d = 7 Using (i) => a = 14 - 3d = -7 Q 2 - Which of the following is equal to 205x15? A - 205x10+15x5 B - 200x15+5x15 C - 200(1+5) D - 200+5x1x5 205x15= (200+5) x15 =200x15+5x15 Q 3 - If |x - 5| = 10 and |2y - 12| = 8, what is the minimum possible value of y/x? A - -2 B - -1 C - -3/5 D - 2/-5 y =10, 2. x =15,-5. So minimum value would be 10 / -5 = -2 Q 4 - If (28)3 is subtracted from the square of a number, the answer so obtained is 1457. What is the number? A - 127 B - 136 C - 142 D - 153 Let the number = x According to question, x2 - 283 = 1457 or, x = 153 Q 5 - How many numbers between 200 and 600 are exactly divisible by 4, 5 and 6? A - 5 B - 6 C - 7 D - 8 L.C.M. of 4, 5 and 6 (2 x 2) x (5) x (3 x 2) = 4 x 5 x 3 = 60 ∴ required numbers are 240, 300, 360, 420, 480, 540 which are 6. Q 6 - What is the sum of all even numbers between 100 and 200 including both? A - 3750 B - 6200 C - 6500 D - 7550 Required sum = 100 + 102 + ... + 200 which is an A.P. where a = 100, d = 2, l = 200. Using formula Tn = a + (n - 1)d Tn = 100 + (n-1)2 = 200 => 2n = 200 - 98 = 102 => n = 51 Now Using formula Sn = (n/2)(a + l) ∴ Required sum = (51/2)(100+200) = 51 x 150 = 7550 Q 7 - If first term of a G.P. is 5, common ratio is 2 what is the 8th term? A - 160 B - 256 C - 640 D - 1280 Here a = 5, r = 2, n = 8. Using formula Tn = arn- 1 Tn = 5 x 2(8-1) =5 x 27 =5 x 128 =640 Q 8 - 142 + 152 ... + 302 = ? A - 3836 B - 8336 C - 8366 D - 8636 Using formula (12 + 32 ... + n2) = [n(n+1)(2n+1)]/6 142 + 152 ... + 302 = (12 + 22 ... + 302) - (12 + 22 ... + 132) = (30 x 31 x 61)/ 6 - (13 x 14 x 27) / 6 = 9455 - 819 = 8636 Q 9 - If an A.P. have 4th term as 16 and 12th term as 80. What will be its first term? A - -10 B - -7 C - 7 D - 10 Let's have first term as a, common difference is d then a + 3d = 16 ... (i) a + 11d = 80 ... (ii) Subtracting (i) from (ii) => 8d = 64 => d = 8 Using (i) => a = 14 - 3d = -10 Q 10 - 142 + 152 ... + 502 = ? A - 6738396 B - 6738416 C - 6738400 D - 6738406 Using formula (12 + 32 ... + n2) = [n(n+1)(2n+1)]/6 142 + 152 ... + 502 = (12 + 22 ... + 502) - (12 + 22 ... + 132) = (50 x 51 x 101)/ 6 - (13 x 14 x 27) / 6 = 6739225 - 819 = 6738406 87 Lectures 22.5 hours Programming Line Print Add Notes Bookmark this page
[ { "code": null, "e": 4222, "s": 3892, "text": "Following quiz provides Multiple Choice Questions (MCQs) related to Basic Arithmetic. You will have to read all the given answers and click over the correct answer. If you are not sure about the answer then you can check the answer using Show Answer button. You can use Next Quiz button to check new set of questions in the quiz." }, { "code": null, "e": 4309, "s": 4222, "text": "Q 1 - If an A.P. have 4th term as 14 and 12th term as 70. What will be its first term?" }, { "code": null, "e": 4317, "s": 4309, "text": "A - -10" }, { "code": null, "e": 4324, "s": 4317, "text": "B - -7" }, { "code": null, "e": 4330, "s": 4324, "text": "C - 7" }, { "code": null, "e": 4337, "s": 4330, "text": "D - 10" }, { "code": null, "e": 4531, "s": 4337, "text": " \nLet's have first term as a, common difference is d then \na + 3d = 14 ... (i) \na + 11d = 70 ... (ii) \nSubtracting (i) from (ii) \n=> 8d = 56 => d = 7 \nUsing (i) \n=> a = 14 - 3d = -7 \n" }, { "code": null, "e": 4580, "s": 4531, "text": "Q 2 - Which of the following is equal to 205x15?" }, { "code": null, "e": 4596, "s": 4580, "text": "A - 205x10+15x5" }, { "code": null, "e": 4612, "s": 4596, "text": "B - 200x15+5x15" }, { "code": null, "e": 4625, "s": 4612, "text": "C - 200(1+5)" }, { "code": null, "e": 4639, "s": 4625, "text": "D - 200+5x1x5" }, { "code": null, "e": 4677, "s": 4639, "text": " \n205x15= (200+5) x15\n=200x15+5x15 " }, { "code": null, "e": 4761, "s": 4677, "text": "Q 3 - If |x - 5| = 10 and |2y - 12| = 8, what is the minimum possible value of y/x?" }, { "code": null, "e": 4768, "s": 4761, "text": "A - -2" }, { "code": null, "e": 4775, "s": 4768, "text": "B - -1" }, { "code": null, "e": 4784, "s": 4775, "text": "C - -3/5" }, { "code": null, "e": 4793, "s": 4784, "text": "D - 2/-5" }, { "code": null, "e": 4864, "s": 4793, "text": " \n y =10, 2. \n x =15,-5. \n So minimum value would be 10 / -5 = -2 " }, { "code": null, "e": 4974, "s": 4864, "text": "Q 4 - If (28)3 is subtracted from the square of a number, the answer so obtained is 1457. What is the number?" }, { "code": null, "e": 4982, "s": 4974, "text": "A - 127" }, { "code": null, "e": 4990, "s": 4982, "text": "B - 136" }, { "code": null, "e": 4998, "s": 4990, "text": "C - 142" }, { "code": null, "e": 5006, "s": 4998, "text": "D - 153" }, { "code": null, "e": 5086, "s": 5006, "text": " \n Let the number = x \n According to question, x2 - 283 = 1457 \n or, \n x = 153 " }, { "code": null, "e": 5166, "s": 5086, "text": "Q 5 - How many numbers between 200 and 600 are exactly divisible by 4, 5 and 6?" }, { "code": null, "e": 5172, "s": 5166, "text": "A - 5" }, { "code": null, "e": 5178, "s": 5172, "text": "B - 6" }, { "code": null, "e": 5184, "s": 5178, "text": "C - 7" }, { "code": null, "e": 5190, "s": 5184, "text": "D - 8" }, { "code": null, "e": 5323, "s": 5190, "text": " \n L.C.M. of 4, 5 and 6 (2 x 2) x (5) x (3 x 2) = 4 x 5 x 3 = 60 \n ∴ required numbers are 240, 300, 360, 420, 480, 540 which are 6. " }, { "code": null, "e": 5401, "s": 5323, "text": "Q 6 - What is the sum of all even numbers between 100 and 200 including both?" }, { "code": null, "e": 5410, "s": 5401, "text": "A - 3750" }, { "code": null, "e": 5419, "s": 5410, "text": "B - 6200" }, { "code": null, "e": 5428, "s": 5419, "text": "C - 6500" }, { "code": null, "e": 5437, "s": 5428, "text": "D - 7550" }, { "code": null, "e": 5723, "s": 5437, "text": " \n Required sum = 100 + 102 + ... + 200 which is an A.P. where a = 100, d = 2, l = 200. \n Using formula Tn = a + (n - 1)d \n Tn = 100 + (n-1)2 = 200 \n => 2n = 200 - 98 = 102 \n => n = 51 \n Now Using formula Sn = (n/2)(a + l) \n ∴ Required sum = (51/2)(100+200) = 51 x 150 = 7550 " }, { "code": null, "e": 5799, "s": 5723, "text": "Q 7 - If first term of a G.P. is 5, common ratio is 2 what is the 8th term?" }, { "code": null, "e": 5807, "s": 5799, "text": "A - 160" }, { "code": null, "e": 5815, "s": 5807, "text": "B - 256" }, { "code": null, "e": 5823, "s": 5815, "text": "C - 640" }, { "code": null, "e": 5832, "s": 5823, "text": "D - 1280" }, { "code": null, "e": 5939, "s": 5832, "text": " \n Here a = 5, r = 2, n = 8. \n Using formula Tn = arn- 1 \n Tn = 5 x 2(8-1) \n =5 x 27 \n =5 x 128 =640 " }, { "code": null, "e": 5969, "s": 5939, "text": "Q 8 - 142 + 152 ... + 302 = ?" }, { "code": null, "e": 5978, "s": 5969, "text": "A - 3836" }, { "code": null, "e": 5987, "s": 5978, "text": "B - 8336" }, { "code": null, "e": 5996, "s": 5987, "text": "C - 8366" }, { "code": null, "e": 6005, "s": 5996, "text": "D - 8636" }, { "code": null, "e": 6199, "s": 6005, "text": " \n Using formula (12 + 32 ... + n2) = [n(n+1)(2n+1)]/6 \n 142 + 152 ... + 302 = (12 + 22 ... + 302) - (12 + 22 ... + 132) \n = (30 x 31 x 61)/ 6 - (13 x 14 x 27) / 6 \n = 9455 - 819 = 8636 " }, { "code": null, "e": 6286, "s": 6199, "text": "Q 9 - If an A.P. have 4th term as 16 and 12th term as 80. What will be its first term?" }, { "code": null, "e": 6294, "s": 6286, "text": "A - -10" }, { "code": null, "e": 6301, "s": 6294, "text": "B - -7" }, { "code": null, "e": 6307, "s": 6301, "text": "C - 7" }, { "code": null, "e": 6314, "s": 6307, "text": "D - 10" }, { "code": null, "e": 6515, "s": 6314, "text": " \n Let's have first term as a, common difference is d then \n a + 3d = 16 ... (i) \n a + 11d = 80 ... (ii) \n Subtracting (i) from (ii) \n => 8d = 64 => d = 8 \n Using (i) \n => a = 14 - 3d = -10 " }, { "code": null, "e": 6546, "s": 6515, "text": "Q 10 - 142 + 152 ... + 502 = ?" }, { "code": null, "e": 6558, "s": 6546, "text": "A - 6738396" }, { "code": null, "e": 6570, "s": 6558, "text": "B - 6738416" }, { "code": null, "e": 6582, "s": 6570, "text": "C - 6738400" }, { "code": null, "e": 6594, "s": 6582, "text": "D - 6738406" }, { "code": null, "e": 6797, "s": 6594, "text": " \n Using formula (12 + 32 ... + n2) = [n(n+1)(2n+1)]/6 \n 142 + 152 ... + 502 = (12 + 22 ... + 502) - (12 + 22 ... + 132) \n = (50 x 51 x 101)/ 6 - (13 x 14 x 27) / 6 \n = 6739225 - 819 \n = 6738406 " }, { "code": null, "e": 6833, "s": 6797, "text": "\n 87 Lectures \n 22.5 hours \n" }, { "code": null, "e": 6851, "s": 6833, "text": " Programming Line" }, { "code": null, "e": 6858, "s": 6851, "text": " Print" }, { "code": null, "e": 6869, "s": 6858, "text": " Add Notes" } ]
Understanding the Effect of Bagging on Variance and Bias visually | by Dr. Robert Kübler | Towards Data Science
There exist a vast amount of great articles describing how Bagging methods like Random Forests work on an algorithmic level and why Bagging is a good thing to do. Usually, the essence is the following: β€œYou train a lot of Decision Trees on different parts of the training set and average their predictions into a final prediction. The prediction gets better, because the variance of the Random Forest is smaller compared to the variance of a single Decision Tree. (dartboard.png)” β€” some article Of course, I am paraphrasing here. The articles include great pictures, code, and many more thoughts. But what I often miss is a good intuition on why Bagging is a good idea and how to see the variance reduction in action, using a real dataset. Thus, in this article, I want to address both of these shortcomings and give intuitive reasoning why the Random Forest algorithm works and how you can see the improvement in the variance graphically. You can consider this article an exploration of these two topics that goes deeper than the average article about the Bias-Variance Dilemma while being not as deep as a fully-fledged research paper. Still, I will provide links to resources that I find useful, so you can go into greater depth whenever desired. I try to keep the math level quite understandable to allow people without a mathematics major to follow along, while also giving some high-level ideas and illustrations that also mathematically involved people can enjoy. Still, I will not explain how Decision Trees, Random Forests and all the other models mentioned work in detail since this has been covered numerous times already, as described. I will only explain the very high-level ideas, starting with Decision Trees. Disclaimer: I will only talk about vanilla Decision Trees here. We do not consider pruning in the rest of this article. The trees can grow arbitrarily deep. A Decision Tree with k leaves is a model of the form meaning that a Decision Tree is a piecewise constant function with a real value w in a region R of the feature space. Here x is from a feature space X and y is the corresponding label from an output space Y. The constraints on the R’s are that they are rectangles with boundaries parallel to the coordinate axes of the feature spacethe set of all rectangles is a partition of the feature space, i.e. if you take two rectangles do not intersect and the union of all rectangles is the complete feature space. they are rectangles with boundaries parallel to the coordinate axes of the feature space the set of all rectangles is a partition of the feature space, i.e. if you take two rectangles do not intersect and the union of all rectangles is the complete feature space. Now, that we have established that, let us examine why a Decision Tree is called a high-variance algorithm, while for example Linear Regression is considered low-variance. For a quick recap, linear regression models have the following form: where the weights w are real numbers and d is the dimension of the samples, i.e. the number of features. For comparing the variance of these models, we have to take one step back and think about what a learning problem actually is. Usually, we are given a fixed amount of samples (learning set, training samples), let our algorithm do some magic and fit all the necessary parameters and in the end, we can predict values for unseen samples. However, this is a quite rigid view of things. In Learning Theory, we model the training set as coming from a distribution D over the space XΓ—Y, where X is the feature space and Y is the output space. We sample a training set L (and also a validation and test set) of size n from the distribution: Imagine a distribution to be a black box with a button; if you hit the button once, you get a random sample (x1, y1) from the distribution. Hit it again and you get another sample (x2, y2), independent of the one(s) before. Repeat, until you have enough samples to work with. Then we can use the n data points from L to train our model. This outputs a function f with f(xi)β‰ˆyi for all (xi, yi) in the sample L (if our model is any good). This approach ensures that the performance of the model is okay on the training set. But now imagine that we query n new samples from the distribution D and use these as a training set L’. Let us call the model resulting from the training on this new set g. This new model g will also meet the condition g(xi’)β‰ˆyi’ for all (xi’, yi’) in L’. Now, since L’ consists of different points (xi’, yi’), the new model g will have a different output shape than f. The models f and g might or might not differ a lot, depending on how different L and L’ were, how the models were created and which randomness the algorithms used internally. If for a fixed algorithm (e.g. β€œDecision Tree”) the models for different training sets L and L’ tend to differ a lot, we call this algorithm a high-variance one. Of course, this is no precise definition, but this is also unnecessary for this article. In the following, we will use graphics to determine if an algorithm has a higher variance than another algorithm. If you are interested in the mathematics (cheers!), I can recommend the dissertation of Gilles Louppe [1], and the book of Shai Shalev-Shwartz and Shai Ben-David [2] which explains the theoretical foundations of machine learning in great detail. Let us get back to our comparison of Decision Trees and Linear Regression. We will use the following running example: X=[0, 10] and Y=R, i.e. the feature space is of dimension 1 and this one feature can take real values between 0 and 10, while the labels can take any real value. In our example, we define a distribution D doing the following: the feature x is chosen uniformly from 0 to 10 and the label y is computed explicitly via the hidden function The function h describes the underlying structure of the labels, it is the truth that we want to learn about the labels. We call it hidden since we will not give this information to the algorithms. They have to figure it out on their own. :) Following the reasoning above, if we query our distribution D three times for 10 samples each time we might end up with the following three training sets: Let us use the rightmost training set now and plot the results after applying Decision Trees and Linear Regression. Let us conduct the same experiment 3000 times for 3000 independently sampled training sets, each of size 10 again. On the left side, we see the results of the Decision Trees and on the right side, there are the Linear Regression results stacked on top of each other. Here we can see that the Decision Trees (left side) fit the data quite well on average. People also refer to this property as Decision Trees having a low bias. Meanwhile, for Linear Regression on the right side, the model clearly can not capture the complex pattern of the underlying label structure. We say that Linear Regression has high bias, in this case, it is not able to learn the truth. Yet, if you consider the vertical width of these black tubes, the ones stemming from the Decision Trees are wider than the Linear Regression ones on the right. This means that the Decision Tree predictions wiggle around more extremely than the Linear Regression predictions when re-sampling the training dataset, which we refer to as Decision Trees having a high variance and Linear Regression having a low variance. What we actually want are algorithms with a low bias (they hit the truth on average) and low variance (they do not wiggle around the truth too much). Luckily, there are numerous ways to lower the bias (e.g. with a technique called Boosting) and also other ways to lower the variance. The latter can be achieved with the so-called Bagging. The good thing about Bagging is, that it also does not increase the bias again, which we will motivate in the following section. That is why the effect of using Bagging together with Linear Regression is low: You can not decrease the bias via Bagging, but with Boosting. The funny thing is that it has proven useful to choose Decision Trees together with Boosting, too. In this case, heavily pruned Decision Trees, which also have a lower bias, are used. In this section, we will see what Bagging does, why it works and how to see the decrease of variance. Imagine we have access to the standard normal distribution, in particular, the mean of an observed value is 0 and the variance is 1. Let us assume that we love to see values around 0 (just as we love to see prediction functions around 3sin(x)+x). But the variance of 1 is too large for our taste (just like the width of the black tubes) and we search for a way to decrease it. An easy way to do it is to sample more values from the standard normal distribution and take the average of them. The following result is well-known and easy to verify: Thus, by averaging, we simulate drawing from another normal distribution with the same mean, but with a smaller variance, if ρ is not too big. This is great because we get values closer to zero with higher probability than before! In the special case of independent random variables (ρ=0) and b=100, the variance drops from 1 to 0.01, for example. The result is the following: Attention: If the random variables X are all correlated with value 1, this implies that ρ=(b-1)/b, i.e. the variance of the average will be 1 again. This corresponds to the case where each sample is, in fact, the same number. Averaging over a lot of the same numbers does not give us any new information, so this is as good as drawing only a single value. In the best case, we can average independent samples. The more correlated they are, the more useless they become in the averaging process. Now, the useful insight is that we can do the same with prediction models. Running a Decision Tree algorithm on a randomly drawn training dataset gives us a model, which is essentially sampling a function from a distribution. Averaging these models gives us another model (e.g. a Random Forest) with the same bias, but with lower variance. This ensemble model is closer to the truth than a single Decision Tree on average. But the question is: How badly are these functions correlated? Consider the following: If we come across a dataset, we can fit a single Decision Tree on it. So far, so good. But, if we do it again, the result will (nearly) be the same in the case of Decision Trees. This means that the functions that we sample this way are highly correlated (Οβ‰ˆ1) and do not improve upon a single Decision Tree. It is not necessarily exactly 1 since the Decision Tree algorithms occasionally have to break ties which can be done in a random manner, but since this is the only source of randomness it does not produce trees that are fundamentally different from each other. Somehow we have to decorrelate these trees, and we will see how to do this in the next section. Random Forests were invented by Leo Breiman [3]. The idea here is to fit numerous Decision Trees on the training set in a special way, giving an equally large number of tree models (=functions). Afterwards, these trees are combined into a single model, e.g. by averaging their outputs for any given input x, making it a special Bagging method. This results in a model with lower variance, similar to what we have seen before with normally distributed random variables. The idea behind getting many and not maximally correlated trees is the following: Use a random subset of the training samples for each tree.Use a random subset of features in each step of growing each tree. Use a random subset of the training samples for each tree. Use a random subset of features in each step of growing each tree. Having two sources of randomization helps to reduce the correlation between different trees even more than using only one of them. Feel free to add more, if you happen to design a new Bagging algorithm! There are various other methods to combine single Decision Trees, for example Extremely Randomized Trees by Geurts et al. [4]. Let us draw 10 samples from our distribution again and fit a Decision Tree and a Random Forest containing 100 Decision Trees. We repeat this procedure 1000 times and get the following picture: We see that the vertical width of the red tube, formed by the Random Forests is smaller than the Decision Trees’ black tube. So, Random Forests have a lower variance than Decision Trees, as expected. Furthermore, it seems that the averages (the middle) of the two tubes are the same which means that the process of averaging did not change the bias. We still hit the underlying true function 3sin(x)+x quite well. Note that the Random Forest algorithm could not show its full potential here since we have used a dataset with only one feature that every single Decision Tree has to use. So the 100 Decision Trees inside the Random Forest can only differ among the training samples that were chosen to grow each tree. In this case, the Random Forest algorithm collapses into an easier Bagging algorithm that only uses different training samples for each tree. If we want to widen the gap in variances while still being able to interpret the results visually, we have to move to a 2-dimensional feature space. This allows the Random Forest algorithm to choose exactly one of the two features available at random at each step within the algorithm. Let us define a distribution for the training data, which is similar to the distribution we used in the 1-dimensional case. We choose X=[0, 10]2 and Y=R, where D samples an (x, x’) uniformly from the square with the vertices in (0, 0), (0, 10), (10, 0) and (10, 10) and A random dataset comprising 50 points can look like this: Now, let us look at how the variance behaves for Decision Trees and Random Forests in this context. Enjoy the results! Let us first start with the case of Decision Trees. We use 9 different training datasets for growing 9 different trees. Looks familiar? ;) Now, let us do the same with Random Forests. Here, we train 100 Decision Trees per Random Forests again on a different subset of samples and using only one of the two given features at random! Each model is trained on 50 random sample points. It has become evident that high-variance algorithms change their outcome (the model) rapidly when the training set changes. This is bad since we can never know how far away our concrete model is from the truth, even if the bias of our model is zero. But we learned how to increase our chance of getting a good model using Bagging. We have also gotten an intuition on why Bagging lowers the variance while leaving the bias unchanged, and we have seen these results in a lot of illustrations. [1] G. Louppe, Understanding Random Forests β€” From Theory to Practice (2014), Dissertation [2] S. Shalev-Shwartz and S. Ben-David, Understanding Machine Learning: From Theory to Algorithm (2014), Cambridge University Press [3] L. Breiman, Random Forests (2001), Machine learning 45.1 (2001): 5–32 [4] P. Geurts, D. Ernst and L. Wehenkel, Extremely Randomized Trees (2005), Machine learning 63.1 (2006): 3–42 I created all formulas using LaTeX. For the other graphics, I used the Python library matplotlib together with numpy. For the model training, I used the scikit-learn. My thanks go to Dr. Patrick Bormann for proofreading and for giving a lot of helpful advice on improving my article. Also thanks to Andre Esser for his help! Please think of me when you are starting to generate money with this Decision Tree mosaic art. :) import matplotlib.pyplot as pltfrom sklearn.tree import DecisionTreeRegressorimport numpy as np# Sample from the distribution with a true function f.def generate_data_2d(f, n_samples): x1 = np.random.uniform(0, 10, n_samples) x2 = np.random.uniform(0, 10, n_samples) y = f(x1, x2) + np.random.randn(n_samples) return np.vstack([x1, x2]).transpose(), y# Parameters to play round with.f = lambda x1, x2: 3 * np.sin(x1 + x2) + x1 - x2n_samples = 50n_rows = 3n_cols = 3# Increase numbers to remove white spaces in the pictures.n_points = 100size_points = 6# Prepare the plotting.fig = plt.figure(constrained_layout=True, figsize=(12, 12))all_points = np.array([(x1, x2) for x1 in np.linspace(0, 10, n_points) for x2 in np.linspace(0, 10, n_points)])# Start plotting.for i in range(1, n_rows * n_cols + 1): # Get a random training set. x, y = generate_data_2d(f, n_samples)# Train a Decision Tree. dt = DecisionTreeRegressor() dt.fit(x, y) predictions = dt.predict(all_points)# Create one mosaic picture. ax = fig.add_subplot(n_rows, n_cols, i) ax.axis('off') ax.scatter(all_points[:, 0], all_points[:, 1], c=predictions, s=size_points) I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 374, "s": 172, "text": "There exist a vast amount of great articles describing how Bagging methods like Random Forests work on an algorithmic level and why Bagging is a good thing to do. Usually, the essence is the following:" }, { "code": null, "e": 653, "s": 374, "text": "β€œYou train a lot of Decision Trees on different parts of the training set and average their predictions into a final prediction. The prediction gets better, because the variance of the Random Forest is smaller compared to the variance of a single Decision Tree. (dartboard.png)”" }, { "code": null, "e": 668, "s": 653, "text": "β€” some article" }, { "code": null, "e": 913, "s": 668, "text": "Of course, I am paraphrasing here. The articles include great pictures, code, and many more thoughts. But what I often miss is a good intuition on why Bagging is a good idea and how to see the variance reduction in action, using a real dataset." }, { "code": null, "e": 1423, "s": 913, "text": "Thus, in this article, I want to address both of these shortcomings and give intuitive reasoning why the Random Forest algorithm works and how you can see the improvement in the variance graphically. You can consider this article an exploration of these two topics that goes deeper than the average article about the Bias-Variance Dilemma while being not as deep as a fully-fledged research paper. Still, I will provide links to resources that I find useful, so you can go into greater depth whenever desired." }, { "code": null, "e": 1644, "s": 1423, "text": "I try to keep the math level quite understandable to allow people without a mathematics major to follow along, while also giving some high-level ideas and illustrations that also mathematically involved people can enjoy." }, { "code": null, "e": 1898, "s": 1644, "text": "Still, I will not explain how Decision Trees, Random Forests and all the other models mentioned work in detail since this has been covered numerous times already, as described. I will only explain the very high-level ideas, starting with Decision Trees." }, { "code": null, "e": 2055, "s": 1898, "text": "Disclaimer: I will only talk about vanilla Decision Trees here. We do not consider pruning in the rest of this article. The trees can grow arbitrarily deep." }, { "code": null, "e": 2108, "s": 2055, "text": "A Decision Tree with k leaves is a model of the form" }, { "code": null, "e": 2352, "s": 2108, "text": "meaning that a Decision Tree is a piecewise constant function with a real value w in a region R of the feature space. Here x is from a feature space X and y is the corresponding label from an output space Y. The constraints on the R’s are that" }, { "code": null, "e": 2615, "s": 2352, "text": "they are rectangles with boundaries parallel to the coordinate axes of the feature spacethe set of all rectangles is a partition of the feature space, i.e. if you take two rectangles do not intersect and the union of all rectangles is the complete feature space." }, { "code": null, "e": 2704, "s": 2615, "text": "they are rectangles with boundaries parallel to the coordinate axes of the feature space" }, { "code": null, "e": 2879, "s": 2704, "text": "the set of all rectangles is a partition of the feature space, i.e. if you take two rectangles do not intersect and the union of all rectangles is the complete feature space." }, { "code": null, "e": 3051, "s": 2879, "text": "Now, that we have established that, let us examine why a Decision Tree is called a high-variance algorithm, while for example Linear Regression is considered low-variance." }, { "code": null, "e": 3120, "s": 3051, "text": "For a quick recap, linear regression models have the following form:" }, { "code": null, "e": 3225, "s": 3120, "text": "where the weights w are real numbers and d is the dimension of the samples, i.e. the number of features." }, { "code": null, "e": 3352, "s": 3225, "text": "For comparing the variance of these models, we have to take one step back and think about what a learning problem actually is." }, { "code": null, "e": 3608, "s": 3352, "text": "Usually, we are given a fixed amount of samples (learning set, training samples), let our algorithm do some magic and fit all the necessary parameters and in the end, we can predict values for unseen samples. However, this is a quite rigid view of things." }, { "code": null, "e": 3859, "s": 3608, "text": "In Learning Theory, we model the training set as coming from a distribution D over the space XΓ—Y, where X is the feature space and Y is the output space. We sample a training set L (and also a validation and test set) of size n from the distribution:" }, { "code": null, "e": 4135, "s": 3859, "text": "Imagine a distribution to be a black box with a button; if you hit the button once, you get a random sample (x1, y1) from the distribution. Hit it again and you get another sample (x2, y2), independent of the one(s) before. Repeat, until you have enough samples to work with." }, { "code": null, "e": 4382, "s": 4135, "text": "Then we can use the n data points from L to train our model. This outputs a function f with f(xi)β‰ˆyi for all (xi, yi) in the sample L (if our model is any good). This approach ensures that the performance of the model is okay on the training set." }, { "code": null, "e": 4638, "s": 4382, "text": "But now imagine that we query n new samples from the distribution D and use these as a training set L’. Let us call the model resulting from the training on this new set g. This new model g will also meet the condition g(xi’)β‰ˆyi’ for all (xi’, yi’) in L’." }, { "code": null, "e": 4927, "s": 4638, "text": "Now, since L’ consists of different points (xi’, yi’), the new model g will have a different output shape than f. The models f and g might or might not differ a lot, depending on how different L and L’ were, how the models were created and which randomness the algorithms used internally." }, { "code": null, "e": 5089, "s": 4927, "text": "If for a fixed algorithm (e.g. β€œDecision Tree”) the models for different training sets L and L’ tend to differ a lot, we call this algorithm a high-variance one." }, { "code": null, "e": 5292, "s": 5089, "text": "Of course, this is no precise definition, but this is also unnecessary for this article. In the following, we will use graphics to determine if an algorithm has a higher variance than another algorithm." }, { "code": null, "e": 5538, "s": 5292, "text": "If you are interested in the mathematics (cheers!), I can recommend the dissertation of Gilles Louppe [1], and the book of Shai Shalev-Shwartz and Shai Ben-David [2] which explains the theoretical foundations of machine learning in great detail." }, { "code": null, "e": 5818, "s": 5538, "text": "Let us get back to our comparison of Decision Trees and Linear Regression. We will use the following running example: X=[0, 10] and Y=R, i.e. the feature space is of dimension 1 and this one feature can take real values between 0 and 10, while the labels can take any real value." }, { "code": null, "e": 5992, "s": 5818, "text": "In our example, we define a distribution D doing the following: the feature x is chosen uniformly from 0 to 10 and the label y is computed explicitly via the hidden function" }, { "code": null, "e": 6234, "s": 5992, "text": "The function h describes the underlying structure of the labels, it is the truth that we want to learn about the labels. We call it hidden since we will not give this information to the algorithms. They have to figure it out on their own. :)" }, { "code": null, "e": 6389, "s": 6234, "text": "Following the reasoning above, if we query our distribution D three times for 10 samples each time we might end up with the following three training sets:" }, { "code": null, "e": 6505, "s": 6389, "text": "Let us use the rightmost training set now and plot the results after applying Decision Trees and Linear Regression." }, { "code": null, "e": 6772, "s": 6505, "text": "Let us conduct the same experiment 3000 times for 3000 independently sampled training sets, each of size 10 again. On the left side, we see the results of the Decision Trees and on the right side, there are the Linear Regression results stacked on top of each other." }, { "code": null, "e": 7167, "s": 6772, "text": "Here we can see that the Decision Trees (left side) fit the data quite well on average. People also refer to this property as Decision Trees having a low bias. Meanwhile, for Linear Regression on the right side, the model clearly can not capture the complex pattern of the underlying label structure. We say that Linear Regression has high bias, in this case, it is not able to learn the truth." }, { "code": null, "e": 7584, "s": 7167, "text": "Yet, if you consider the vertical width of these black tubes, the ones stemming from the Decision Trees are wider than the Linear Regression ones on the right. This means that the Decision Tree predictions wiggle around more extremely than the Linear Regression predictions when re-sampling the training dataset, which we refer to as Decision Trees having a high variance and Linear Regression having a low variance." }, { "code": null, "e": 8052, "s": 7584, "text": "What we actually want are algorithms with a low bias (they hit the truth on average) and low variance (they do not wiggle around the truth too much). Luckily, there are numerous ways to lower the bias (e.g. with a technique called Boosting) and also other ways to lower the variance. The latter can be achieved with the so-called Bagging. The good thing about Bagging is, that it also does not increase the bias again, which we will motivate in the following section." }, { "code": null, "e": 8378, "s": 8052, "text": "That is why the effect of using Bagging together with Linear Regression is low: You can not decrease the bias via Bagging, but with Boosting. The funny thing is that it has proven useful to choose Decision Trees together with Boosting, too. In this case, heavily pruned Decision Trees, which also have a lower bias, are used." }, { "code": null, "e": 8480, "s": 8378, "text": "In this section, we will see what Bagging does, why it works and how to see the decrease of variance." }, { "code": null, "e": 9026, "s": 8480, "text": "Imagine we have access to the standard normal distribution, in particular, the mean of an observed value is 0 and the variance is 1. Let us assume that we love to see values around 0 (just as we love to see prediction functions around 3sin(x)+x). But the variance of 1 is too large for our taste (just like the width of the black tubes) and we search for a way to decrease it. An easy way to do it is to sample more values from the standard normal distribution and take the average of them. The following result is well-known and easy to verify:" }, { "code": null, "e": 9257, "s": 9026, "text": "Thus, by averaging, we simulate drawing from another normal distribution with the same mean, but with a smaller variance, if ρ is not too big. This is great because we get values closer to zero with higher probability than before!" }, { "code": null, "e": 9403, "s": 9257, "text": "In the special case of independent random variables (ρ=0) and b=100, the variance drops from 1 to 0.01, for example. The result is the following:" }, { "code": null, "e": 9759, "s": 9403, "text": "Attention: If the random variables X are all correlated with value 1, this implies that ρ=(b-1)/b, i.e. the variance of the average will be 1 again. This corresponds to the case where each sample is, in fact, the same number. Averaging over a lot of the same numbers does not give us any new information, so this is as good as drawing only a single value." }, { "code": null, "e": 9898, "s": 9759, "text": "In the best case, we can average independent samples. The more correlated they are, the more useless they become in the averaging process." }, { "code": null, "e": 10321, "s": 9898, "text": "Now, the useful insight is that we can do the same with prediction models. Running a Decision Tree algorithm on a randomly drawn training dataset gives us a model, which is essentially sampling a function from a distribution. Averaging these models gives us another model (e.g. a Random Forest) with the same bias, but with lower variance. This ensemble model is closer to the truth than a single Decision Tree on average." }, { "code": null, "e": 10717, "s": 10321, "text": "But the question is: How badly are these functions correlated? Consider the following: If we come across a dataset, we can fit a single Decision Tree on it. So far, so good. But, if we do it again, the result will (nearly) be the same in the case of Decision Trees. This means that the functions that we sample this way are highly correlated (Οβ‰ˆ1) and do not improve upon a single Decision Tree." }, { "code": null, "e": 10978, "s": 10717, "text": "It is not necessarily exactly 1 since the Decision Tree algorithms occasionally have to break ties which can be done in a random manner, but since this is the only source of randomness it does not produce trees that are fundamentally different from each other." }, { "code": null, "e": 11074, "s": 10978, "text": "Somehow we have to decorrelate these trees, and we will see how to do this in the next section." }, { "code": null, "e": 11543, "s": 11074, "text": "Random Forests were invented by Leo Breiman [3]. The idea here is to fit numerous Decision Trees on the training set in a special way, giving an equally large number of tree models (=functions). Afterwards, these trees are combined into a single model, e.g. by averaging their outputs for any given input x, making it a special Bagging method. This results in a model with lower variance, similar to what we have seen before with normally distributed random variables." }, { "code": null, "e": 11625, "s": 11543, "text": "The idea behind getting many and not maximally correlated trees is the following:" }, { "code": null, "e": 11750, "s": 11625, "text": "Use a random subset of the training samples for each tree.Use a random subset of features in each step of growing each tree." }, { "code": null, "e": 11809, "s": 11750, "text": "Use a random subset of the training samples for each tree." }, { "code": null, "e": 11876, "s": 11809, "text": "Use a random subset of features in each step of growing each tree." }, { "code": null, "e": 12206, "s": 11876, "text": "Having two sources of randomization helps to reduce the correlation between different trees even more than using only one of them. Feel free to add more, if you happen to design a new Bagging algorithm! There are various other methods to combine single Decision Trees, for example Extremely Randomized Trees by Geurts et al. [4]." }, { "code": null, "e": 12399, "s": 12206, "text": "Let us draw 10 samples from our distribution again and fit a Decision Tree and a Random Forest containing 100 Decision Trees. We repeat this procedure 1000 times and get the following picture:" }, { "code": null, "e": 12813, "s": 12399, "text": "We see that the vertical width of the red tube, formed by the Random Forests is smaller than the Decision Trees’ black tube. So, Random Forests have a lower variance than Decision Trees, as expected. Furthermore, it seems that the averages (the middle) of the two tubes are the same which means that the process of averaging did not change the bias. We still hit the underlying true function 3sin(x)+x quite well." }, { "code": null, "e": 13257, "s": 12813, "text": "Note that the Random Forest algorithm could not show its full potential here since we have used a dataset with only one feature that every single Decision Tree has to use. So the 100 Decision Trees inside the Random Forest can only differ among the training samples that were chosen to grow each tree. In this case, the Random Forest algorithm collapses into an easier Bagging algorithm that only uses different training samples for each tree." }, { "code": null, "e": 13543, "s": 13257, "text": "If we want to widen the gap in variances while still being able to interpret the results visually, we have to move to a 2-dimensional feature space. This allows the Random Forest algorithm to choose exactly one of the two features available at random at each step within the algorithm." }, { "code": null, "e": 13813, "s": 13543, "text": "Let us define a distribution for the training data, which is similar to the distribution we used in the 1-dimensional case. We choose X=[0, 10]2 and Y=R, where D samples an (x, x’) uniformly from the square with the vertices in (0, 0), (0, 10), (10, 0) and (10, 10) and" }, { "code": null, "e": 13871, "s": 13813, "text": "A random dataset comprising 50 points can look like this:" }, { "code": null, "e": 13990, "s": 13871, "text": "Now, let us look at how the variance behaves for Decision Trees and Random Forests in this context. Enjoy the results!" }, { "code": null, "e": 14110, "s": 13990, "text": "Let us first start with the case of Decision Trees. We use 9 different training datasets for growing 9 different trees." }, { "code": null, "e": 14129, "s": 14110, "text": "Looks familiar? ;)" }, { "code": null, "e": 14372, "s": 14129, "text": "Now, let us do the same with Random Forests. Here, we train 100 Decision Trees per Random Forests again on a different subset of samples and using only one of the two given features at random! Each model is trained on 50 random sample points." }, { "code": null, "e": 14622, "s": 14372, "text": "It has become evident that high-variance algorithms change their outcome (the model) rapidly when the training set changes. This is bad since we can never know how far away our concrete model is from the truth, even if the bias of our model is zero." }, { "code": null, "e": 14863, "s": 14622, "text": "But we learned how to increase our chance of getting a good model using Bagging. We have also gotten an intuition on why Bagging lowers the variance while leaving the bias unchanged, and we have seen these results in a lot of illustrations." }, { "code": null, "e": 14954, "s": 14863, "text": "[1] G. Louppe, Understanding Random Forests β€” From Theory to Practice (2014), Dissertation" }, { "code": null, "e": 15086, "s": 14954, "text": "[2] S. Shalev-Shwartz and S. Ben-David, Understanding Machine Learning: From Theory to Algorithm (2014), Cambridge University Press" }, { "code": null, "e": 15160, "s": 15086, "text": "[3] L. Breiman, Random Forests (2001), Machine learning 45.1 (2001): 5–32" }, { "code": null, "e": 15271, "s": 15160, "text": "[4] P. Geurts, D. Ernst and L. Wehenkel, Extremely Randomized Trees (2005), Machine learning 63.1 (2006): 3–42" }, { "code": null, "e": 15438, "s": 15271, "text": "I created all formulas using LaTeX. For the other graphics, I used the Python library matplotlib together with numpy. For the model training, I used the scikit-learn." }, { "code": null, "e": 15596, "s": 15438, "text": "My thanks go to Dr. Patrick Bormann for proofreading and for giving a lot of helpful advice on improving my article. Also thanks to Andre Esser for his help!" }, { "code": null, "e": 15694, "s": 15596, "text": "Please think of me when you are starting to generate money with this Decision Tree mosaic art. :)" }, { "code": null, "e": 16862, "s": 15694, "text": "import matplotlib.pyplot as pltfrom sklearn.tree import DecisionTreeRegressorimport numpy as np# Sample from the distribution with a true function f.def generate_data_2d(f, n_samples): x1 = np.random.uniform(0, 10, n_samples) x2 = np.random.uniform(0, 10, n_samples) y = f(x1, x2) + np.random.randn(n_samples) return np.vstack([x1, x2]).transpose(), y# Parameters to play round with.f = lambda x1, x2: 3 * np.sin(x1 + x2) + x1 - x2n_samples = 50n_rows = 3n_cols = 3# Increase numbers to remove white spaces in the pictures.n_points = 100size_points = 6# Prepare the plotting.fig = plt.figure(constrained_layout=True, figsize=(12, 12))all_points = np.array([(x1, x2) for x1 in np.linspace(0, 10, n_points) for x2 in np.linspace(0, 10, n_points)])# Start plotting.for i in range(1, n_rows * n_cols + 1): # Get a random training set. x, y = generate_data_2d(f, n_samples)# Train a Decision Tree. dt = DecisionTreeRegressor() dt.fit(x, y) predictions = dt.predict(all_points)# Create one mosaic picture. ax = fig.add_subplot(n_rows, n_cols, i) ax.axis('off') ax.scatter(all_points[:, 0], all_points[:, 1], c=predictions, s=size_points)" }, { "code": null, "e": 16952, "s": 16862, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 16978, "s": 16952, "text": "As the last point, if you" }, { "code": null, "e": 17081, "s": 16978, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 17143, "s": 17081, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 17185, "s": 17143, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 17242, "s": 17185, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 17355, "s": 17242, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 17400, "s": 17355, "text": "Thanks a lot, if you consider supporting me!" } ]
Cocktail Sort - GeeksforGeeks
03 Mar, 2022 Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively. Algorithm: Each iteration of the algorithm is broken up into 2 stages: The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required. The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array. The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required. Example : Let us consider an example array (5 1 4 2 8 0 2) First Forward Pass: (5 1 4 2 8 0 2) ? (1 5 4 2 8 0 2), Swap since 5 > 1 (1 5 4 2 8 0 2) ? (1 4 5 2 8 0 2), Swap since 5 > 4 (1 4 5 2 8 0 2) ? (1 4 2 5 8 0 2), Swap since 5 > 2 (1 4 2 5 8 0 2) ? (1 4 2 5 8 0 2) (1 4 2 5 8 0 2) ? (1 4 2 5 0 8 2), Swap since 8 > 0 (1 4 2 5 0 8 2) ? (1 4 2 5 0 2 8), Swap since 8 > 2After first forward pass, greatest element of the array will be present at the last index of array.First Backward Pass: (1 4 2 5 0 2 8) ? (1 4 2 5 0 2 8) (1 4 2 5 0 2 8) ? (1 4 2 0 5 2 8), Swap since 5 > 0 (1 4 2 0 5 2 8) ? (1 4 0 2 5 2 8), Swap since 2 > 0 (1 4 0 2 5 2 8) ? (1 0 4 2 5 2 8), Swap since 4 > 0 (1 0 4 2 5 2 8) ? (0 1 4 2 5 2 8), Swap since 1 > 0After first backward pass, smallest element of the array will be present at the first index of the array.Second Forward Pass: (0 1 4 2 5 2 8) ? (0 1 4 2 5 2 8) (0 1 4 2 5 2 8) ? (0 1 2 4 5 2 8), Swap since 4 > 2 (0 1 2 4 5 2 8) ? (0 1 2 4 5 2 8) (0 1 2 4 5 2 8) ? (0 1 2 4 2 5 8), Swap since 5 > 2Second Backward Pass: (0 1 2 4 2 5 8) ? (0 1 2 2 4 5 8), Swap since 4 > 2Now, the array is already sorted, but our algorithm doesn’t know if it is completed. The algorithm needs to complete this whole pass without any swap to know it is sorted. (0 1 2 2 4 5 8) ? (0 1 2 2 4 5 8) (0 1 2 2 4 5 8) ? (0 1 2 2 4 5 8)Below is the implementation of the above algorithm : C++ Java Python C# Javascript // C++ implementation of Cocktail Sort#include <bits/stdc++.h>using namespace std; // Sorts array a[0..n-1] using Cocktail sortvoid CocktailSort(int a[], int n){ bool swapped = true; int start = 0; int end = n - 1; while (swapped) { // reset the swapped flag on entering // the loop, because it might be true from // a previous iteration. swapped = false; // loop from left to right same as // the bubble sort for (int i = start; i < end; ++i) { if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); swapped = true; } } // if nothing moved, then array is sorted. if (!swapped) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot --end; // from right to left, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; --i) { if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. ++start; }} /* Prints the array */void printArray(int a[], int n){ for (int i = 0; i < n; i++) printf("%d ", a[i]); printf("\n");} // Driver codeint main(){ int a[] = { 5, 1, 4, 2, 8, 0, 2 }; int n = sizeof(a) / sizeof(a[0]); CocktailSort(a, n); printf("Sorted array :\n"); printArray(a, n); return 0;} // Java program for implementation of Cocktail Sortpublic class CocktailSort{ void cocktailSort(int a[]) { boolean swapped = true; int start = 0; int end = a.length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (int i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ void printArray(int a[]) { int n = a.length; for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); } // Driver code public static void main(String[] args) { CocktailSort ob = new CocktailSort(); int a[] = { 5, 1, 4, 2, 8, 0, 2 }; ob.cocktailSort(a); System.out.println("Sorted array"); ob.printArray(a); }} # Python program for implementation of Cocktail Sort def cocktailSort(a): n = len(a) swapped = True start = 0 end = n-1 while (swapped == True): # reset the swapped flag on entering the loop, # because it might be true from a previous # iteration. swapped = False # loop from left to right same as the bubble # sort for i in range(start, end): if (a[i] > a[i + 1]): a[i], a[i + 1] = a[i + 1], a[i] swapped = True # if nothing moved, then array is sorted. if (swapped == False): break # otherwise, reset the swapped flag so that it # can be used in the next stage swapped = False # move the end point back by one, because # item at the end is in its rightful spot end = end-1 # from right to left, doing the same # comparison as in the previous stage for i in range(end-1, start-1, -1): if (a[i] > a[i + 1]): a[i], a[i + 1] = a[i + 1], a[i] swapped = True # increase the starting point, because # the last stage would have moved the next # smallest number to its rightful spot. start = start + 1 # Driver codea = [5, 1, 4, 2, 8, 0, 2]cocktailSort(a)print("Sorted array is:")for i in range(len(a)): print("% d" % a[i]) // C# program for implementation of Cocktail Sortusing System; class GFG { static void cocktailSort(int[] a) { bool swapped = true; int start = 0; int end = a.Length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (int i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ static void printArray(int[] a) { int n = a.Length; for (int i = 0; i < n; i++) Console.Write(a[i] + " "); Console.WriteLine(); } // Driver code public static void Main() { int[] a = { 5, 1, 4, 2, 8, 0, 2 }; cocktailSort(a); Console.WriteLine("Sorted array "); printArray(a); }} // This code is contributed by Sam007 <script> // Javascript program for implementation of Cocktail Sort function cocktailSort(a) { let swapped = true; let start = 0; let end = a.length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (let i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { let temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (let i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { let temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ function printArray(a) { let n = a.length; for (let i = 0; i < n; i++) document.write(a[i] + " "); document.write("</br>"); } let a = [ 5, 1, 4, 2, 8, 0, 2 ]; cocktailSort(a); document.write("Sorted array :" + "</br>"); printArray(a); // This code is contributed by decode2207.</script> Sorted array : 0 1 2 2 4 5 8 Worst and Average Case Time Complexity: O(n*n). Best Case Time Complexity: O(n). Best case occurs when array is already sorted.Auxiliary Space: O(1)Sorting In Place: YesStable: YesComparison with Bubble Sort: Time complexities are same, but Cocktail performs better than Bubble Sort. Typically cocktail sort is less than two times faster than bubble sort. Consider the example (2, 3, 4, 5, 1). Bubble sort requires four traversals of array for this example, while Cocktail sort requires only two traversals. (Source Wiki)References: https://en.wikipedia.org/wiki/Cocktail_shaker_sort http://will.thimbleby.net/algorithms/doku.php?id=cocktail_sort http://www.programming-algorithms.net/article/40270/Shaker-sort This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 decode2207 simmytarika5 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexities of all Sorting Algorithms Radix Sort Merge two sorted arrays Sort an array of 0s, 1s and 2s Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second) k largest(or smallest) elements in an array sort() in Python Count Inversions in an array | Set 1 (Using Merge Sort) Python List sort() method Python Program for QuickSort
[ { "code": null, "e": 23854, "s": 23826, "text": "\n03 Mar, 2022" }, { "code": null, "e": 24236, "s": 23854, "text": "Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively. Algorithm: Each iteration of the algorithm is broken up into 2 stages: " }, { "code": null, "e": 24781, "s": 24236, "text": "The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required." }, { "code": null, "e": 25086, "s": 24781, "text": "The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array." }, { "code": null, "e": 25327, "s": 25086, "text": "The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required." }, { "code": null, "e": 25338, "s": 25327, "text": "Example : " }, { "code": null, "e": 25387, "s": 25338, "text": "Let us consider an example array (5 1 4 2 8 0 2)" }, { "code": null, "e": 26723, "s": 25387, "text": "First Forward Pass: (5 1 4 2 8 0 2) ? (1 5 4 2 8 0 2), Swap since 5 > 1 (1 5 4 2 8 0 2) ? (1 4 5 2 8 0 2), Swap since 5 > 4 (1 4 5 2 8 0 2) ? (1 4 2 5 8 0 2), Swap since 5 > 2 (1 4 2 5 8 0 2) ? (1 4 2 5 8 0 2) (1 4 2 5 8 0 2) ? (1 4 2 5 0 8 2), Swap since 8 > 0 (1 4 2 5 0 8 2) ? (1 4 2 5 0 2 8), Swap since 8 > 2After first forward pass, greatest element of the array will be present at the last index of array.First Backward Pass: (1 4 2 5 0 2 8) ? (1 4 2 5 0 2 8) (1 4 2 5 0 2 8) ? (1 4 2 0 5 2 8), Swap since 5 > 0 (1 4 2 0 5 2 8) ? (1 4 0 2 5 2 8), Swap since 2 > 0 (1 4 0 2 5 2 8) ? (1 0 4 2 5 2 8), Swap since 4 > 0 (1 0 4 2 5 2 8) ? (0 1 4 2 5 2 8), Swap since 1 > 0After first backward pass, smallest element of the array will be present at the first index of the array.Second Forward Pass: (0 1 4 2 5 2 8) ? (0 1 4 2 5 2 8) (0 1 4 2 5 2 8) ? (0 1 2 4 5 2 8), Swap since 4 > 2 (0 1 2 4 5 2 8) ? (0 1 2 4 5 2 8) (0 1 2 4 5 2 8) ? (0 1 2 4 2 5 8), Swap since 5 > 2Second Backward Pass: (0 1 2 4 2 5 8) ? (0 1 2 2 4 5 8), Swap since 4 > 2Now, the array is already sorted, but our algorithm doesn’t know if it is completed. The algorithm needs to complete this whole pass without any swap to know it is sorted. (0 1 2 2 4 5 8) ? (0 1 2 2 4 5 8) (0 1 2 2 4 5 8) ? (0 1 2 2 4 5 8)Below is the implementation of the above algorithm :" }, { "code": null, "e": 26727, "s": 26723, "text": "C++" }, { "code": null, "e": 26732, "s": 26727, "text": "Java" }, { "code": null, "e": 26739, "s": 26732, "text": "Python" }, { "code": null, "e": 26742, "s": 26739, "text": "C#" }, { "code": null, "e": 26753, "s": 26742, "text": "Javascript" }, { "code": "// C++ implementation of Cocktail Sort#include <bits/stdc++.h>using namespace std; // Sorts array a[0..n-1] using Cocktail sortvoid CocktailSort(int a[], int n){ bool swapped = true; int start = 0; int end = n - 1; while (swapped) { // reset the swapped flag on entering // the loop, because it might be true from // a previous iteration. swapped = false; // loop from left to right same as // the bubble sort for (int i = start; i < end; ++i) { if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); swapped = true; } } // if nothing moved, then array is sorted. if (!swapped) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot --end; // from right to left, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; --i) { if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. ++start; }} /* Prints the array */void printArray(int a[], int n){ for (int i = 0; i < n; i++) printf(\"%d \", a[i]); printf(\"\\n\");} // Driver codeint main(){ int a[] = { 5, 1, 4, 2, 8, 0, 2 }; int n = sizeof(a) / sizeof(a[0]); CocktailSort(a, n); printf(\"Sorted array :\\n\"); printArray(a, n); return 0;}", "e": 28483, "s": 26753, "text": null }, { "code": "// Java program for implementation of Cocktail Sortpublic class CocktailSort{ void cocktailSort(int a[]) { boolean swapped = true; int start = 0; int end = a.length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (int i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ void printArray(int a[]) { int n = a.length; for (int i = 0; i < n; i++) System.out.print(a[i] + \" \"); System.out.println(); } // Driver code public static void main(String[] args) { CocktailSort ob = new CocktailSort(); int a[] = { 5, 1, 4, 2, 8, 0, 2 }; ob.cocktailSort(a); System.out.println(\"Sorted array\"); ob.printArray(a); }}", "e": 30652, "s": 28483, "text": null }, { "code": "# Python program for implementation of Cocktail Sort def cocktailSort(a): n = len(a) swapped = True start = 0 end = n-1 while (swapped == True): # reset the swapped flag on entering the loop, # because it might be true from a previous # iteration. swapped = False # loop from left to right same as the bubble # sort for i in range(start, end): if (a[i] > a[i + 1]): a[i], a[i + 1] = a[i + 1], a[i] swapped = True # if nothing moved, then array is sorted. if (swapped == False): break # otherwise, reset the swapped flag so that it # can be used in the next stage swapped = False # move the end point back by one, because # item at the end is in its rightful spot end = end-1 # from right to left, doing the same # comparison as in the previous stage for i in range(end-1, start-1, -1): if (a[i] > a[i + 1]): a[i], a[i + 1] = a[i + 1], a[i] swapped = True # increase the starting point, because # the last stage would have moved the next # smallest number to its rightful spot. start = start + 1 # Driver codea = [5, 1, 4, 2, 8, 0, 2]cocktailSort(a)print(\"Sorted array is:\")for i in range(len(a)): print(\"% d\" % a[i])", "e": 32043, "s": 30652, "text": null }, { "code": "// C# program for implementation of Cocktail Sortusing System; class GFG { static void cocktailSort(int[] a) { bool swapped = true; int start = 0; int end = a.Length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (int i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ static void printArray(int[] a) { int n = a.Length; for (int i = 0; i < n; i++) Console.Write(a[i] + \" \"); Console.WriteLine(); } // Driver code public static void Main() { int[] a = { 5, 1, 4, 2, 8, 0, 2 }; cocktailSort(a); Console.WriteLine(\"Sorted array \"); printArray(a); }} // This code is contributed by Sam007", "e": 34148, "s": 32043, "text": null }, { "code": "<script> // Javascript program for implementation of Cocktail Sort function cocktailSort(a) { let swapped = true; let start = 0; let end = a.length; while (swapped == true) { // reset the swapped flag on entering the // loop, because it might be true from a // previous iteration. swapped = false; // loop from bottom to top same as // the bubble sort for (let i = start; i < end - 1; ++i) { if (a[i] > a[i + 1]) { let temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // if nothing moved, then array is sorted. if (swapped == false) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot end = end - 1; // from top to bottom, doing the // same comparison as in the previous stage for (let i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { let temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. start = start + 1; } } /* Prints the array */ function printArray(a) { let n = a.length; for (let i = 0; i < n; i++) document.write(a[i] + \" \"); document.write(\"</br>\"); } let a = [ 5, 1, 4, 2, 8, 0, 2 ]; cocktailSort(a); document.write(\"Sorted array :\" + \"</br>\"); printArray(a); // This code is contributed by decode2207.</script>", "e": 36205, "s": 34148, "text": null }, { "code": null, "e": 36235, "s": 36205, "text": "Sorted array :\n0 1 2 2 4 5 8 " }, { "code": null, "e": 36769, "s": 36235, "text": "Worst and Average Case Time Complexity: O(n*n). Best Case Time Complexity: O(n). Best case occurs when array is already sorted.Auxiliary Space: O(1)Sorting In Place: YesStable: YesComparison with Bubble Sort: Time complexities are same, but Cocktail performs better than Bubble Sort. Typically cocktail sort is less than two times faster than bubble sort. Consider the example (2, 3, 4, 5, 1). Bubble sort requires four traversals of array for this example, while Cocktail sort requires only two traversals. (Source Wiki)References: " }, { "code": null, "e": 36820, "s": 36769, "text": "https://en.wikipedia.org/wiki/Cocktail_shaker_sort" }, { "code": null, "e": 36883, "s": 36820, "text": "http://will.thimbleby.net/algorithms/doku.php?id=cocktail_sort" }, { "code": null, "e": 36947, "s": 36883, "text": "http://www.programming-algorithms.net/article/40270/Shaker-sort" }, { "code": null, "e": 37369, "s": 36947, "text": "This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 37378, "s": 37371, "text": "Sam007" }, { "code": null, "e": 37389, "s": 37378, "text": "decode2207" }, { "code": null, "e": 37402, "s": 37389, "text": "simmytarika5" }, { "code": null, "e": 37410, "s": 37402, "text": "Sorting" }, { "code": null, "e": 37418, "s": 37410, "text": "Sorting" }, { "code": null, "e": 37516, "s": 37418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37560, "s": 37516, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 37571, "s": 37560, "text": "Radix Sort" }, { "code": null, "e": 37595, "s": 37571, "text": "Merge two sorted arrays" }, { "code": null, "e": 37626, "s": 37595, "text": "Sort an array of 0s, 1s and 2s" }, { "code": null, "e": 37692, "s": 37626, "text": "Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)" }, { "code": null, "e": 37736, "s": 37692, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 37753, "s": 37736, "text": "sort() in Python" }, { "code": null, "e": 37809, "s": 37753, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 37835, "s": 37809, "text": "Python List sort() method" } ]
How does Selenium Webdriver handle the SSL certificate in Edge?
We can handle SSL certificates in Edge browser with Selenium webdriver. This is done with the help of the EdgeOptions class. We shall create an object of this class and set the parameter setAcceptInsecureCerts to the true value. Finally, this information has to be passed to the webdriver object to get the desired browser settings. An SSL is a protocol designed to establish a secured connection between the server and the browser. EdgeOptions e = new EdgeOptions(); e.setAcceptInsecureCerts(true); import org.openqa.selenium.WebDriver; import org.openqa.selenium.edge.EdgeDriver; import org.openqa.selenium.edge.EdgeOptions; public class EdgeBrwserSSL{ public static void main(String[] args) { System.setProperty("webdriver.edge.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\msedgedriver.exe"); //instance of EdgeOptions EdgeOptions e = new EdgeOptions(); //configure setAcceptInsecureCerts to true boolean value e.setAcceptInsecureCerts(true); //object of EdgeDriver WebDriver driver = new EdgeDriver(e); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("application url"); } }
[ { "code": null, "e": 1291, "s": 1062, "text": "We can handle SSL certificates in Edge browser with Selenium webdriver. This is done with the help of the EdgeOptions class. We shall create an object of this class and set the parameter setAcceptInsecureCerts to the true value." }, { "code": null, "e": 1495, "s": 1291, "text": "Finally, this information has to be passed to the webdriver object to get the desired browser settings. An SSL is a protocol designed to establish a secured connection between the server and the browser." }, { "code": null, "e": 1562, "s": 1495, "text": "EdgeOptions e = new EdgeOptions();\ne.setAcceptInsecureCerts(true);" }, { "code": null, "e": 2275, "s": 1562, "text": "import org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.edge.EdgeDriver;\nimport org.openqa.selenium.edge.EdgeOptions;\npublic class EdgeBrwserSSL{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.edge.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\msedgedriver.exe\");\n //instance of EdgeOptions\n EdgeOptions e = new EdgeOptions();\n //configure setAcceptInsecureCerts to true boolean value\n e.setAcceptInsecureCerts(true);\n //object of EdgeDriver\n WebDriver driver = new EdgeDriver(e);\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"application url\");\n }\n}" } ]
Java & MySQL - Environment Setup
To start developing with JDBC, you should setup your JDBC environment by following the steps shown below. We assume that you are working on a Windows platform. Java SE is available for download for free. To download click here, please download a version compatible with your operating system. Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories. Assuming you have installed Java in c:\Program Files\java\jdk directory βˆ’ Right-click on 'My Computer' and select 'Properties'. Right-click on 'My Computer' and select 'Properties'. Click on the 'Environment variables' button under the 'Advanced' tab. Click on the 'Environment variables' button under the 'Advanced' tab. Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way C:\Windows\System32;c:\Program Files\java\jdk\bin Assuming you have installed Java in c:\Program Files\java\jdk directory βˆ’ Edit the 'C:\autoexec.bat' file and add the following line at the end βˆ’ Edit the 'C:\autoexec.bat' file and add the following line at the end βˆ’ SET PATH = %PATH%;C:\Program Files\java\jdk\bin Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc βˆ’ export PATH = /path/to/java:$PATH' You automatically get both JDBC packages java.sql and javax.sql, when you install J2SE Development Kit. The most important thing you will need, of course is an actual running database with a table that you can query and modify. MySQL DB βˆ’ MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. MySQL DB βˆ’ MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8. Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice. Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password. If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you. To create the TUTORIALSPOINT database, use the following steps βˆ’ Open a Command Prompt and change to the installation directory as follows βˆ’ C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Note βˆ’ The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. Start the database server by executing the following command, if it is already not running. C:\Program Files\MySQL\bin>mysqld C:\Program Files\MySQL\bin> Create the TUTORIALSPOINT database by executing the following command βˆ’ C:\Program Files\MySQL\bin> mysqladmin create TUTORIALSPOINT -u guest -p Enter password: ******** C:\Program Files\MySQL\bin> To create the Employees table in TUTORIALSPOINT database, use the following steps βˆ’ Open a Command Prompt and change to the installation directory as follows βˆ’ C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Login to the database as follows βˆ’ C:\Program Files\MySQL\bin>mysql -u guest -p Enter password: ******** mysql> Create the table Employees as follows βˆ’ mysql> use TUTORIALSPOINT; mysql> create table Employees -> ( -> id int not null, -> age int not null, -> first varchar (255), -> last varchar (255) -> ); Query OK, 0 rows affected (0.08 sec) mysql> Finally you create few records in Employee table as follows βˆ’ mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> For a complete understanding on MySQL database, study the MySQL Tutorial. Now you are ready to start experimenting with JDBC. Next chapter gives you a sample example on JDBC Programming. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2846, "s": 2686, "text": "To start developing with JDBC, you should setup your JDBC environment by following the steps shown below. We assume that you are working on a Windows platform." }, { "code": null, "e": 2979, "s": 2846, "text": "Java SE is available for download for free. To download click here, please download a version compatible with your operating system." }, { "code": null, "e": 3207, "s": 2979, "text": "Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories." }, { "code": null, "e": 3281, "s": 3207, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory βˆ’" }, { "code": null, "e": 3335, "s": 3281, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 3389, "s": 3335, "text": "Right-click on 'My Computer' and select 'Properties'." }, { "code": null, "e": 3459, "s": 3389, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 3529, "s": 3459, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 3724, "s": 3529, "text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way" }, { "code": null, "e": 3919, "s": 3724, "text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way" }, { "code": null, "e": 3970, "s": 3919, "text": "C:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin\n" }, { "code": null, "e": 4044, "s": 3970, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory βˆ’" }, { "code": null, "e": 4116, "s": 4044, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end βˆ’" }, { "code": null, "e": 4188, "s": 4116, "text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end βˆ’" }, { "code": null, "e": 4237, "s": 4188, "text": "SET PATH = %PATH%;C:\\Program Files\\java\\jdk\\bin\n" }, { "code": null, "e": 4400, "s": 4237, "text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this." }, { "code": null, "e": 4511, "s": 4400, "text": "For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc βˆ’" }, { "code": null, "e": 4547, "s": 4511, "text": "export PATH = /path/to/java:$PATH'\n" }, { "code": null, "e": 4651, "s": 4547, "text": "You automatically get both JDBC packages java.sql and javax.sql, when you install J2SE Development Kit." }, { "code": null, "e": 4775, "s": 4651, "text": "The most important thing you will need, of course is an actual running database with a table that you can query and modify." }, { "code": null, "e": 4922, "s": 4775, "text": "MySQL DB βˆ’ MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation." }, { "code": null, "e": 5069, "s": 4922, "text": "MySQL DB βˆ’ MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation." }, { "code": null, "e": 5226, "s": 5069, "text": "In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier." }, { "code": null, "e": 5383, "s": 5226, "text": "In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier." }, { "code": null, "e": 5617, "s": 5383, "text": "Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8." }, { "code": null, "e": 5851, "s": 5617, "text": "Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8." }, { "code": null, "e": 6033, "s": 5851, "text": "Accordingly, set CLASSPATH variable to C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8\\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation." }, { "code": null, "e": 6215, "s": 6033, "text": "Accordingly, set CLASSPATH variable to C:\\Program Files\\MySQL\\mysql-connector-java-5.1.8\\mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation." }, { "code": null, "e": 6340, "s": 6215, "text": "When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice." }, { "code": null, "e": 6482, "s": 6340, "text": "Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application." }, { "code": null, "e": 6605, "s": 6482, "text": "There are various database operations like database creation and deletion, which would need administrator ID and password." }, { "code": null, "e": 6707, "s": 6605, "text": "For rest of the JDBC tutorial, we would use MySQL Database with guest as ID and guest123 as password." }, { "code": null, "e": 6862, "s": 6707, "text": "If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you." }, { "code": null, "e": 6927, "s": 6862, "text": "To create the TUTORIALSPOINT database, use the following steps βˆ’" }, { "code": null, "e": 7003, "s": 6927, "text": "Open a Command Prompt and change to the installation directory as follows βˆ’" }, { "code": null, "e": 7068, "s": 7003, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 7246, "s": 7068, "text": "Note βˆ’ The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server." }, { "code": null, "e": 7338, "s": 7246, "text": "Start the database server by executing the following command, if it is already not running." }, { "code": null, "e": 7401, "s": 7338, "text": "C:\\Program Files\\MySQL\\bin>mysqld\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 7473, "s": 7401, "text": "Create the TUTORIALSPOINT database by executing the following command βˆ’" }, { "code": null, "e": 7600, "s": 7473, "text": "C:\\Program Files\\MySQL\\bin> mysqladmin create TUTORIALSPOINT -u guest -p\nEnter password: ********\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 7684, "s": 7600, "text": "To create the Employees table in TUTORIALSPOINT database, use the following steps βˆ’" }, { "code": null, "e": 7760, "s": 7684, "text": "Open a Command Prompt and change to the installation directory as follows βˆ’" }, { "code": null, "e": 7825, "s": 7760, "text": "C:\\>\nC:\\>cd Program Files\\MySQL\\bin\nC:\\Program Files\\MySQL\\bin>\n" }, { "code": null, "e": 7860, "s": 7825, "text": "Login to the database as follows βˆ’" }, { "code": null, "e": 7938, "s": 7860, "text": "C:\\Program Files\\MySQL\\bin>mysql -u guest -p\nEnter password: ********\nmysql>\n" }, { "code": null, "e": 7978, "s": 7938, "text": "Create the table Employees as follows βˆ’" }, { "code": null, "e": 8202, "s": 7978, "text": "mysql> use TUTORIALSPOINT;\nmysql> create table Employees\n -> (\n -> id int not null,\n -> age int not null,\n -> first varchar (255),\n -> last varchar (255)\n -> );\nQuery OK, 0 rows affected (0.08 sec)\nmysql>\n" }, { "code": null, "e": 8264, "s": 8202, "text": "Finally you create few records in Employee table as follows βˆ’" }, { "code": null, "e": 8676, "s": 8264, "text": "mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql>" }, { "code": null, "e": 8750, "s": 8676, "text": "For a complete understanding on MySQL database, study the MySQL Tutorial." }, { "code": null, "e": 8863, "s": 8750, "text": "Now you are ready to start experimenting with JDBC. Next chapter gives you a sample example on JDBC Programming." }, { "code": null, "e": 8896, "s": 8863, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 8912, "s": 8896, "text": " Malhar Lathkar" }, { "code": null, "e": 8945, "s": 8912, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8961, "s": 8945, "text": " Malhar Lathkar" }, { "code": null, "e": 8996, "s": 8961, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 9010, "s": 8996, "text": " Anadi Sharma" }, { "code": null, "e": 9044, "s": 9010, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 9058, "s": 9044, "text": " Tushar Kale" }, { "code": null, "e": 9095, "s": 9058, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 9110, "s": 9095, "text": " Monica Mittal" }, { "code": null, "e": 9143, "s": 9110, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 9162, "s": 9143, "text": " Arnab Chakraborty" }, { "code": null, "e": 9169, "s": 9162, "text": " Print" }, { "code": null, "e": 9180, "s": 9169, "text": " Add Notes" } ]
How do you check if a ResultSet is closed or not in JDBC?
Whenever we execute SQL statements using the executeQuery() method, it returns a ResultSet object which holds the tabular data returned by the SELECT queries(in general). The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position). The isClosed() method of the ResultSet interface is used to determine whether the current ResultSet object is closed. rs.isclosed() Let us create a table with name tutorials_data in MySQL database using CREATE statement as shown below βˆ’ CREATE TABLE tutorials_data ( tutorial_id INT, tutorial_title VARCHAR(100), tutorial_author VARCHAR(40), submission_date date, PRIMARY KEY (tutorial_id) ); Now, we will insert 5 records in tutorials_data table using INSERT statements βˆ’ insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01')); insert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 ')); insert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01')); insert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01')); insert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06')); Following JDBC program establishes connection with the database, retrieves the contents of the above table into a ResultSet object displays it contents. In this we have set the ResultSet holdability to CLOSE_CURSORS_AT_COMMIT. Therefore, soon we close the connection the ResultSet object will be closed. We are verifying whether the ResultSet object is closed using the isClosed() method. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RS_is_closed { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydb"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("select * from tutorials_data"); //Setting the ResultSet to CLOSE_CURSORS_AT_COMMIT con.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); System.out.println("Contents of the ResultSet object:"); while(rs.next()) { System.out.print("ID: "+rs.getInt("tutorial_id")+", "); System.out.print("Title: "+rs.getString("tutorial_title")+", "); System.out.print("Author: "+rs.getString("tutorial_author")+", "); System.out.print("Submission date: "+rs.getDate("submission_date")); System.out.println(); } //Closing the connection con.close(); boolean bool = rs.isClosed(); if(bool) { System.out.println("ResultSet is closed"); } else { System.out.println("ResultSet is not closed"); } } } Connection established...... Contents of the ResultSet object: ID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01 ID: 2, Title: JFreeCharts, Author: Satish kumar, Submission date: 2019-05-01 ID: 3, Title: JavaSprings, Author: Amit Tiwari, Submission date: 2019-03-01 ID: 4, Title: Android, Author: Sai Ram, Submission date: 2019-03-01 ID: 5, Title: Cassandra, Author: Pruthvi Raj, Submission date: 2019-04-06 ResultSet is closed
[ { "code": null, "e": 1233, "s": 1062, "text": "Whenever we execute SQL statements using the executeQuery() method, it returns a ResultSet object which holds the tabular data returned by the SELECT queries(in general)." }, { "code": null, "e": 1386, "s": 1233, "text": "The ResultSet object contains a cursor/pointer which points to the current row. Initially this cursor is positioned before first row (default position)." }, { "code": null, "e": 1504, "s": 1386, "text": "The isClosed() method of the ResultSet interface is used to determine whether the current ResultSet object is closed." }, { "code": null, "e": 1518, "s": 1504, "text": "rs.isclosed()" }, { "code": null, "e": 1623, "s": 1518, "text": "Let us create a table with name tutorials_data in MySQL database using CREATE statement as shown below βˆ’" }, { "code": null, "e": 1794, "s": 1623, "text": "CREATE TABLE tutorials_data (\n tutorial_id INT,\n tutorial_title VARCHAR(100),\n tutorial_author VARCHAR(40),\n submission_date date,\n PRIMARY KEY (tutorial_id)\n);" }, { "code": null, "e": 1874, "s": 1794, "text": "Now, we will insert 5 records in tutorials_data table using INSERT statements βˆ’" }, { "code": null, "e": 2304, "s": 1874, "text": "insert into tutorials_data values(1, 'Java', 'Krishna Kasyap', DATE('2019-09-01'));\ninsert into tutorials_data values(2, 'JFreeCharts', 'Satish Kumar', DATE('2019-05-01 '));\ninsert into tutorials_data values(3, 'JavaSprings', 'Amit Tiwari', DATE(' 2019-05-01'));\ninsert into tutorials_data values(4, 'Android', 'Sai Ram', DATE('2019-03-01'));\ninsert into tutorials_data values(5, 'Cassandra', 'Pruthvi Raj', DATE(' 2019-04-06'));" }, { "code": null, "e": 2457, "s": 2304, "text": "Following JDBC program establishes connection with the database, retrieves the contents of the above table into a ResultSet object displays it contents." }, { "code": null, "e": 2608, "s": 2457, "text": "In this we have set the ResultSet holdability to CLOSE_CURSORS_AT_COMMIT. Therefore, soon we close the connection the ResultSet object will be closed." }, { "code": null, "e": 2693, "s": 2608, "text": "We are verifying whether the ResultSet object is closed using the isClosed() method." }, { "code": null, "e": 4178, "s": 2693, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.Statement;\npublic class RS_is_closed {\n public static void main(String args[]) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydb\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating a Statement object\n Statement stmt = con.createStatement();\n //Retrieving the data\n ResultSet rs = stmt.executeQuery(\"select * from tutorials_data\");\n //Setting the ResultSet to CLOSE_CURSORS_AT_COMMIT\n con.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);\n System.out.println(\"Contents of the ResultSet object:\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"tutorial_id\")+\", \");\n System.out.print(\"Title: \"+rs.getString(\"tutorial_title\")+\", \");\n System.out.print(\"Author: \"+rs.getString(\"tutorial_author\")+\", \");\n System.out.print(\"Submission date: \"+rs.getDate(\"submission_date\"));\n System.out.println();\n }\n //Closing the connection\n con.close();\n boolean bool = rs.isClosed();\n if(bool) {\n System.out.println(\"ResultSet is closed\");\n } else {\n System.out.println(\"ResultSet is not closed\");\n }\n }\n}" }, { "code": null, "e": 4628, "s": 4178, "text": "Connection established......\nContents of the ResultSet object:\nID: 1, Title: Java, Author: Krishna Kasyap, Submission date: 2019-09-01\nID: 2, Title: JFreeCharts, Author: Satish kumar, Submission date: 2019-05-01\nID: 3, Title: JavaSprings, Author: Amit Tiwari, Submission date: 2019-03-01\nID: 4, Title: Android, Author: Sai Ram, Submission date: 2019-03-01\nID: 5, Title: Cassandra, Author: Pruthvi Raj, Submission date: 2019-04-06\nResultSet is closed" } ]
Fast and Robust Sliding Window Vectorization with NumPy | by Syafiq Kamarul Azman | Towards Data Science
Once in a while, you get to work with the underdog of the data world: time series (images and natural language have been in the limelight a lot, recently!). I’ve been lucky (or unlucky) enough to have had to work on time series data for the most part of last year. Among my adventures in the wacky world of 1-dimensional machine learning, I found some very useful vectorization that allowed me through blaze through my data pre-processing stage. I wanted to share these tricks that were instrumental in accelerating my tasks in hopes that it could do so for you. We will be working with multivariate time-domain simulations in this article. Our goal here is to learn how to develop a component in a performant data pipeline. NumPy is my library of choice for executing the matrix operations. Let’s get to it! More commonly, you will see time series as a single line that cuts through a plot while progressing up or down. On the horizontal axis, time proceeds gracefully, yet ever so regularly while on the vertical axis, measurements or values stand recorded. A unit in the horizontal axis is what we will term a timestep. Multivariate time series are similar with the difference being that the lonely line is now accompanied by other lines propagating through in parallel. One common example of a multivariate time series data is a weather station measuring temperature, humidity, pressure, and other facets of the environment at regular intervals. Another is electroencephalograms which capture the brain activity using multiple electrodes producing many readings in parallel. More abstractly, sheet music can be interpreted as multivariate time series: the instruments are different channels of information over a regular sampling time (tempo) of the piece. My research looks at transient stability in power systems when a fault occurs. During a fault in a power system, a measure is taken to mitigate the mishap. Depending on what state the system is in, where the fault happened and how long it took to clear away that fault, the system can go two ways: return to stability or diverge to instability. One way to determine this is to simulate a bunch of states, fault locations, and clearing times, then learn from the dynamics of the system to predict whether the system stabilizes or explodes (okay, not really). The data we capture comes from phasor measurements over a period of time at different buses (bold solid lines) in the power system. Since there are many buses and each bus measures different types of data, this naturally lends itself to multivariate time series data. We will be working with some of those simulation data for the purposes of this article. It is known that the transient stability phenomenon can be predicted by taking a small section of the entire data. Most of the remainder of the time series is superfluous. Our goal is to extract important regions of the signal for a training dataset. I will first introduce the core concept of a basic extraction before diving deeper and extending the functionality of the extractor. You can find the dataset for the 9 bus system on this link or on my website as a gzipped folder of NumPy matrix files along with some metadata. The metadata column which has particular importance here is the clearing time. Take a few minutes to digest the data if you want. The part of the signal that we want is around the clearing time of the simulation. We want a window of information before the clearing time and after the clearing time; called the main window. The main window can span up to some maximum timestep after the clearing time, we call this max time. Within the main window, we want a bunch of smaller windows, called sub-windows, that will make up our training examples. The main window should accommodate such that there is a sub-window-sized amount of timesteps before the clearing time. This is a lot to capture but maybe a figure can help us understand the structure of these windows. We will use the voltage magnitude for case 693 for all illustrations going forward. Essentially, we want to slide a sub-window across the main window, step by step, and collect the information at each timestep. The first sub-window must contain the first timestep after the clearing time. The rationale here is that we only know the time at which the fault is cleared in the system (the clearing time). Therefore, the earliest we can have any usable data is the next timestep after clearance. Let’s capture a main window with a max time of 10 timesteps. Within the main window, we can take 11 sub-windows of size 5 timesteps. Visually: 1st timestep after clearing --| |-- max time v vmain_window = [..., 5, 6, 7, 8, 9, 10, ..., 19] ^ clearing time index --|sub_windows = [ [ 5, 6, 7, 8, 9], [ 6, 7, 8, 9, 10], ... [15, 16, 17, 18, 19]] So if I have a max time T, and a sub-window of size K, I can get T+1 examples from one simulation (including the index at the max time). This scheme disregards K because we can increase K to whatever size we want which will in turn increase the size of the left half of the main window (assuming we don’t underflow the data matrix). This means extracting data with a sub-window of either size 5 or size 8 gives you an identical number of sub-windows but of different sub-window sizes. Awesome! Now that we have the framework, we can roughly plan out the extraction function. We have the input information as a 2-dimensional (2D) matrix where timesteps propagate down the rows, and features are distributed across the columns. Visually, a sample input matrix with 4 features and 6 timesteps would look like this: Feature 1 Feature 2 Feature 3 Feature 4 ------------------------------------------[[ -5.29328 , 9.89139 , -2.79590 , -8.73531 ], Time=1 | [ -5.29345 , 9.89152 , -2.79595 , -8.73542 ], Time=2 | [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 | [ -5.29451 , 9.89257 , -2.79702 , -8.73649 ], Time=5 | [ -5.29479 , 9.89258 , -2.79732 , -8.73643 ]] Time=6 V Our target output matrix is a 3D matrix that looks something like this (assuming we want a sliding window of size 4): Feature 1 Feature 2 Feature 3 Feature 4 ------------------------------------------[[[ -5.29328 , 9.89139 , -2.79590 , -8.73531 ], Time=1 | [ -5.29345 , 9.89152 , -2.79595 , -8.73542 ], Time=2 | [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 V [ -5.29345 , 9.89152 , -2.79595 , -8.73542 ], Time=2 | [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 | [ -5.29451 , 9.89257 , -2.79702 , -8.73649 ], Time=5 V [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 | [ -5.29451 , 9.89257 , -2.79702 , -8.73649 ], Time=5 | [ -5.29479 , 9.89258 , -2.79732 , -8.73643 ]]] Time=6 V This should be trivial: just loop over the timesteps and slice the rows of the matrix to get the sub-windows. The function takes the array from which the data is extracted, the clearing time index which is the index of our clearing time, the max timesteps (T), and the sub-window size (K). First, we declare an empty list to store our output sub-windows. Then we define the start index which is the index at which the sliding window will begin. Using the T+1 rule explained earlier, we know how many data points we expect. All that’s left is a for-loop to extract the data from the array using good old slicing. As our goal is to collect a bunch of 2D matrices, it would be wise to stack the data in a batch using a 3D matrix where the first dimension would tell you how many 2D matrices are available. Hence the use of expand_dims and vstack to achieve this. That looks like a good solution, right? That wasn’t so bad. Or is it? Well, Python for-loops are notoriously slow and we are not exploiting the capabilities of NumPy’s fancy indexing. At the moment, we don’t really have anything to compare the for-loop method, but try to convince yourself that it is indeed bad and that we can do better. So, let’s see a few tricks of fancy indexing that will help us reach a blazing fast sliding window extraction function. Trick #1: We can index any row of a 2D matrix arbitrarily using a 1D matrix of integer indices. What we did was pick the row indices 7, 4, 1, and 2 out of the 2D matrix X by using an array of indices. By knowing what indices we want, NumPy allows us to forgo loops and instead immediately index the rows that we need. The analog of a single sub-window in our sliding window is indexing an array of consecutive numbers. But, really, this isn’t much more useful compared to the slicing that we have used in our original code since you would need to loop and create consecutive arrays of indices to extract all the sub-windows. However, Trick #1 is only the prelude to a more powerful trick. Trick #2: We can index any 2D sub-matrix of rows of a 2D matrix using a 2D matrix of integer indices (wow, that’s a mouthful of 2Ds). This is a little harder to catch but let’s understand what is going on. First, we created a matrix, I, which is a 3Γ—4 matrix of integers. Then, we indexed multiple rows of X together using NumPy’s fancy indexing giving us a 3D matrix. The first index of the output 3D matrix is the 2D matrix as if we used Trick #1 on matrix X with the indices [7, 4, 1, 2]. Similarly, the second index of the 3D matrix is the output of applying Trick #1 on X with the indices [5, 6, 8, 9]. Can you figure out the third index of the output 3D matrix? Basically, we have found a way to vectorize the outer for-loop in the starter code: we can create a 2D matrix of integers that contains consecutive indices of our simulation data and apply Trick #2 to quickly extract a 3D array that contains those sub-windows. If instead, we replaced matrix I with the matrix below, we can quickly get our sliding window sub-windows. I = np.array([[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5]) Now that we know we can index arbitrarily any 2D matrix, we can come up with a systematic way to compose matrix I so that we can generalize this indexing to any sub-window size and up to any max time to vectorize the sliding window extraction. This part is a little math-heavy with lots of symbols flying around so feel free to leave a comment if you don’t follow anything. Knowing Trick #2, what we are looking to extract is a 2D matrix of consecutive indices equal to the width of the sub-window. The main window would span from the clearing time plus one (C) minus the sub-window size (K) until the max time (T). Specifically, we want to fancily index our data using the following (T+1)Γ—K indexer matrix: [[C-K+1 , C-K+2 , C-K+3 , ..., C ] [C-K+2 , C-K+3 , C-K+4 , ..., C+1 ]I = [C-K+3 , C-K+4 , C-K+5 , ..., C+2 ] [ ..., ] [C+T-K+1, C+T-K+2, C+T-K+3, ..., C+T ]] Okay, I have to admit, I did spend some time making sense of this matrix (mainly because of Python’s 0-indexing scheme). But, in essence, this is the application of Trick #2 to a generic situation in our sliding window extraction. Ideally, we would also generate this 2D indexer matrix without using for-loops too: they’re just that slow! We can actually simplify this matrix significantly by calculating our starting index. The starting index (S) is calculated as S = C - K+1 = C - (K - 1). Thus, we can represent our index matrix in the simpler-to-understand version: [[0 , 1 , 2 , ..., K-1 ] [1 , 2 , 3 , ..., K ]I = S + [2 , 3 , 4 , ..., K+1 ] [ ..., ] [T , T+1 , T+2 , ..., T+K-1]] Simply, we add an offset amount, S, to a (T+1)Γ—K matrix. This matrix has rows of consecutive values across the columns from 0 up to K - 1, and each row starts with increasing consecutive values down the rows from 0 up to T. We know that we will have T+1 sub-windows, so we just need to have consecutive indices up to the size of the sub-window T+1 times. This would get the same matrix as we would above. In fact, we can represent this matrix in a yet simpler decomposition: [[0 , 1 , 2 , ..., K-1] [[0, 0, 0, ..., 0] [0 , 1 , 2 , ..., K-1] [1, 1, 1, ..., 1]S + [0 , 1 , 2 , ..., K-1] + [2, 2, 2, ..., 2] [ ..., ] ..., [0 , 1 , 2 , ..., K-1]] [T, T, T, ..., T]] The astute among you might’ve seen this coming from the second matrix already but let’s go through it. Since we know that each sub-window has size K, we really just need to make a matrix of consecutive indices once. Also, with the information of T+1 consecutive sub-windows, we just need to add the values [0, 1, 2, ..., T] to each of the sub-window indices one at a time. Using a clever vectorization technique called broadcasting, we don’t even have to construct the whole middle and right 2D matrices of the addition. Rather, we only need to create a 1Γ—K and a (T+1)Γ—1 matrix instead of two (T+1)Γ—K matrices: [[0] [1]S + [[0 , 1 , 2 , ..., K-1]] + [2] ... [T]] By broadcasting the addition of the center row matrix and the right column matrix, we can get the original (T+1)Γ—K matrix that we needed. Let’s see this in code. If the elegance is not convincing enough for you, perhaps hard numbers will. To test the performance, I first created two matrices, X and Y, with equal size but different data using NumPy’s random.randn function. This ensures that any computation between the two functions is not cached between the runs. Then I run the loop-based extractor on X and the vectorized extractor on Y. The extraction yields a matrix of size 1201Γ—10Γ—200. What a significant speed up! Our vectorized implementation drove circles around the loop-based extractor. This is particularly useful when you are processing multiple files and want to extract lots of windows from many different files one at a time. There are however some caveats to this method. With the for-loop, we extract data without having to create a 2D matrix to index the original matrix. This is definitely β€œeasier” on the memory, but I argue that since our output matrix is much larger than the indexer matrix, ultimately that’s the decisive memory consumer. That’s pretty much the core of it. Now let’s explore how to make full use of this vectorization to perform other manipulations to the time series data. Alright, let’s add more features to our window extractor. Of course, we’ll keep the vectorization flavor going. What if we wanted to slide the window over more than one timestep? Like this: Borrowing the terminology of convolutional neural network filter operations, we call this striding windows. You can imagine this to be a relatively simple augmentation to our indexing matrix. Specifically, we are looking at an indexing matrix like this: [[0 ] [V ]S + [[0 , 1 , 2 , ..., K-1]] + [2V] ... [T ]] I’m running out of clever symbol names so I’m going to denote the number of spaces as V for the stride size. When V is 1, this is the basic sliding-window code we have above. Any larger integer values will determine how much it jumps resulting in a smaller set of output sub-windows. We need to be careful: since our max time (T) hasn’t changed, we will need to account for reducing the size of the rightmost vector. There are two ways around this: Create the entire array of indices (as we did before) and do fancy indexing to select every V row from that array, or,Create the rightmost vector that looks like the one in the block above. Create the entire array of indices (as we did before) and do fancy indexing to select every V row from that array, or, Create the rightmost vector that looks like the one in the block above. Let’s code both implementations. Not sure which one is better? Let’s do a similar test as we did before and measure the performance. The only difference in the arguments that I pass to the function now is the stride size which is 3. As you can see, there isn’t much difference, but variant 1 is slightly (but, negligibly) slower than variant 2. I attribute this slow down in variant 1 to the fact that it has to make a full (T+1)Γ—K matrix and then slice it. In contrast, variant 2 creates the stride indices immediately which could save time and memory in the long run. In my research, the simulator is able to generate signals at a frequency much higher than what is practically possible. The real-world devices usually sample at around 50Hz or 60Hz (50/60 timesteps per second) while the simulator can generate data above 1kHz (>1000 timesteps per second). Downsampling the simulation data can be useful for training models that are deployable in a production environment. We can easily downsample the sub-windows using the same technique presented in the striding windows part earlier, with the exception that we create a striding sub-windows vector. But this can only work if our downsampling rate is evenly divisible. For example, if we have to downsample 1kHz to 100Hz, we just take every 10 timesteps in the sub-window (we have a downsampling ratio (R) of 10). However, if we are downsampling 1kHz to 60Hz, we need to take every 16.667 timesteps which is not an integer downsampling ratio. We can cheat a bit without too much issue by rounding the steps multiplied by the downsampling ratio (R). When R is equal to 1, this is, yet again, our basic sliding window. More importantly, we also need to consider how the data window is spaced out. We wanted a certain sub-window size which now has an interval of the sampling ratio. Also, the max timesteps that we need to capture are also similarly spaced. Let’s view this in our good friend, the matrix: [[0 ] [R ]S' + [[0 , R , 2R , ..., (K-1)R]] + [2R] ... [TR]] There are a few things to note here. S’ is a new starting point index accounting for the spaced-out sub-window, R is our downsampling ratio, and accordingly, we have to adjust the spacing to capture the desired max timesteps. Caveat: R should not be less than 1; otherwise you’re sampling data in between unit timesteps which entails interpolation. Calculating S’ is relatively simple, we just need to subtract from the clearing time (C) the size of the sub-window (K) minus one multiplied by the sampling rate; mathematically, we have S’ = C - (K - 1)R. This will ensure that the first timestep after clearance is the last data point in the first index. Okay, enough maths, let’s code. Downsampled windows maintain the same output window size as a standard sliding window but occupy a greater time scale. This can be useful if you want to keep your data similar in size but cover timesteps that are more spaced-out. I hope you’ve found some awesome tricks to help you vectorize your sliding window pre-processing workflows. Changing your mindset to approach matrix manipulation without for-loops can be tough but once you get the hang of it, it feels more natural. My biggest challenge was thinking of the outputs in high dimensional matrices which feels so foreign (and still does sometimes). The only gripe with this technique that I have is the maintainability factor of the code decreases since you’d have to ensure that the people using your code can understand what the vectorization is doing. This means having solid documentation alongside the function is crucial and naming your variables sensibly is paramount for other’s understanding. The extensions to the basic sliding window vectorization will hopefully inspire you to try out your own complex vectorization to speed up your data pipeline. When you get it running, you’ll feel like a NumPy ninja, honest! Nevertheless, the increased performance will leave you waiting a lot less for files to process. What better way to keep working more and minimizing your idle time. Right?
[ { "code": null, "e": 735, "s": 172, "text": "Once in a while, you get to work with the underdog of the data world: time series (images and natural language have been in the limelight a lot, recently!). I’ve been lucky (or unlucky) enough to have had to work on time series data for the most part of last year. Among my adventures in the wacky world of 1-dimensional machine learning, I found some very useful vectorization that allowed me through blaze through my data pre-processing stage. I wanted to share these tricks that were instrumental in accelerating my tasks in hopes that it could do so for you." }, { "code": null, "e": 981, "s": 735, "text": "We will be working with multivariate time-domain simulations in this article. Our goal here is to learn how to develop a component in a performant data pipeline. NumPy is my library of choice for executing the matrix operations. Let’s get to it!" }, { "code": null, "e": 1446, "s": 981, "text": "More commonly, you will see time series as a single line that cuts through a plot while progressing up or down. On the horizontal axis, time proceeds gracefully, yet ever so regularly while on the vertical axis, measurements or values stand recorded. A unit in the horizontal axis is what we will term a timestep. Multivariate time series are similar with the difference being that the lonely line is now accompanied by other lines propagating through in parallel." }, { "code": null, "e": 1933, "s": 1446, "text": "One common example of a multivariate time series data is a weather station measuring temperature, humidity, pressure, and other facets of the environment at regular intervals. Another is electroencephalograms which capture the brain activity using multiple electrodes producing many readings in parallel. More abstractly, sheet music can be interpreted as multivariate time series: the instruments are different channels of information over a regular sampling time (tempo) of the piece." }, { "code": null, "e": 2491, "s": 1933, "text": "My research looks at transient stability in power systems when a fault occurs. During a fault in a power system, a measure is taken to mitigate the mishap. Depending on what state the system is in, where the fault happened and how long it took to clear away that fault, the system can go two ways: return to stability or diverge to instability. One way to determine this is to simulate a bunch of states, fault locations, and clearing times, then learn from the dynamics of the system to predict whether the system stabilizes or explodes (okay, not really)." }, { "code": null, "e": 3019, "s": 2491, "text": "The data we capture comes from phasor measurements over a period of time at different buses (bold solid lines) in the power system. Since there are many buses and each bus measures different types of data, this naturally lends itself to multivariate time series data. We will be working with some of those simulation data for the purposes of this article. It is known that the transient stability phenomenon can be predicted by taking a small section of the entire data. Most of the remainder of the time series is superfluous." }, { "code": null, "e": 3098, "s": 3019, "text": "Our goal is to extract important regions of the signal for a training dataset." }, { "code": null, "e": 3505, "s": 3098, "text": "I will first introduce the core concept of a basic extraction before diving deeper and extending the functionality of the extractor. You can find the dataset for the 9 bus system on this link or on my website as a gzipped folder of NumPy matrix files along with some metadata. The metadata column which has particular importance here is the clearing time. Take a few minutes to digest the data if you want." }, { "code": null, "e": 4222, "s": 3505, "text": "The part of the signal that we want is around the clearing time of the simulation. We want a window of information before the clearing time and after the clearing time; called the main window. The main window can span up to some maximum timestep after the clearing time, we call this max time. Within the main window, we want a bunch of smaller windows, called sub-windows, that will make up our training examples. The main window should accommodate such that there is a sub-window-sized amount of timesteps before the clearing time. This is a lot to capture but maybe a figure can help us understand the structure of these windows. We will use the voltage magnitude for case 693 for all illustrations going forward." }, { "code": null, "e": 4631, "s": 4222, "text": "Essentially, we want to slide a sub-window across the main window, step by step, and collect the information at each timestep. The first sub-window must contain the first timestep after the clearing time. The rationale here is that we only know the time at which the fault is cleared in the system (the clearing time). Therefore, the earliest we can have any usable data is the next timestep after clearance." }, { "code": null, "e": 4774, "s": 4631, "text": "Let’s capture a main window with a max time of 10 timesteps. Within the main window, we can take 11 sub-windows of size 5 timesteps. Visually:" }, { "code": null, "e": 5080, "s": 4774, "text": " 1st timestep after clearing --| |-- max time v vmain_window = [..., 5, 6, 7, 8, 9, 10, ..., 19] ^ clearing time index --|sub_windows = [ [ 5, 6, 7, 8, 9], [ 6, 7, 8, 9, 10], ... [15, 16, 17, 18, 19]]" }, { "code": null, "e": 5565, "s": 5080, "text": "So if I have a max time T, and a sub-window of size K, I can get T+1 examples from one simulation (including the index at the max time). This scheme disregards K because we can increase K to whatever size we want which will in turn increase the size of the left half of the main window (assuming we don’t underflow the data matrix). This means extracting data with a sub-window of either size 5 or size 8 gives you an identical number of sub-windows but of different sub-window sizes." }, { "code": null, "e": 5892, "s": 5565, "text": "Awesome! Now that we have the framework, we can roughly plan out the extraction function. We have the input information as a 2-dimensional (2D) matrix where timesteps propagate down the rows, and features are distributed across the columns. Visually, a sample input matrix with 4 features and 6 timesteps would look like this:" }, { "code": null, "e": 6317, "s": 5892, "text": " Feature 1 Feature 2 Feature 3 Feature 4 ------------------------------------------[[ -5.29328 , 9.89139 , -2.79590 , -8.73531 ], Time=1 | [ -5.29345 , 9.89152 , -2.79595 , -8.73542 ], Time=2 | [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 | [ -5.29451 , 9.89257 , -2.79702 , -8.73649 ], Time=5 | [ -5.29479 , 9.89258 , -2.79732 , -8.73643 ]] Time=6 V" }, { "code": null, "e": 6435, "s": 6317, "text": "Our target output matrix is a 3D matrix that looks something like this (assuming we want a sliding window of size 4):" }, { "code": null, "e": 7222, "s": 6435, "text": " Feature 1 Feature 2 Feature 3 Feature 4 ------------------------------------------[[[ -5.29328 , 9.89139 , -2.79590 , -8.73531 ], Time=1 | [ -5.29345 , 9.89152 , -2.79595 , -8.73542 ], Time=2 | [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 V [ -5.29345 , 9.89152 , -2.79595 , -8.73542 ], Time=2 | [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 | [ -5.29451 , 9.89257 , -2.79702 , -8.73649 ], Time=5 V [ -5.29396 , 9.89200 , -2.79644 , -8.73593 ], Time=3 | [ -5.29416 , 9.89222 , -2.79671 , -8.73614 ], Time=4 | [ -5.29451 , 9.89257 , -2.79702 , -8.73649 ], Time=5 | [ -5.29479 , 9.89258 , -2.79732 , -8.73643 ]]] Time=6 V" }, { "code": null, "e": 7332, "s": 7222, "text": "This should be trivial: just loop over the timesteps and slice the rows of the matrix to get the sub-windows." }, { "code": null, "e": 7834, "s": 7332, "text": "The function takes the array from which the data is extracted, the clearing time index which is the index of our clearing time, the max timesteps (T), and the sub-window size (K). First, we declare an empty list to store our output sub-windows. Then we define the start index which is the index at which the sliding window will begin. Using the T+1 rule explained earlier, we know how many data points we expect. All that’s left is a for-loop to extract the data from the array using good old slicing." }, { "code": null, "e": 8082, "s": 7834, "text": "As our goal is to collect a bunch of 2D matrices, it would be wise to stack the data in a batch using a 3D matrix where the first dimension would tell you how many 2D matrices are available. Hence the use of expand_dims and vstack to achieve this." }, { "code": null, "e": 8541, "s": 8082, "text": "That looks like a good solution, right? That wasn’t so bad. Or is it? Well, Python for-loops are notoriously slow and we are not exploiting the capabilities of NumPy’s fancy indexing. At the moment, we don’t really have anything to compare the for-loop method, but try to convince yourself that it is indeed bad and that we can do better. So, let’s see a few tricks of fancy indexing that will help us reach a blazing fast sliding window extraction function." }, { "code": null, "e": 8637, "s": 8541, "text": "Trick #1: We can index any row of a 2D matrix arbitrarily using a 1D matrix of integer indices." }, { "code": null, "e": 8859, "s": 8637, "text": "What we did was pick the row indices 7, 4, 1, and 2 out of the 2D matrix X by using an array of indices. By knowing what indices we want, NumPy allows us to forgo loops and instead immediately index the rows that we need." }, { "code": null, "e": 8960, "s": 8859, "text": "The analog of a single sub-window in our sliding window is indexing an array of consecutive numbers." }, { "code": null, "e": 9230, "s": 8960, "text": "But, really, this isn’t much more useful compared to the slicing that we have used in our original code since you would need to loop and create consecutive arrays of indices to extract all the sub-windows. However, Trick #1 is only the prelude to a more powerful trick." }, { "code": null, "e": 9364, "s": 9230, "text": "Trick #2: We can index any 2D sub-matrix of rows of a 2D matrix using a 2D matrix of integer indices (wow, that’s a mouthful of 2Ds)." }, { "code": null, "e": 9898, "s": 9364, "text": "This is a little harder to catch but let’s understand what is going on. First, we created a matrix, I, which is a 3Γ—4 matrix of integers. Then, we indexed multiple rows of X together using NumPy’s fancy indexing giving us a 3D matrix. The first index of the output 3D matrix is the 2D matrix as if we used Trick #1 on matrix X with the indices [7, 4, 1, 2]. Similarly, the second index of the 3D matrix is the output of applying Trick #1 on X with the indices [5, 6, 8, 9]. Can you figure out the third index of the output 3D matrix?" }, { "code": null, "e": 10266, "s": 9898, "text": "Basically, we have found a way to vectorize the outer for-loop in the starter code: we can create a 2D matrix of integers that contains consecutive indices of our simulation data and apply Trick #2 to quickly extract a 3D array that contains those sub-windows. If instead, we replaced matrix I with the matrix below, we can quickly get our sliding window sub-windows." }, { "code": null, "e": 10348, "s": 10266, "text": "I = np.array([[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5])" }, { "code": null, "e": 10592, "s": 10348, "text": "Now that we know we can index arbitrarily any 2D matrix, we can come up with a systematic way to compose matrix I so that we can generalize this indexing to any sub-window size and up to any max time to vectorize the sliding window extraction." }, { "code": null, "e": 10722, "s": 10592, "text": "This part is a little math-heavy with lots of symbols flying around so feel free to leave a comment if you don’t follow anything." }, { "code": null, "e": 11056, "s": 10722, "text": "Knowing Trick #2, what we are looking to extract is a 2D matrix of consecutive indices equal to the width of the sub-window. The main window would span from the clearing time plus one (C) minus the sub-window size (K) until the max time (T). Specifically, we want to fancily index our data using the following (T+1)Γ—K indexer matrix:" }, { "code": null, "e": 11268, "s": 11056, "text": " [[C-K+1 , C-K+2 , C-K+3 , ..., C ] [C-K+2 , C-K+3 , C-K+4 , ..., C+1 ]I = [C-K+3 , C-K+4 , C-K+5 , ..., C+2 ] [ ..., ] [C+T-K+1, C+T-K+2, C+T-K+3, ..., C+T ]]" }, { "code": null, "e": 11838, "s": 11268, "text": "Okay, I have to admit, I did spend some time making sense of this matrix (mainly because of Python’s 0-indexing scheme). But, in essence, this is the application of Trick #2 to a generic situation in our sliding window extraction. Ideally, we would also generate this 2D indexer matrix without using for-loops too: they’re just that slow! We can actually simplify this matrix significantly by calculating our starting index. The starting index (S) is calculated as S = C - K+1 = C - (K - 1). Thus, we can represent our index matrix in the simpler-to-understand version:" }, { "code": null, "e": 12045, "s": 11838, "text": " [[0 , 1 , 2 , ..., K-1 ] [1 , 2 , 3 , ..., K ]I = S + [2 , 3 , 4 , ..., K+1 ] [ ..., ] [T , T+1 , T+2 , ..., T+K-1]]" }, { "code": null, "e": 12520, "s": 12045, "text": "Simply, we add an offset amount, S, to a (T+1)Γ—K matrix. This matrix has rows of consecutive values across the columns from 0 up to K - 1, and each row starts with increasing consecutive values down the rows from 0 up to T. We know that we will have T+1 sub-windows, so we just need to have consecutive indices up to the size of the sub-window T+1 times. This would get the same matrix as we would above. In fact, we can represent this matrix in a yet simpler decomposition:" }, { "code": null, "e": 12780, "s": 12520, "text": " [[0 , 1 , 2 , ..., K-1] [[0, 0, 0, ..., 0] [0 , 1 , 2 , ..., K-1] [1, 1, 1, ..., 1]S + [0 , 1 , 2 , ..., K-1] + [2, 2, 2, ..., 2] [ ..., ] ..., [0 , 1 , 2 , ..., K-1]] [T, T, T, ..., T]]" }, { "code": null, "e": 13153, "s": 12780, "text": "The astute among you might’ve seen this coming from the second matrix already but let’s go through it. Since we know that each sub-window has size K, we really just need to make a matrix of consecutive indices once. Also, with the information of T+1 consecutive sub-windows, we just need to add the values [0, 1, 2, ..., T] to each of the sub-window indices one at a time." }, { "code": null, "e": 13392, "s": 13153, "text": "Using a clever vectorization technique called broadcasting, we don’t even have to construct the whole middle and right 2D matrices of the addition. Rather, we only need to create a 1Γ—K and a (T+1)Γ—1 matrix instead of two (T+1)Γ—K matrices:" }, { "code": null, "e": 13584, "s": 13392, "text": " [[0] [1]S + [[0 , 1 , 2 , ..., K-1]] + [2] ... [T]]" }, { "code": null, "e": 13746, "s": 13584, "text": "By broadcasting the addition of the center row matrix and the right column matrix, we can get the original (T+1)Γ—K matrix that we needed. Let’s see this in code." }, { "code": null, "e": 14179, "s": 13746, "text": "If the elegance is not convincing enough for you, perhaps hard numbers will. To test the performance, I first created two matrices, X and Y, with equal size but different data using NumPy’s random.randn function. This ensures that any computation between the two functions is not cached between the runs. Then I run the loop-based extractor on X and the vectorized extractor on Y. The extraction yields a matrix of size 1201Γ—10Γ—200." }, { "code": null, "e": 14750, "s": 14179, "text": "What a significant speed up! Our vectorized implementation drove circles around the loop-based extractor. This is particularly useful when you are processing multiple files and want to extract lots of windows from many different files one at a time. There are however some caveats to this method. With the for-loop, we extract data without having to create a 2D matrix to index the original matrix. This is definitely β€œeasier” on the memory, but I argue that since our output matrix is much larger than the indexer matrix, ultimately that’s the decisive memory consumer." }, { "code": null, "e": 14902, "s": 14750, "text": "That’s pretty much the core of it. Now let’s explore how to make full use of this vectorization to perform other manipulations to the time series data." }, { "code": null, "e": 15014, "s": 14902, "text": "Alright, let’s add more features to our window extractor. Of course, we’ll keep the vectorization flavor going." }, { "code": null, "e": 15092, "s": 15014, "text": "What if we wanted to slide the window over more than one timestep? Like this:" }, { "code": null, "e": 15346, "s": 15092, "text": "Borrowing the terminology of convolutional neural network filter operations, we call this striding windows. You can imagine this to be a relatively simple augmentation to our indexing matrix. Specifically, we are looking at an indexing matrix like this:" }, { "code": null, "e": 15548, "s": 15346, "text": " [[0 ] [V ]S + [[0 , 1 , 2 , ..., K-1]] + [2V] ... [T ]]" }, { "code": null, "e": 15997, "s": 15548, "text": "I’m running out of clever symbol names so I’m going to denote the number of spaces as V for the stride size. When V is 1, this is the basic sliding-window code we have above. Any larger integer values will determine how much it jumps resulting in a smaller set of output sub-windows. We need to be careful: since our max time (T) hasn’t changed, we will need to account for reducing the size of the rightmost vector. There are two ways around this:" }, { "code": null, "e": 16187, "s": 15997, "text": "Create the entire array of indices (as we did before) and do fancy indexing to select every V row from that array, or,Create the rightmost vector that looks like the one in the block above." }, { "code": null, "e": 16306, "s": 16187, "text": "Create the entire array of indices (as we did before) and do fancy indexing to select every V row from that array, or," }, { "code": null, "e": 16378, "s": 16306, "text": "Create the rightmost vector that looks like the one in the block above." }, { "code": null, "e": 16411, "s": 16378, "text": "Let’s code both implementations." }, { "code": null, "e": 16511, "s": 16411, "text": "Not sure which one is better? Let’s do a similar test as we did before and measure the performance." }, { "code": null, "e": 16948, "s": 16511, "text": "The only difference in the arguments that I pass to the function now is the stride size which is 3. As you can see, there isn’t much difference, but variant 1 is slightly (but, negligibly) slower than variant 2. I attribute this slow down in variant 1 to the fact that it has to make a full (T+1)Γ—K matrix and then slice it. In contrast, variant 2 creates the stride indices immediately which could save time and memory in the long run." }, { "code": null, "e": 17353, "s": 16948, "text": "In my research, the simulator is able to generate signals at a frequency much higher than what is practically possible. The real-world devices usually sample at around 50Hz or 60Hz (50/60 timesteps per second) while the simulator can generate data above 1kHz (>1000 timesteps per second). Downsampling the simulation data can be useful for training models that are deployable in a production environment." }, { "code": null, "e": 17875, "s": 17353, "text": "We can easily downsample the sub-windows using the same technique presented in the striding windows part earlier, with the exception that we create a striding sub-windows vector. But this can only work if our downsampling rate is evenly divisible. For example, if we have to downsample 1kHz to 100Hz, we just take every 10 timesteps in the sub-window (we have a downsampling ratio (R) of 10). However, if we are downsampling 1kHz to 60Hz, we need to take every 16.667 timesteps which is not an integer downsampling ratio." }, { "code": null, "e": 18335, "s": 17875, "text": "We can cheat a bit without too much issue by rounding the steps multiplied by the downsampling ratio (R). When R is equal to 1, this is, yet again, our basic sliding window. More importantly, we also need to consider how the data window is spaced out. We wanted a certain sub-window size which now has an interval of the sampling ratio. Also, the max timesteps that we need to capture are also similarly spaced. Let’s view this in our good friend, the matrix:" }, { "code": null, "e": 18562, "s": 18335, "text": " [[0 ] [R ]S' + [[0 , R , 2R , ..., (K-1)R]] + [2R] ... [TR]]" }, { "code": null, "e": 18911, "s": 18562, "text": "There are a few things to note here. S’ is a new starting point index accounting for the spaced-out sub-window, R is our downsampling ratio, and accordingly, we have to adjust the spacing to capture the desired max timesteps. Caveat: R should not be less than 1; otherwise you’re sampling data in between unit timesteps which entails interpolation." }, { "code": null, "e": 19249, "s": 18911, "text": "Calculating S’ is relatively simple, we just need to subtract from the clearing time (C) the size of the sub-window (K) minus one multiplied by the sampling rate; mathematically, we have S’ = C - (K - 1)R. This will ensure that the first timestep after clearance is the last data point in the first index. Okay, enough maths, let’s code." }, { "code": null, "e": 19479, "s": 19249, "text": "Downsampled windows maintain the same output window size as a standard sliding window but occupy a greater time scale. This can be useful if you want to keep your data similar in size but cover timesteps that are more spaced-out." }, { "code": null, "e": 19857, "s": 19479, "text": "I hope you’ve found some awesome tricks to help you vectorize your sliding window pre-processing workflows. Changing your mindset to approach matrix manipulation without for-loops can be tough but once you get the hang of it, it feels more natural. My biggest challenge was thinking of the outputs in high dimensional matrices which feels so foreign (and still does sometimes)." }, { "code": null, "e": 20210, "s": 19857, "text": "The only gripe with this technique that I have is the maintainability factor of the code decreases since you’d have to ensure that the people using your code can understand what the vectorization is doing. This means having solid documentation alongside the function is crucial and naming your variables sensibly is paramount for other’s understanding." } ]
XSD - Quick Guide
XML Schema Definition, commonly known as XSD, is a way to describe precisely the XML language. XSD checks the validity of structure and vocabulary of an XML document against the grammatical rules of the appropriate XML language. An XML document can be defined as βˆ’ Well-formed βˆ’ If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed. OR Well-formed βˆ’ If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed. OR Valid βˆ’ An XML document said to be valid when it is not only well-formed, but it also conforms to available XSD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties. Valid βˆ’ An XML document said to be valid when it is not only well-formed, but it also conforms to available XSD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties. The following diagram shows how XSD is used to structure XML documents βˆ’ Here is a simple XSD code. Take a look at it. <?xml version = "1.0"?> <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> targetNamespace = "http://www.tutorialspoint.com" xmlns = "http://www.tutorialspoint.com" elementFormDefault = "qualified"> <xs:element name = 'class'> <xs:complexType> <xs:sequence> <xs:element name = 'student' type = 'StudentType' minOccurs = '0' maxOccurs = 'unbounded' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name = "StudentType"> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> </xs:schema> Here is a list of some of the popular features of XSD βˆ’ XSDs can be extensible for future additions. XSD is richer and more powerful than DTD. XSD is written in XML. XSD supports data types. XSD supports namespaces. XSD is W3C recommendation. An XML XSD is kept in a separate document and then the document can be linked to an XML document to use it. The basic syntax of a XSD is as follows βˆ’ <?xml version = "1.0"?> <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> targetNamespace = "http://www.tutorialspoint.com" xmlns = "http://www.tutorialspoint.com" elementFormDefault = "qualified"> <xs:element name = 'class'> <xs:complexType> <xs:sequence> <xs:element name = 'student' type = 'StudentType' minOccurs = '0' maxOccurs = 'unbounded' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name = "StudentType"> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> </xs:schema> Schema is the root element of XSD and it is always required. <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> The above fragment specifies that elements and datatypes used in the schema are defined in http://www.w3.org/2001/XMLSchema namespace and these elements/data types should be prefixed with xs. It is always required. targetNamespace = "http://www.tutorialspoint.com" The above fragment specifies that elements used in this schema are defined in http://www.tutorialspoint.com namespace. It is optional. xmlns = "http://www.tutorialspoint.com" The above fragment specifies that default namespace is http://www.tutorialspoint.com. elementFormDefault = "qualified" The above fragment indicates that any elements declared in this schema must be namespace qualified before using them in any XML Document.It is optional. Take a look at the following Referencing Schema βˆ’ <?xml version = "1.0"?> <class xmlns = "http://www.tutorialspoint.com" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.tutorialspoint.com student.xsd"> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> xmlns = "http://www.tutorialspoint.com" The above fragment specifies default namespace declaration. This namespace is used by the schema validator check that all the elements are part of this namespace. It is optional. xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.tutorialspoint.com student.xsd"> After defining the XMLSchema-instance xsi, use schemaLocation attribute. This attribute has two values, namespace and location of XML Schema, to be used separated by a space. It is optional. We'll use Java based XSD validator to validate students.xml against the students.xsd. <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>Dinkar</firstname> <lastname>Kad</lastname> <nickname>Dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>Vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>Jasvir</firstname> <lastname>Singh</lastname> <nickname>Jazz</nickname> <marks>90</marks> </student> </class> <?xml version = "1.0"?> <xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"> <xs:element name = 'class'> <xs:complexType> <xs:sequence> <xs:element name = 'student' type = 'StudentType' minOccurs = '0' maxOccurs = 'unbounded' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name = "StudentType"> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> </xs:schema> import java.io.File; import java.io.IOException; import javax.xml.XMLConstants; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.SAXException; public class XSDValidator { public static void main(String[] args) { if(args.length !=2){ System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" ); } else { boolean isValid = validateXMLSchema(args[0],args[1]); if(isValid){ System.out.println(args[1] + " is valid against " + args[0]); } else { System.out.println(args[1] + " is not valid against " + args[0]); } } } public static boolean validateXMLSchema(String xsdPath, String xmlPath){ try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(new File(xsdPath)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(new File(xmlPath))); } catch (IOException e){ System.out.println("Exception: "+e.getMessage()); return false; } catch(SAXException e1){ System.out.println("SAX Exception: "+e1.getMessage()); return false; } return true; } } Copy the XSDValidator.java file to any location, say E: > java Copy the XSDValidator.java file to any location, say E: > java Copy the students.xml to same location E: > java Copy the students.xml to same location E: > java Copy the students.xsd to same location E: > java Copy the students.xsd to same location E: > java Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial E:\java\javac XSDValidator.java Execute XSDValidator with students.xsd and students.xml passed as argument. Execute XSDValidator with students.xsd and students.xml passed as argument. E:\java\java XSDValidator students.xsd students.xml You'll see the following result βˆ’ students.xml is valid against students.xsd In this chapter, we'll see Simple Types that XSD defines. Element Simple Element can contain only text. It can not contain any other element. Attribute Attribute is itself a type and is used in Complex Element. Restriction Restriction defines the acceptable values of an XML element. Complex Element is an XML element which can contain other elements and/or attributes. We can create a complex element in two ways βˆ’ Define a complex type and then create an element using the type attribute Define a complex type and then create an element using the type attribute Define a complex type directly by naming Define a complex type directly by naming <xs:complexType name = "StudentType"> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> <xs:element name = 'student' type = 'StudentType' /> <xs:element name = "student"> <xs:complexType> <xs:sequence> <xs:element name = "firstname" type = "xs:string"/> <xs:element name = "lastname" type = "xs:string"/> <xs:element name = "nickname" type = "xs:string"/> <xs:element name = "marks" type = "xs:positiveInteger"/> </xs:sequence> <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/> </xs:complexType> <xs:element> Following is the list of Complex Types that XSD supports. Empty Complex Empty complex type element can only have attributes but no contents. Elements Only Elements-Only complex type element can only contain elements Text Only Text-Only complex type element can only contain attribute and text. Mixed Mixed complex type element can contain element, attribute and text. Indicators Indicators controls the ways how elements are to be organized in an XML document. <any> The <any> element is used for elements which are not defined by schema <anyAttribute> The <anyAttribute> attribute is used for attribute which are not defined by schema. String data types are used to represent characters in the XML documents. The <xs:string> data type can take characters, line feeds, carriage returns, and tab characters. The XML processor does not replace line feeds, carriage returns, and tab characters in the content with space and keep them intact. For example, multiple spaces or tabs are preserved during display. Element declaration in xsd βˆ’ <xs:element name = "name" type = "xs:string"/> Element usage in xml βˆ’ <name>Dinkar</name> <name>Dinkar Kad</name> The <xs:token> data type is derived from <string> data type and can take characters, line feeds, carriage returns, and tab characters. XML processor will remove line feeds, tabs, carriage returns, leading and trailing spaces, and multiple spaces. Element declaration in xsd βˆ’ <xs:element name = "name" type = "xs:token"/> Element usage in xml βˆ’ <name>Dinkar</name> <name>Dinkar Kad</name> Following is the list of commonly used data types which are derived from <string> data type. ID Represents the ID attribute in XML and is used in schema attributes. IDREF Represents the IDREF attribute in XML and is used in schema attributes. language Represents a valid language id Name Represents a valid XML name NMTOKEN Represents a NMTOKEN attribute in XML and is used in schema attributes. normalizedString Represents a string that does not contain line feeds, carriage returns, or tabs. string Represents a string that can contain line feeds, carriage returns, or tabs. token Represents a string that does not contain line feeds, carriage returns, tabs, leading or trailing spaces, or multiple spaces Following types of restrictions can be used with String data types βˆ’ enumeration length maxLength minLength pattern whiteSpace Date and Time data types are used to represent date and time in the XML documents. The <xs:date> data type is used to represent date in YYYY-MM-DD format. YYYY βˆ’ represents year YYYY βˆ’ represents year MM βˆ’ represents month MM βˆ’ represents month DD βˆ’ represents day DD βˆ’ represents day Element declaration in XSD βˆ’ <xs:element name = "birthdate" type = "xs:date"/> Element usage in XML βˆ’ <birthdate>1980-03-23</birthdate> The <xs:time> data type is used to represent time in hh:mm:ss format. hh βˆ’ represents hours hh βˆ’ represents hours mm βˆ’ represents minutes mm βˆ’ represents minutes ss βˆ’ represents seconds ss βˆ’ represents seconds Element declaration in XSD βˆ’ <xs:element name = "startTime" type = "xs:time"/> Element usage in XML βˆ’ <startTime>10:20:15</startTime> The <xs:datetime> data type is used to represent date and time in YYYY-MM-DDThh:mm:ss format. YYYY βˆ’ represents year YYYY βˆ’ represents year MM βˆ’ represents month MM βˆ’ represents month DD βˆ’ represents day DD βˆ’ represents day T βˆ’ represents start of time section T βˆ’ represents start of time section hh βˆ’ represents hours hh βˆ’ represents hours mm βˆ’ represents minutes mm βˆ’ represents minutes ss βˆ’ represents seconds ss βˆ’ represents seconds Element declaration in XSD βˆ’ <xs:element name = "startTime" type = "xs:datetime"/> Element usage in XML βˆ’ <startTime>1980-03-23T10:20:15</startTime> The <xs:duration> data type is used to represent time interval in PnYnMnDTnHnMnS format. Each component is optional except P. P βˆ’ represents start of date section P βˆ’ represents start of date section nY βˆ’ represents year nY βˆ’ represents year nM βˆ’ represents month nM βˆ’ represents month nD βˆ’ represents day nD βˆ’ represents day T βˆ’ represents start of time section T βˆ’ represents start of time section nH βˆ’ represents hours nH βˆ’ represents hours nM βˆ’ represents minutes nM βˆ’ represents minutes nS βˆ’ represents seconds nS βˆ’ represents seconds Element declaration in XSD βˆ’ <xs:element name = "period" type = "xs:duration"/> Element usage in xml to represent period of 6 years, 3 months, 10 days and 15 hours. <period>P6Y3M10DT15H</period> Following is the list of commonly used date data types. date Represents a date value dateTime Represents a date and time value duration Represents a time interval gDay Represents a part of a date as the day (DD) gMonth Represents a part of a date as the month (MM) gMonthDay Represents a part of a date as the month and day (MM-DD) gYear Represents a part of a date as the year (YYYY) gYearMonth Represents a part of a date as the year and month (YYYY-MM) time Represents a time value Following types of restrictions can be used with Date data types βˆ’ enumeration maxExclusive maxInclusive minExclusive minInclusive pattern whiteSpace Numeric data types are used to represent numbers in XML documents. The <xs:decimal> data type is used to represent numeric values. It supports decimal numbers up to 18 digits. Element declaration in XSD βˆ’ <xs:element name = "score" type = "xs:decimal"/> Element usage in XML βˆ’ <score>9.12</score> The <xs:integer> data type is used to represent integer values. Element declaration in XSD βˆ’ <xs:element name = "score" type = "xs:integer"/> Element usage in XML βˆ’ <score>9</score> Following is the list of commonly used numeric data types. byte A signed 8 bit integer decimal A decimal value int A signed 32 bit integer integer An integer value long A signed 64 bit integer negativeInteger An integer having only negative values (..,-2,-1) nonNegativeInteger An integer having only non-negative values (0,1,2,..) nonPositiveInteger An integer having only non-positive values (..,-2,-1,0) positiveInteger An integer having only positive values (1,2,..) short A signed 16 bit integer unsignedLong An unsigned 64 bit integer unsignedInt An unsigned 32 bit integer unsignedShort An unsigned 16 bit integer unsignedByte An unsigned 8 bit integer Following types of restrictions can be used with Date data types βˆ’ enumeration fractionDigits maxExclusive maxInclusive minExclusive minInclusive pattern totalDigits whiteSpace XSD has a few other important data types, such as Boolean, binary, and anyURI. The <xs:boolean> data type is used to represent true, false, 1 (for true) or 0 (for false) value. Element declaration in XSD βˆ’ <xs:element name = "pass" type = "xs:boolean"/> Element usage in XML βˆ’ <pass>false</pass> The Binary data types are used to represent binary values. Two binary types are common in use. base64Binary βˆ’ represents base64 encoded binary data base64Binary βˆ’ represents base64 encoded binary data hexBinary βˆ’ represents hexadecimal encoded binary data hexBinary βˆ’ represents hexadecimal encoded binary data Element declaration in XSD βˆ’ <xs:element name = "blob" type = "xs:hexBinary"/> Element usage in XML βˆ’ <blob>9FEEF</blob> The <xs:anyURI> data type is used to represent URI. Element declaration in XSD βˆ’ <xs:attribute name = "resource" type = "xs:anyURI"/> Element usage in XML βˆ’ <image resource = "http://www.tutorialspoint.com/images/smiley.jpg" /> Following is the list of commonly used numeric data types. byte A signed 8 bit integer decimal A decimal value int A signed 32 bit integer integer An integer value long A signed 64 bit integer negativeInteger An integer having only negative values (..,-2,-1) nonNegativeInteger An integer having only non-negative values (0,1,2,..) nonPositiveInteger An integer having only non-positive values (..,-2,-1,0) positiveInteger An integer having only positive values (1,2,..) short A signed 16 bit integer unsignedLong An unsigned 64 bit integer unsignedInt An unsigned 32 bit integer unsignedShort An unsigned 16 bit integer unsignedByte An unsigned 8 bit integer Following types of restrictions can be used with Miscellaneous data types except on boolean data type βˆ’ enumeration length maxLength minLength pattern whiteSpace Print Add Notes Bookmark this page
[ { "code": null, "e": 1933, "s": 1704, "text": "XML Schema Definition, commonly known as XSD, is a way to describe precisely the XML language. XSD checks the validity of structure and vocabulary of an XML document against the grammatical rules of the appropriate XML language." }, { "code": null, "e": 1969, "s": 1933, "text": "An XML document can be defined as βˆ’" }, { "code": null, "e": 2194, "s": 1969, "text": "Well-formed βˆ’ If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed.\nOR\n" }, { "code": null, "e": 2415, "s": 2194, "text": "Well-formed βˆ’ If the XML document adheres to all the general XML rules such as tags must be properly nested, opening and closing tags must be balanced, and empty tags must end with '/>', then it is called as well-formed." }, { "code": null, "e": 2418, "s": 2415, "text": "OR" }, { "code": null, "e": 2673, "s": 2418, "text": "Valid βˆ’ An XML document said to be valid when it is not only well-formed, but it also conforms to available XSD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties." }, { "code": null, "e": 2928, "s": 2673, "text": "Valid βˆ’ An XML document said to be valid when it is not only well-formed, but it also conforms to available XSD that specifies which tags it uses, what attributes those tags can contain, and which tags can occur inside other tags, among other properties." }, { "code": null, "e": 3001, "s": 2928, "text": "The following diagram shows how XSD is used to structure XML documents βˆ’" }, { "code": null, "e": 3047, "s": 3001, "text": "Here is a simple XSD code. Take a look at it." }, { "code": null, "e": 3962, "s": 3047, "text": "<?xml version = \"1.0\"?>\n\n<xs:schema xmlns:xs = \"http://www.w3.org/2001/XMLSchema\">\n targetNamespace = \"http://www.tutorialspoint.com\" \n xmlns = \"http://www.tutorialspoint.com\"\n elementFormDefault = \"qualified\">\n\n <xs:element name = 'class'>\n <xs:complexType>\n <xs:sequence>\n <xs:element name = 'student' type = 'StudentType' minOccurs = '0' \n maxOccurs = 'unbounded' />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n <xs:complexType name = \"StudentType\">\n <xs:sequence>\n <xs:element name = \"firstname\" type = \"xs:string\"/>\n <xs:element name = \"lastname\" type = \"xs:string\"/>\n <xs:element name = \"nickname\" type = \"xs:string\"/>\n <xs:element name = \"marks\" type = \"xs:positiveInteger\"/>\n </xs:sequence>\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>\n </xs:complexType>\n \n</xs:schema>" }, { "code": null, "e": 4018, "s": 3962, "text": "Here is a list of some of the popular features of XSD βˆ’" }, { "code": null, "e": 4063, "s": 4018, "text": "XSDs can be extensible for future additions." }, { "code": null, "e": 4105, "s": 4063, "text": "XSD is richer and more powerful than DTD." }, { "code": null, "e": 4128, "s": 4105, "text": "XSD is written in XML." }, { "code": null, "e": 4153, "s": 4128, "text": "XSD supports data types." }, { "code": null, "e": 4178, "s": 4153, "text": "XSD supports namespaces." }, { "code": null, "e": 4205, "s": 4178, "text": "XSD is W3C recommendation." }, { "code": null, "e": 4313, "s": 4205, "text": "An XML XSD is kept in a separate document and then the document can be linked to an XML document to use it." }, { "code": null, "e": 4355, "s": 4313, "text": "The basic syntax of a XSD is as follows βˆ’" }, { "code": null, "e": 5269, "s": 4355, "text": "<?xml version = \"1.0\"?>\n\n<xs:schema xmlns:xs = \"http://www.w3.org/2001/XMLSchema\">\n targetNamespace = \"http://www.tutorialspoint.com\"\n xmlns = \"http://www.tutorialspoint.com\" elementFormDefault = \"qualified\">\n \n <xs:element name = 'class'>\n <xs:complexType>\n <xs:sequence>\n <xs:element name = 'student' type = 'StudentType' minOccurs = '0' \n maxOccurs = 'unbounded' />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n <xs:complexType name = \"StudentType\">\n <xs:sequence>\n <xs:element name = \"firstname\" type = \"xs:string\"/>\n <xs:element name = \"lastname\" type = \"xs:string\"/>\n <xs:element name = \"nickname\" type = \"xs:string\"/>\n <xs:element name = \"marks\" type = \"xs:positiveInteger\"/>\n </xs:sequence>\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>\n </xs:complexType>\n \n</xs:schema>" }, { "code": null, "e": 5330, "s": 5269, "text": "Schema is the root element of XSD and it is always required." }, { "code": null, "e": 5389, "s": 5330, "text": "<xs:schema xmlns:xs = \"http://www.w3.org/2001/XMLSchema\">\n" }, { "code": null, "e": 5604, "s": 5389, "text": "The above fragment specifies that elements and datatypes used in the schema are defined in http://www.w3.org/2001/XMLSchema namespace and these elements/data types should be prefixed with xs. It is always required." }, { "code": null, "e": 5655, "s": 5604, "text": "targetNamespace = \"http://www.tutorialspoint.com\"\n" }, { "code": null, "e": 5790, "s": 5655, "text": "The above fragment specifies that elements used in this schema are defined in http://www.tutorialspoint.com namespace. It is optional." }, { "code": null, "e": 5831, "s": 5790, "text": "xmlns = \"http://www.tutorialspoint.com\"\n" }, { "code": null, "e": 5917, "s": 5831, "text": "The above fragment specifies that default namespace is http://www.tutorialspoint.com." }, { "code": null, "e": 5951, "s": 5917, "text": "elementFormDefault = \"qualified\"\n" }, { "code": null, "e": 6104, "s": 5951, "text": "The above fragment indicates that any elements declared in this schema must be namespace qualified before using them in any XML Document.It is optional." }, { "code": null, "e": 6154, "s": 6104, "text": "Take a look at the following Referencing Schema βˆ’" }, { "code": null, "e": 6889, "s": 6154, "text": "<?xml version = \"1.0\"?>\n\n<class xmlns = \"http://www.tutorialspoint.com\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.tutorialspoint.com student.xsd\"> \n \n <student rollno = \"393\"> \n <firstname>Dinkar</firstname>\n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\t \n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 6930, "s": 6889, "text": "xmlns = \"http://www.tutorialspoint.com\"\n" }, { "code": null, "e": 7109, "s": 6930, "text": "The above fragment specifies default namespace declaration. This namespace is used by the schema validator check that all the elements are part of this namespace. It is optional." }, { "code": null, "e": 7234, "s": 7109, "text": "xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:schemaLocation = \"http://www.tutorialspoint.com student.xsd\"> \n" }, { "code": null, "e": 7425, "s": 7234, "text": "After defining the XMLSchema-instance xsi, use schemaLocation attribute. This attribute has two values, namespace and location of XML Schema, to be used separated by a space. It is optional." }, { "code": null, "e": 7511, "s": 7425, "text": "We'll use Java based XSD validator to validate students.xml against the students.xsd." }, { "code": null, "e": 8077, "s": 7511, "text": "<?xml version = \"1.0\"?>\n\n<class> \n <student rollno = \"393\">\n <firstname>Dinkar</firstname> \n <lastname>Kad</lastname>\n <nickname>Dinkar</nickname>\n <marks>85</marks>\t \n </student>\n \n <student rollno = \"493\">\t \n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>Vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\"> \n <firstname>Jasvir</firstname>\n <lastname>Singh</lastname>\n <nickname>Jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 8859, "s": 8077, "text": "<?xml version = \"1.0\"?>\n\n<xs:schema xmlns:xs = \"http://www.w3.org/2001/XMLSchema\">\n <xs:element name = 'class'>\n <xs:complexType>\n <xs:sequence>\n <xs:element name = 'student' type = 'StudentType' minOccurs = '0' \n maxOccurs = 'unbounded' />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n <xs:complexType name = \"StudentType\">\n <xs:sequence>\n <xs:element name = \"firstname\" type = \"xs:string\"/>\n <xs:element name = \"lastname\" type = \"xs:string\"/>\n <xs:element name = \"nickname\" type = \"xs:string\"/>\n <xs:element name = \"marks\" type = \"xs:positiveInteger\"/>\n </xs:sequence>\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>\n </xs:complexType>\t\t\t \n</xs:schema>" }, { "code": null, "e": 10292, "s": 8859, "text": "import java.io.File;\nimport java.io.IOException;\n\nimport javax.xml.XMLConstants;\nimport javax.xml.transform.stream.StreamSource;\n\nimport javax.xml.validation.Schema;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.validation.Validator;\n\nimport org.xml.sax.SAXException;\n\npublic class XSDValidator {\n public static void main(String[] args) {\n if(args.length !=2){\n System.out.println(\"Usage : XSDValidator <file-name.xsd> <file-name.xml>\" );\n } else {\n boolean isValid = validateXMLSchema(args[0],args[1]);\n \n if(isValid){\n System.out.println(args[1] + \" is valid against \" + args[0]);\n } else {\n System.out.println(args[1] + \" is not valid against \" + args[0]);\n }\n }\n }\n \n public static boolean validateXMLSchema(String xsdPath, String xmlPath){\n try {\n SchemaFactory factory =\n SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n Schema schema = factory.newSchema(new File(xsdPath));\n Validator validator = schema.newValidator();\n validator.validate(new StreamSource(new File(xmlPath)));\n } catch (IOException e){\n System.out.println(\"Exception: \"+e.getMessage());\n return false;\n } catch(SAXException e1){\n System.out.println(\"SAX Exception: \"+e1.getMessage());\n return false;\n }\n\t\t\n return true;\n }\n}" }, { "code": null, "e": 10355, "s": 10292, "text": "Copy the XSDValidator.java file to any location, say E: > java" }, { "code": null, "e": 10418, "s": 10355, "text": "Copy the XSDValidator.java file to any location, say E: > java" }, { "code": null, "e": 10468, "s": 10418, "text": "Copy the students.xml to same location E: > java" }, { "code": null, "e": 10518, "s": 10468, "text": "Copy the students.xml to same location E: > java" }, { "code": null, "e": 10568, "s": 10518, "text": "Copy the students.xsd to same location E: > java" }, { "code": null, "e": 10618, "s": 10568, "text": "Copy the students.xsd to same location E: > java" }, { "code": null, "e": 10802, "s": 10618, "text": "Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial" }, { "code": null, "e": 10986, "s": 10802, "text": "Compile XSDValidator.java using console. Make sure you have JDK 1.5 onwards installed on your machine and classpaths are configured. For details on how to use JAVA, see JAVA Tutorial" }, { "code": null, "e": 11019, "s": 10986, "text": "E:\\java\\javac XSDValidator.java\n" }, { "code": null, "e": 11095, "s": 11019, "text": "Execute XSDValidator with students.xsd and students.xml passed as argument." }, { "code": null, "e": 11171, "s": 11095, "text": "Execute XSDValidator with students.xsd and students.xml passed as argument." }, { "code": null, "e": 11224, "s": 11171, "text": "E:\\java\\java XSDValidator students.xsd students.xml\n" }, { "code": null, "e": 11258, "s": 11224, "text": "You'll see the following result βˆ’" }, { "code": null, "e": 11302, "s": 11258, "text": "students.xml is valid against students.xsd\n" }, { "code": null, "e": 11360, "s": 11302, "text": "In this chapter, we'll see Simple Types that XSD defines." }, { "code": null, "e": 11368, "s": 11360, "text": "Element" }, { "code": null, "e": 11444, "s": 11368, "text": "Simple Element can contain only text. It can not contain any other element." }, { "code": null, "e": 11454, "s": 11444, "text": "Attribute" }, { "code": null, "e": 11513, "s": 11454, "text": "Attribute is itself a type and is used in Complex Element." }, { "code": null, "e": 11525, "s": 11513, "text": "Restriction" }, { "code": null, "e": 11586, "s": 11525, "text": "Restriction defines the acceptable values of an XML element." }, { "code": null, "e": 11718, "s": 11586, "text": "Complex Element is an XML element which can contain other elements and/or attributes. We can create a complex element in two ways βˆ’" }, { "code": null, "e": 11792, "s": 11718, "text": "Define a complex type and then create an element using the type attribute" }, { "code": null, "e": 11866, "s": 11792, "text": "Define a complex type and then create an element using the type attribute" }, { "code": null, "e": 11907, "s": 11866, "text": "Define a complex type directly by naming" }, { "code": null, "e": 11948, "s": 11907, "text": "Define a complex type directly by naming" }, { "code": null, "e": 12395, "s": 11948, "text": "<xs:complexType name = \"StudentType\">\n <xs:sequence>\n <xs:element name = \"firstname\" type = \"xs:string\"/>\n <xs:element name = \"lastname\" type = \"xs:string\"/>\n <xs:element name = \"nickname\" type = \"xs:string\"/>\n <xs:element name = \"marks\" type = \"xs:positiveInteger\"/>\n </xs:sequence>\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>\n</xs:complexType>\n\n<xs:element name = 'student' type = 'StudentType' />\t\t\t " }, { "code": null, "e": 12833, "s": 12395, "text": "<xs:element name = \"student\">\n <xs:complexType> \n <xs:sequence>\n <xs:element name = \"firstname\" type = \"xs:string\"/>\n <xs:element name = \"lastname\" type = \"xs:string\"/>\n <xs:element name = \"nickname\" type = \"xs:string\"/>\n <xs:element name = \"marks\" type = \"xs:positiveInteger\"/>\n </xs:sequence>\n <xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>\n </xs:complexType>\n<xs:element>" }, { "code": null, "e": 12891, "s": 12833, "text": "Following is the list of Complex Types that XSD supports." }, { "code": null, "e": 12897, "s": 12891, "text": "Empty" }, { "code": null, "e": 12974, "s": 12897, "text": "Complex Empty complex type element can only have attributes but no contents." }, { "code": null, "e": 12988, "s": 12974, "text": "Elements Only" }, { "code": null, "e": 13049, "s": 12988, "text": "Elements-Only complex type element can only contain elements" }, { "code": null, "e": 13059, "s": 13049, "text": "Text Only" }, { "code": null, "e": 13127, "s": 13059, "text": "Text-Only complex type element can only contain attribute and text." }, { "code": null, "e": 13133, "s": 13127, "text": "Mixed" }, { "code": null, "e": 13201, "s": 13133, "text": "Mixed complex type element can contain element, attribute and text." }, { "code": null, "e": 13212, "s": 13201, "text": "Indicators" }, { "code": null, "e": 13294, "s": 13212, "text": "Indicators controls the ways how elements are to be organized in an XML document." }, { "code": null, "e": 13300, "s": 13294, "text": "<any>" }, { "code": null, "e": 13371, "s": 13300, "text": "The <any> element is used for elements which are not defined by schema" }, { "code": null, "e": 13386, "s": 13371, "text": "<anyAttribute>" }, { "code": null, "e": 13470, "s": 13386, "text": "The <anyAttribute> attribute is used for attribute which are not defined by schema." }, { "code": null, "e": 13543, "s": 13470, "text": "String data types are used to represent characters in the XML documents." }, { "code": null, "e": 13839, "s": 13543, "text": "The <xs:string> data type can take characters, line feeds, carriage returns, and tab characters. The XML processor does not replace line feeds, carriage returns, and tab characters in the content with space and keep them intact. For example, multiple spaces or tabs are preserved during display." }, { "code": null, "e": 13868, "s": 13839, "text": "Element declaration in xsd βˆ’" }, { "code": null, "e": 13916, "s": 13868, "text": "<xs:element name = \"name\" type = \"xs:string\"/>\n" }, { "code": null, "e": 13939, "s": 13916, "text": "Element usage in xml βˆ’" }, { "code": null, "e": 13987, "s": 13939, "text": "<name>Dinkar</name>\n<name>Dinkar Kad</name>\n" }, { "code": null, "e": 14234, "s": 13987, "text": "The <xs:token> data type is derived from <string> data type and can take characters, line feeds, carriage returns, and tab characters. XML processor will remove line feeds, tabs, carriage returns, leading and trailing spaces, and multiple spaces." }, { "code": null, "e": 14263, "s": 14234, "text": "Element declaration in xsd βˆ’" }, { "code": null, "e": 14310, "s": 14263, "text": "<xs:element name = \"name\" type = \"xs:token\"/>\n" }, { "code": null, "e": 14333, "s": 14310, "text": "Element usage in xml βˆ’" }, { "code": null, "e": 14381, "s": 14333, "text": "<name>Dinkar</name>\n<name>Dinkar Kad</name>\n" }, { "code": null, "e": 14474, "s": 14381, "text": "Following is the list of commonly used data types which are derived from <string> data type." }, { "code": null, "e": 14477, "s": 14474, "text": "ID" }, { "code": null, "e": 14546, "s": 14477, "text": "Represents the ID attribute in XML and is used in schema attributes." }, { "code": null, "e": 14552, "s": 14546, "text": "IDREF" }, { "code": null, "e": 14624, "s": 14552, "text": "Represents the IDREF attribute in XML and is used in schema attributes." }, { "code": null, "e": 14633, "s": 14624, "text": "language" }, { "code": null, "e": 14664, "s": 14633, "text": "Represents a valid language id" }, { "code": null, "e": 14669, "s": 14664, "text": "Name" }, { "code": null, "e": 14697, "s": 14669, "text": "Represents a valid XML name" }, { "code": null, "e": 14705, "s": 14697, "text": "NMTOKEN" }, { "code": null, "e": 14777, "s": 14705, "text": "Represents a NMTOKEN attribute in XML and is used in schema attributes." }, { "code": null, "e": 14794, "s": 14777, "text": "normalizedString" }, { "code": null, "e": 14875, "s": 14794, "text": "Represents a string that does not contain line feeds, carriage returns, or tabs." }, { "code": null, "e": 14882, "s": 14875, "text": "string" }, { "code": null, "e": 14958, "s": 14882, "text": "Represents a string that can contain line feeds, carriage returns, or tabs." }, { "code": null, "e": 14964, "s": 14958, "text": "token" }, { "code": null, "e": 15089, "s": 14964, "text": "Represents a string that does not contain line feeds, carriage returns, tabs, leading or trailing spaces, or multiple spaces" }, { "code": null, "e": 15158, "s": 15089, "text": "Following types of restrictions can be used with String data types βˆ’" }, { "code": null, "e": 15170, "s": 15158, "text": "enumeration" }, { "code": null, "e": 15177, "s": 15170, "text": "length" }, { "code": null, "e": 15187, "s": 15177, "text": "maxLength" }, { "code": null, "e": 15197, "s": 15187, "text": "minLength" }, { "code": null, "e": 15205, "s": 15197, "text": "pattern" }, { "code": null, "e": 15216, "s": 15205, "text": "whiteSpace" }, { "code": null, "e": 15299, "s": 15216, "text": "Date and Time data types are used to represent date and time in the XML documents." }, { "code": null, "e": 15371, "s": 15299, "text": "The <xs:date> data type is used to represent date in YYYY-MM-DD format." }, { "code": null, "e": 15394, "s": 15371, "text": "YYYY βˆ’ represents year" }, { "code": null, "e": 15417, "s": 15394, "text": "YYYY βˆ’ represents year" }, { "code": null, "e": 15439, "s": 15417, "text": "MM βˆ’ represents month" }, { "code": null, "e": 15461, "s": 15439, "text": "MM βˆ’ represents month" }, { "code": null, "e": 15481, "s": 15461, "text": "DD βˆ’ represents day" }, { "code": null, "e": 15501, "s": 15481, "text": "DD βˆ’ represents day" }, { "code": null, "e": 15530, "s": 15501, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 15581, "s": 15530, "text": "<xs:element name = \"birthdate\" type = \"xs:date\"/>\n" }, { "code": null, "e": 15604, "s": 15581, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 15639, "s": 15604, "text": "<birthdate>1980-03-23</birthdate>\n" }, { "code": null, "e": 15709, "s": 15639, "text": "The <xs:time> data type is used to represent time in hh:mm:ss format." }, { "code": null, "e": 15731, "s": 15709, "text": "hh βˆ’ represents hours" }, { "code": null, "e": 15753, "s": 15731, "text": "hh βˆ’ represents hours" }, { "code": null, "e": 15777, "s": 15753, "text": "mm βˆ’ represents minutes" }, { "code": null, "e": 15801, "s": 15777, "text": "mm βˆ’ represents minutes" }, { "code": null, "e": 15825, "s": 15801, "text": "ss βˆ’ represents seconds" }, { "code": null, "e": 15849, "s": 15825, "text": "ss βˆ’ represents seconds" }, { "code": null, "e": 15878, "s": 15849, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 15929, "s": 15878, "text": "<xs:element name = \"startTime\" type = \"xs:time\"/>\n" }, { "code": null, "e": 15952, "s": 15929, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 15985, "s": 15952, "text": "<startTime>10:20:15</startTime>\n" }, { "code": null, "e": 16079, "s": 15985, "text": "The <xs:datetime> data type is used to represent date and time in YYYY-MM-DDThh:mm:ss format." }, { "code": null, "e": 16102, "s": 16079, "text": "YYYY βˆ’ represents year" }, { "code": null, "e": 16125, "s": 16102, "text": "YYYY βˆ’ represents year" }, { "code": null, "e": 16147, "s": 16125, "text": "MM βˆ’ represents month" }, { "code": null, "e": 16169, "s": 16147, "text": "MM βˆ’ represents month" }, { "code": null, "e": 16189, "s": 16169, "text": "DD βˆ’ represents day" }, { "code": null, "e": 16209, "s": 16189, "text": "DD βˆ’ represents day" }, { "code": null, "e": 16246, "s": 16209, "text": "T βˆ’ represents start of time section" }, { "code": null, "e": 16283, "s": 16246, "text": "T βˆ’ represents start of time section" }, { "code": null, "e": 16305, "s": 16283, "text": "hh βˆ’ represents hours" }, { "code": null, "e": 16327, "s": 16305, "text": "hh βˆ’ represents hours" }, { "code": null, "e": 16351, "s": 16327, "text": "mm βˆ’ represents minutes" }, { "code": null, "e": 16375, "s": 16351, "text": "mm βˆ’ represents minutes" }, { "code": null, "e": 16399, "s": 16375, "text": "ss βˆ’ represents seconds" }, { "code": null, "e": 16423, "s": 16399, "text": "ss βˆ’ represents seconds" }, { "code": null, "e": 16452, "s": 16423, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 16507, "s": 16452, "text": "<xs:element name = \"startTime\" type = \"xs:datetime\"/>\n" }, { "code": null, "e": 16530, "s": 16507, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 16574, "s": 16530, "text": "<startTime>1980-03-23T10:20:15</startTime>\n" }, { "code": null, "e": 16700, "s": 16574, "text": "The <xs:duration> data type is used to represent time interval in PnYnMnDTnHnMnS format. Each component is optional except P." }, { "code": null, "e": 16737, "s": 16700, "text": "P βˆ’ represents start of date section" }, { "code": null, "e": 16774, "s": 16737, "text": "P βˆ’ represents start of date section" }, { "code": null, "e": 16795, "s": 16774, "text": "nY βˆ’ represents year" }, { "code": null, "e": 16816, "s": 16795, "text": "nY βˆ’ represents year" }, { "code": null, "e": 16838, "s": 16816, "text": "nM βˆ’ represents month" }, { "code": null, "e": 16860, "s": 16838, "text": "nM βˆ’ represents month" }, { "code": null, "e": 16880, "s": 16860, "text": "nD βˆ’ represents day" }, { "code": null, "e": 16900, "s": 16880, "text": "nD βˆ’ represents day" }, { "code": null, "e": 16937, "s": 16900, "text": "T βˆ’ represents start of time section" }, { "code": null, "e": 16974, "s": 16937, "text": "T βˆ’ represents start of time section" }, { "code": null, "e": 16996, "s": 16974, "text": "nH βˆ’ represents hours" }, { "code": null, "e": 17018, "s": 16996, "text": "nH βˆ’ represents hours" }, { "code": null, "e": 17042, "s": 17018, "text": "nM βˆ’ represents minutes" }, { "code": null, "e": 17066, "s": 17042, "text": "nM βˆ’ represents minutes" }, { "code": null, "e": 17090, "s": 17066, "text": "nS βˆ’ represents seconds" }, { "code": null, "e": 17114, "s": 17090, "text": "nS βˆ’ represents seconds" }, { "code": null, "e": 17143, "s": 17114, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 17195, "s": 17143, "text": "<xs:element name = \"period\" type = \"xs:duration\"/>\n" }, { "code": null, "e": 17280, "s": 17195, "text": "Element usage in xml to represent period of 6 years, 3 months, 10 days and 15 hours." }, { "code": null, "e": 17311, "s": 17280, "text": "<period>P6Y3M10DT15H</period>\n" }, { "code": null, "e": 17367, "s": 17311, "text": "Following is the list of commonly used date data types." }, { "code": null, "e": 17372, "s": 17367, "text": "date" }, { "code": null, "e": 17396, "s": 17372, "text": "Represents a date value" }, { "code": null, "e": 17405, "s": 17396, "text": "dateTime" }, { "code": null, "e": 17438, "s": 17405, "text": "Represents a date and time value" }, { "code": null, "e": 17447, "s": 17438, "text": "duration" }, { "code": null, "e": 17474, "s": 17447, "text": "Represents a time interval" }, { "code": null, "e": 17479, "s": 17474, "text": "gDay" }, { "code": null, "e": 17523, "s": 17479, "text": "Represents a part of a date as the day (DD)" }, { "code": null, "e": 17530, "s": 17523, "text": "gMonth" }, { "code": null, "e": 17576, "s": 17530, "text": "Represents a part of a date as the month (MM)" }, { "code": null, "e": 17586, "s": 17576, "text": "gMonthDay" }, { "code": null, "e": 17643, "s": 17586, "text": "Represents a part of a date as the month and day (MM-DD)" }, { "code": null, "e": 17649, "s": 17643, "text": "gYear" }, { "code": null, "e": 17696, "s": 17649, "text": "Represents a part of a date as the year (YYYY)" }, { "code": null, "e": 17707, "s": 17696, "text": "gYearMonth" }, { "code": null, "e": 17767, "s": 17707, "text": "Represents a part of a date as the year and month (YYYY-MM)" }, { "code": null, "e": 17772, "s": 17767, "text": "time" }, { "code": null, "e": 17796, "s": 17772, "text": "Represents a time value" }, { "code": null, "e": 17863, "s": 17796, "text": "Following types of restrictions can be used with Date data types βˆ’" }, { "code": null, "e": 17875, "s": 17863, "text": "enumeration" }, { "code": null, "e": 17888, "s": 17875, "text": "maxExclusive" }, { "code": null, "e": 17901, "s": 17888, "text": "maxInclusive" }, { "code": null, "e": 17914, "s": 17901, "text": "minExclusive" }, { "code": null, "e": 17927, "s": 17914, "text": "minInclusive" }, { "code": null, "e": 17935, "s": 17927, "text": "pattern" }, { "code": null, "e": 17946, "s": 17935, "text": "whiteSpace" }, { "code": null, "e": 18013, "s": 17946, "text": "Numeric data types are used to represent numbers in XML documents." }, { "code": null, "e": 18122, "s": 18013, "text": "The <xs:decimal> data type is used to represent numeric values. It supports decimal numbers up to 18 digits." }, { "code": null, "e": 18151, "s": 18122, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 18201, "s": 18151, "text": "<xs:element name = \"score\" type = \"xs:decimal\"/>\n" }, { "code": null, "e": 18224, "s": 18201, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 18245, "s": 18224, "text": "<score>9.12</score>\n" }, { "code": null, "e": 18309, "s": 18245, "text": "The <xs:integer> data type is used to represent integer values." }, { "code": null, "e": 18338, "s": 18309, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 18388, "s": 18338, "text": "<xs:element name = \"score\" type = \"xs:integer\"/>\n" }, { "code": null, "e": 18411, "s": 18388, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 18429, "s": 18411, "text": "<score>9</score>\n" }, { "code": null, "e": 18488, "s": 18429, "text": "Following is the list of commonly used numeric data types." }, { "code": null, "e": 18493, "s": 18488, "text": "byte" }, { "code": null, "e": 18516, "s": 18493, "text": "A signed 8 bit integer" }, { "code": null, "e": 18524, "s": 18516, "text": "decimal" }, { "code": null, "e": 18540, "s": 18524, "text": "A decimal value" }, { "code": null, "e": 18544, "s": 18540, "text": "int" }, { "code": null, "e": 18568, "s": 18544, "text": "A signed 32 bit integer" }, { "code": null, "e": 18576, "s": 18568, "text": "integer" }, { "code": null, "e": 18593, "s": 18576, "text": "An integer value" }, { "code": null, "e": 18598, "s": 18593, "text": "long" }, { "code": null, "e": 18622, "s": 18598, "text": "A signed 64 bit integer" }, { "code": null, "e": 18638, "s": 18622, "text": "negativeInteger" }, { "code": null, "e": 18688, "s": 18638, "text": "An integer having only negative values (..,-2,-1)" }, { "code": null, "e": 18707, "s": 18688, "text": "nonNegativeInteger" }, { "code": null, "e": 18761, "s": 18707, "text": "An integer having only non-negative values (0,1,2,..)" }, { "code": null, "e": 18780, "s": 18761, "text": "nonPositiveInteger" }, { "code": null, "e": 18836, "s": 18780, "text": "An integer having only non-positive values (..,-2,-1,0)" }, { "code": null, "e": 18852, "s": 18836, "text": "positiveInteger" }, { "code": null, "e": 18900, "s": 18852, "text": "An integer having only positive values (1,2,..)" }, { "code": null, "e": 18906, "s": 18900, "text": "short" }, { "code": null, "e": 18930, "s": 18906, "text": "A signed 16 bit integer" }, { "code": null, "e": 18943, "s": 18930, "text": "unsignedLong" }, { "code": null, "e": 18970, "s": 18943, "text": "An unsigned 64 bit integer" }, { "code": null, "e": 18982, "s": 18970, "text": "unsignedInt" }, { "code": null, "e": 19009, "s": 18982, "text": "An unsigned 32 bit integer" }, { "code": null, "e": 19023, "s": 19009, "text": "unsignedShort" }, { "code": null, "e": 19050, "s": 19023, "text": "An unsigned 16 bit integer" }, { "code": null, "e": 19063, "s": 19050, "text": "unsignedByte" }, { "code": null, "e": 19089, "s": 19063, "text": "An unsigned 8 bit integer" }, { "code": null, "e": 19156, "s": 19089, "text": "Following types of restrictions can be used with Date data types βˆ’" }, { "code": null, "e": 19168, "s": 19156, "text": "enumeration" }, { "code": null, "e": 19183, "s": 19168, "text": "fractionDigits" }, { "code": null, "e": 19196, "s": 19183, "text": "maxExclusive" }, { "code": null, "e": 19209, "s": 19196, "text": "maxInclusive" }, { "code": null, "e": 19222, "s": 19209, "text": "minExclusive" }, { "code": null, "e": 19235, "s": 19222, "text": "minInclusive" }, { "code": null, "e": 19243, "s": 19235, "text": "pattern" }, { "code": null, "e": 19255, "s": 19243, "text": "totalDigits" }, { "code": null, "e": 19266, "s": 19255, "text": "whiteSpace" }, { "code": null, "e": 19345, "s": 19266, "text": "XSD has a few other important data types, such as Boolean, binary, and anyURI." }, { "code": null, "e": 19443, "s": 19345, "text": "The <xs:boolean> data type is used to represent true, false, 1 (for true) or 0 (for false) value." }, { "code": null, "e": 19472, "s": 19443, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 19521, "s": 19472, "text": "<xs:element name = \"pass\" type = \"xs:boolean\"/>\n" }, { "code": null, "e": 19544, "s": 19521, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 19564, "s": 19544, "text": "<pass>false</pass>\n" }, { "code": null, "e": 19659, "s": 19564, "text": "The Binary data types are used to represent binary values. Two binary types are common in use." }, { "code": null, "e": 19712, "s": 19659, "text": "base64Binary βˆ’ represents base64 encoded binary data" }, { "code": null, "e": 19765, "s": 19712, "text": "base64Binary βˆ’ represents base64 encoded binary data" }, { "code": null, "e": 19821, "s": 19765, "text": "hexBinary βˆ’ represents hexadecimal encoded binary data" }, { "code": null, "e": 19877, "s": 19821, "text": "hexBinary βˆ’ represents hexadecimal encoded binary data" }, { "code": null, "e": 19906, "s": 19877, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 19957, "s": 19906, "text": "<xs:element name = \"blob\" type = \"xs:hexBinary\"/>\n" }, { "code": null, "e": 19980, "s": 19957, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 20000, "s": 19980, "text": "<blob>9FEEF</blob>\n" }, { "code": null, "e": 20053, "s": 20000, "text": "The <xs:anyURI> data type is used to represent URI. " }, { "code": null, "e": 20082, "s": 20053, "text": "Element declaration in XSD βˆ’" }, { "code": null, "e": 20136, "s": 20082, "text": "<xs:attribute name = \"resource\" type = \"xs:anyURI\"/>\n" }, { "code": null, "e": 20159, "s": 20136, "text": "Element usage in XML βˆ’" }, { "code": null, "e": 20231, "s": 20159, "text": "<image resource = \"http://www.tutorialspoint.com/images/smiley.jpg\" />\n" }, { "code": null, "e": 20290, "s": 20231, "text": "Following is the list of commonly used numeric data types." }, { "code": null, "e": 20295, "s": 20290, "text": "byte" }, { "code": null, "e": 20318, "s": 20295, "text": "A signed 8 bit integer" }, { "code": null, "e": 20326, "s": 20318, "text": "decimal" }, { "code": null, "e": 20342, "s": 20326, "text": "A decimal value" }, { "code": null, "e": 20346, "s": 20342, "text": "int" }, { "code": null, "e": 20370, "s": 20346, "text": "A signed 32 bit integer" }, { "code": null, "e": 20378, "s": 20370, "text": "integer" }, { "code": null, "e": 20395, "s": 20378, "text": "An integer value" }, { "code": null, "e": 20400, "s": 20395, "text": "long" }, { "code": null, "e": 20424, "s": 20400, "text": "A signed 64 bit integer" }, { "code": null, "e": 20440, "s": 20424, "text": "negativeInteger" }, { "code": null, "e": 20490, "s": 20440, "text": "An integer having only negative values (..,-2,-1)" }, { "code": null, "e": 20509, "s": 20490, "text": "nonNegativeInteger" }, { "code": null, "e": 20563, "s": 20509, "text": "An integer having only non-negative values (0,1,2,..)" }, { "code": null, "e": 20582, "s": 20563, "text": "nonPositiveInteger" }, { "code": null, "e": 20638, "s": 20582, "text": "An integer having only non-positive values (..,-2,-1,0)" }, { "code": null, "e": 20654, "s": 20638, "text": "positiveInteger" }, { "code": null, "e": 20702, "s": 20654, "text": "An integer having only positive values (1,2,..)" }, { "code": null, "e": 20708, "s": 20702, "text": "short" }, { "code": null, "e": 20732, "s": 20708, "text": "A signed 16 bit integer" }, { "code": null, "e": 20745, "s": 20732, "text": "unsignedLong" }, { "code": null, "e": 20772, "s": 20745, "text": "An unsigned 64 bit integer" }, { "code": null, "e": 20784, "s": 20772, "text": "unsignedInt" }, { "code": null, "e": 20811, "s": 20784, "text": "An unsigned 32 bit integer" }, { "code": null, "e": 20825, "s": 20811, "text": "unsignedShort" }, { "code": null, "e": 20852, "s": 20825, "text": "An unsigned 16 bit integer" }, { "code": null, "e": 20865, "s": 20852, "text": "unsignedByte" }, { "code": null, "e": 20891, "s": 20865, "text": "An unsigned 8 bit integer" }, { "code": null, "e": 20995, "s": 20891, "text": "Following types of restrictions can be used with Miscellaneous data types except on boolean data type βˆ’" }, { "code": null, "e": 21007, "s": 20995, "text": "enumeration" }, { "code": null, "e": 21014, "s": 21007, "text": "length" }, { "code": null, "e": 21024, "s": 21014, "text": "maxLength" }, { "code": null, "e": 21034, "s": 21024, "text": "minLength" }, { "code": null, "e": 21042, "s": 21034, "text": "pattern" }, { "code": null, "e": 21053, "s": 21042, "text": "whiteSpace" }, { "code": null, "e": 21060, "s": 21053, "text": " Print" }, { "code": null, "e": 21071, "s": 21060, "text": " Add Notes" } ]
Traffic Intersection Simulation using Pygame, Part 2 | by Mihir Gandhi | Towards Data Science
In this article, we will be adding some more features to the simulation developed in my previous article. This updated simulation will represent real-life scenario more closely and can be used effectively in Data Analysis tasks or AI applications. First, we will be adding turning functionality to the vehicles being generated. So unlike the previous simulation where all the vehicles went straight through the intersection, some of the vehicles will be turning left, some right and some will go straight in the modified simulation. Second, we will be adding a feature that lets us choose which vehicle types among car, bus, truck, and bike we want in our simulation. Third, we will be adding a random green signal timer function, which sets the green signal time equal to a random number generated within a given range and helps in modeling tasks. The video below shows the final output of the simulation we will be building. We are starting from where we left off in the previous article. Follow the steps in the article to set up the environment and build a basic simulation, which looks something like this. In this article, we will be modifying the basic simulation to include the aforementioned additional features. Alternatively, you can find the source code for the basic simulation along with setup instructions here. To code the additional functionalities into our existing simulation, we need to add some new variables, define some new functions, and modify some of the existing functions as well. Here, we are increasing the value of 2 variables, stoppingGap and movingGap. This is done to prevent overlap of vehicles when they turn. # modify existing variablesstoppingGap = 25 movingGap = 25 Next, we define some new variables that will be required to implement our desired functionalities. # add new variablesallowedVehicleTypes = {'car': True, 'bus': True, 'truck': True, 'bike': True}allowedVehicleTypesList = []vehiclesTurned = {'right': {1:[], 2:[]}, 'down': {1:[], 2:[]}, 'left': {1:[], 2:[]}, 'up': {1:[], 2:[]}}vehiclesNotTurned = {'right': {1:[], 2:[]}, 'down': {1:[], 2:[]}, 'left': {1:[], 2:[]}, 'up': {1:[], 2:[]}}rotationAngle = 3mid = {'right': {'x':705, 'y':445}, 'down': {'x':695, 'y':450}, 'left': {'x':695, 'y':425}, 'up': {'x':695, 'y':400}}randomGreenSignalTimer = TruerandomGreenSignalTimerRange = [10,20] The allowedVehicleTypes dictionary is used to control which vehicle types will be generated in the simulation. The mid dictionary represents the coordinates of the midpoint of the intersection image, from where the vehicles would turn right to cross the intersection. randomGreenSignalTimer is used to control whether the green signal timer will be set randomly or equal to default values. If randomGreenSignalTimer is set to True, then a random number between the range specified by randomGreenSignalTimerRange is set as green signal time. We need to add some new attributes to the Vehicle class and update the move() function. The Vehicle class now has the following additional attributes: willTurn: Represents whether the vehicle will turn at the intersection or not turned: Represents whether the vehicle has turned or not rotateAngle: Represents the angle by which the vehicle rotates in each move() call crossedIndex: Represents the relative position of the vehicle among the vehicles moving in the same direction and the same lane after crossing the intersection index: Represents the relative position of the vehicle among the vehicles moving in the same direction and the same lane originalImage: Represents the original image of the vehicle The constructor also needs to be modified to accommodate these new attributes. The modified Vehicle class looks like this. The latter part of the constructor and the render() function remain the same. Now comes the most important and complicated part of our code, the move() function. Let us focus on the code for vehicles moving towards the right, as the same conditions are checked for other directions, and the code is quite similar. For each direction, we first check if the vehicle has crossed the intersection or not. This is important because if the vehicle has already crossed, then it can keep moving regardless of the signal being green or red, depending only on the vehicle ahead. So when the vehicle crosses the intersection, we set the value of crossed to 1. Now, if the vehicle goes straight i.e. it does not turn, then we add it to the vehiclesNotTurned list and update its crossedIndex, which is its index in the vehiclesNotTurned list. This is done because the order of the vehicles changes after the intersection as some turn and some do not, and the vehicles list defined earlier is not useful to prevent them from overlapping. Next, if the vehicle is going to turn, it moves straight until the turning point which is the middle of the intersection. This movement can happen in 3 cases: If it has not reached its stop point before the intersectionIf it has already crossed the intersectionIf the traffic signal controlling the direction in which the vehicle is moving is Green If it has not reached its stop point before the intersection If it has already crossed the intersection If the traffic signal controlling the direction in which the vehicle is moving is Green Along with this, we need to ensure that there is no overlap with the vehicle ahead when it moves. This is decided by taking into consideration the following three parameters: the coordinate of the vehicle ahead, the width/height of the vehicle ahead, and the movingGap. Also, if the vehicle ahead has already turned, then we need not worry about overlap. Only when any of these three conditions are satisfied along with no overlap, the coordinate of the vehicle is updated by incrementing/decrementing it by the speed of the vehicle, depending on its direction of motion. Once the vehicle crosses its turning point, if the turned value is 0, it turns as it rotates while moving along both the x and y-axis. Once the rotationAngle is 90 degrees, the turned variable is set to 1, the vehicle is added to the vehiclesTurned list, and its crossedIndex is updated. Else if the turned value is 1, the vehicle moves only if there is a sufficient gap to the vehicle ahead, found using the vehiclesTurned list. This is decided based on the same three parameters mentioned above. This turning logic is coded separately for the two lanes to have more control over the simulation. This is where the originalImage is used. Rotating an image is considered a destructive transform. This means that every time it is performed, the image loses pixel data. For this reason, it is better to re-transform the original image than to keep transforming an image multiple times. Thus, we rotate the originalImage by rotationAngle and update the image by this modified image, while keeping the originalImage unchanged. Lastly, if the vehicle is not going to turn, then the first part remains the same as the turning vehicles, and they move straight until they cross the intersection. However, after crossing the intersection, they simply move if there is a sufficient gap to the vehicle ahead, found using the vehiclesNotTurned list. Again, this is decided based on the three parameters mentioned above. The entire move() function is given below. Note that this function is also a part of the Vehicle class defined above and needs to be indented accordingly. We need to modify the initialize() function so that the 4 TrafficSignal objects are initialized with random values between the range specified by randomGreenSignalTimerRange if randomGreenSignalTime is set to True. def initialize(): minTime = randomGreenSignalTimerRange[0] maxTime = randomGreenSignalTimerRange[1] if(randomGreenSignalTimer): ts1 = TrafficSignal(0, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts1) ts2 = TrafficSignal(ts1.yellow+ts1.green, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts2) ts3 = TrafficSignal(defaultRed, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts3) ts4 = TrafficSignal(defaultRed, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts4) else: ts1 = TrafficSignal(0, defaultYellow, defaultGreen[0]) signals.append(ts1) ts2 = TrafficSignal(ts1.yellow+ts1.green, defaultYellow, defaultGreen[1]) signals.append(ts2) ts3 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[2]) signals.append(ts3) ts4 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[3]) signals.append(ts4) repeat() The same applies to the repeat() function as well. The only change is that if randomGreenSignalTimer is set to True, we generate a random number between randomGreenSignalTimerRange[0] and randomGreenSignalTimerRange[1], and set it as the green signal time. def repeat(): global currentGreen, currentYellow, nextGreen while(signals[currentGreen].green>0): updateValues() time.sleep(1) currentYellow = 1 for i in range(0,3): for vehicle in vehicles[directionNumbers[currentGreen]][i]: vehicle.stop=defaultStop[directionNumbers[currentGreen]] while(signals[currentGreen].yellow>0): updateValues() time.sleep(1) currentYellow = 0 minTime = randomGreenSignalTimerRange[0] maxTime = randomGreenSignalTimerRange[1] if(randomGreenSignalTimer): signals[currentGreen].green=random.randint(minTime, maxTime) else: signals[currentGreen].green = defaultGreen[currentGreen] signals[currentGreen].yellow = defaultYellow signals[currentGreen].red = defaultRed currentGreen = nextGreen nextGreen = (currentGreen+1)%noOfSignals signals[nextGreen].red = signals[currentGreen].yellow+signals[currentGreen].green repeat() The generateVehicles() function is modified as shown below. The vehicle type is set by generating a random number from allowedVehicleTypesList. This list is populated in the Main class below. We define a new variable will_turn, which is initially set to 0. will_turn is then set to 1 with a 40% chance using random numbers. Lastly, in addition to the existing variables, this will_turn variable is also passed in the constructor while creating an object of the Vehicle class. def generateVehicles(): while(True): vehicle_type = random.choice(allowedVehicleTypesList) lane_number = random.randint(1,2) will_turn = 0 if(lane_number == 1): temp = random.randint(0,99) if(temp<40): will_turn = 1 elif(lane_number == 2): temp = random.randint(0,99) if(temp<40): will_turn = 1 temp = random.randint(0,99) direction_number = 0 dist = [25,50,75,100] if(temp<dist[0]): direction_number = 0 elif(temp<dist[1]): direction_number = 1 elif(temp<dist[2]): direction_number = 2 elif(temp<dist[3]): direction_number = 3 Vehicle(lane_number, vehicleTypes[vehicle_type], direction_number, directionNumbers[direction_number], will_turn) time.sleep(1) There is only one small addition here. We just need to populate the allowedVehicleTypesList according to the allowedVehicleTypes dictionary. For this, the following code needs to be added right at the beginning of the Main class, as shown below. The rest of the Main class remains the same. class Main: global allowedVehicleTypesList i = 0 for vehicleType in allowedVehicleTypes: if(allowedVehicleTypes[vehicleType]): allowedVehicleTypesList.append(i) i += 1 Time to see the results. Fire up a cmd/terminal and run the command: $ python simulation.py And we are done! We have added the three additional features β€” turning functionality, vehicle type controller, and random green signal timer function β€” to our simulation. This makes the simulation more representative of the real-life scenarios and gives us more control to customize it, thus serving as a handy tool for data analysis as well as AI or ML applications. Source code: https://github.com/mihir-m-gandhi/Traffic-Intersection-Simulation-with-Turns This is the second part in a series of articles: Traffic Intersection Simulation using Pygame, Part 1 Traffic Intersection Simulation using Pygame, Part 2 Traffic Intersection Simulation using Pygame, Part 3 This simulation was developed as part of a research project titled β€˜Smart Control of Traffic Lights using Artificial Intelligence’. Check out its demonstration video here. This research work was presented at IEEE International Conference on Recent Advances and Innovations in Engineering (ICRAIE) 2020 and published in IEEE Xplore. Read the paper here. Thanks for reading! I hope this article was helpful. If you have any doubts or need further clarification, feel free to reach out to me on LinkedIn.
[ { "code": null, "e": 1098, "s": 171, "text": "In this article, we will be adding some more features to the simulation developed in my previous article. This updated simulation will represent real-life scenario more closely and can be used effectively in Data Analysis tasks or AI applications. First, we will be adding turning functionality to the vehicles being generated. So unlike the previous simulation where all the vehicles went straight through the intersection, some of the vehicles will be turning left, some right and some will go straight in the modified simulation. Second, we will be adding a feature that lets us choose which vehicle types among car, bus, truck, and bike we want in our simulation. Third, we will be adding a random green signal timer function, which sets the green signal time equal to a random number generated within a given range and helps in modeling tasks. The video below shows the final output of the simulation we will be building." }, { "code": null, "e": 1498, "s": 1098, "text": "We are starting from where we left off in the previous article. Follow the steps in the article to set up the environment and build a basic simulation, which looks something like this. In this article, we will be modifying the basic simulation to include the aforementioned additional features. Alternatively, you can find the source code for the basic simulation along with setup instructions here." }, { "code": null, "e": 1680, "s": 1498, "text": "To code the additional functionalities into our existing simulation, we need to add some new variables, define some new functions, and modify some of the existing functions as well." }, { "code": null, "e": 1817, "s": 1680, "text": "Here, we are increasing the value of 2 variables, stoppingGap and movingGap. This is done to prevent overlap of vehicles when they turn." }, { "code": null, "e": 1879, "s": 1817, "text": "# modify existing variablesstoppingGap = 25 movingGap = 25" }, { "code": null, "e": 1978, "s": 1879, "text": "Next, we define some new variables that will be required to implement our desired functionalities." }, { "code": null, "e": 2514, "s": 1978, "text": "# add new variablesallowedVehicleTypes = {'car': True, 'bus': True, 'truck': True, 'bike': True}allowedVehicleTypesList = []vehiclesTurned = {'right': {1:[], 2:[]}, 'down': {1:[], 2:[]}, 'left': {1:[], 2:[]}, 'up': {1:[], 2:[]}}vehiclesNotTurned = {'right': {1:[], 2:[]}, 'down': {1:[], 2:[]}, 'left': {1:[], 2:[]}, 'up': {1:[], 2:[]}}rotationAngle = 3mid = {'right': {'x':705, 'y':445}, 'down': {'x':695, 'y':450}, 'left': {'x':695, 'y':425}, 'up': {'x':695, 'y':400}}randomGreenSignalTimer = TruerandomGreenSignalTimerRange = [10,20]" }, { "code": null, "e": 3055, "s": 2514, "text": "The allowedVehicleTypes dictionary is used to control which vehicle types will be generated in the simulation. The mid dictionary represents the coordinates of the midpoint of the intersection image, from where the vehicles would turn right to cross the intersection. randomGreenSignalTimer is used to control whether the green signal timer will be set randomly or equal to default values. If randomGreenSignalTimer is set to True, then a random number between the range specified by randomGreenSignalTimerRange is set as green signal time." }, { "code": null, "e": 3206, "s": 3055, "text": "We need to add some new attributes to the Vehicle class and update the move() function. The Vehicle class now has the following additional attributes:" }, { "code": null, "e": 3284, "s": 3206, "text": "willTurn: Represents whether the vehicle will turn at the intersection or not" }, { "code": null, "e": 3341, "s": 3284, "text": "turned: Represents whether the vehicle has turned or not" }, { "code": null, "e": 3424, "s": 3341, "text": "rotateAngle: Represents the angle by which the vehicle rotates in each move() call" }, { "code": null, "e": 3584, "s": 3424, "text": "crossedIndex: Represents the relative position of the vehicle among the vehicles moving in the same direction and the same lane after crossing the intersection" }, { "code": null, "e": 3705, "s": 3584, "text": "index: Represents the relative position of the vehicle among the vehicles moving in the same direction and the same lane" }, { "code": null, "e": 3765, "s": 3705, "text": "originalImage: Represents the original image of the vehicle" }, { "code": null, "e": 3888, "s": 3765, "text": "The constructor also needs to be modified to accommodate these new attributes. The modified Vehicle class looks like this." }, { "code": null, "e": 3966, "s": 3888, "text": "The latter part of the constructor and the render() function remain the same." }, { "code": null, "e": 4202, "s": 3966, "text": "Now comes the most important and complicated part of our code, the move() function. Let us focus on the code for vehicles moving towards the right, as the same conditions are checked for other directions, and the code is quite similar." }, { "code": null, "e": 4912, "s": 4202, "text": "For each direction, we first check if the vehicle has crossed the intersection or not. This is important because if the vehicle has already crossed, then it can keep moving regardless of the signal being green or red, depending only on the vehicle ahead. So when the vehicle crosses the intersection, we set the value of crossed to 1. Now, if the vehicle goes straight i.e. it does not turn, then we add it to the vehiclesNotTurned list and update its crossedIndex, which is its index in the vehiclesNotTurned list. This is done because the order of the vehicles changes after the intersection as some turn and some do not, and the vehicles list defined earlier is not useful to prevent them from overlapping." }, { "code": null, "e": 5071, "s": 4912, "text": "Next, if the vehicle is going to turn, it moves straight until the turning point which is the middle of the intersection. This movement can happen in 3 cases:" }, { "code": null, "e": 5261, "s": 5071, "text": "If it has not reached its stop point before the intersectionIf it has already crossed the intersectionIf the traffic signal controlling the direction in which the vehicle is moving is Green" }, { "code": null, "e": 5322, "s": 5261, "text": "If it has not reached its stop point before the intersection" }, { "code": null, "e": 5365, "s": 5322, "text": "If it has already crossed the intersection" }, { "code": null, "e": 5453, "s": 5365, "text": "If the traffic signal controlling the direction in which the vehicle is moving is Green" }, { "code": null, "e": 6025, "s": 5453, "text": "Along with this, we need to ensure that there is no overlap with the vehicle ahead when it moves. This is decided by taking into consideration the following three parameters: the coordinate of the vehicle ahead, the width/height of the vehicle ahead, and the movingGap. Also, if the vehicle ahead has already turned, then we need not worry about overlap. Only when any of these three conditions are satisfied along with no overlap, the coordinate of the vehicle is updated by incrementing/decrementing it by the speed of the vehicle, depending on its direction of motion." }, { "code": null, "e": 6622, "s": 6025, "text": "Once the vehicle crosses its turning point, if the turned value is 0, it turns as it rotates while moving along both the x and y-axis. Once the rotationAngle is 90 degrees, the turned variable is set to 1, the vehicle is added to the vehiclesTurned list, and its crossedIndex is updated. Else if the turned value is 1, the vehicle moves only if there is a sufficient gap to the vehicle ahead, found using the vehiclesTurned list. This is decided based on the same three parameters mentioned above. This turning logic is coded separately for the two lanes to have more control over the simulation." }, { "code": null, "e": 7047, "s": 6622, "text": "This is where the originalImage is used. Rotating an image is considered a destructive transform. This means that every time it is performed, the image loses pixel data. For this reason, it is better to re-transform the original image than to keep transforming an image multiple times. Thus, we rotate the originalImage by rotationAngle and update the image by this modified image, while keeping the originalImage unchanged." }, { "code": null, "e": 7432, "s": 7047, "text": "Lastly, if the vehicle is not going to turn, then the first part remains the same as the turning vehicles, and they move straight until they cross the intersection. However, after crossing the intersection, they simply move if there is a sufficient gap to the vehicle ahead, found using the vehiclesNotTurned list. Again, this is decided based on the three parameters mentioned above." }, { "code": null, "e": 7587, "s": 7432, "text": "The entire move() function is given below. Note that this function is also a part of the Vehicle class defined above and needs to be indented accordingly." }, { "code": null, "e": 7802, "s": 7587, "text": "We need to modify the initialize() function so that the 4 TrafficSignal objects are initialized with random values between the range specified by randomGreenSignalTimerRange if randomGreenSignalTime is set to True." }, { "code": null, "e": 8810, "s": 7802, "text": "def initialize(): minTime = randomGreenSignalTimerRange[0] maxTime = randomGreenSignalTimerRange[1] if(randomGreenSignalTimer): ts1 = TrafficSignal(0, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts1) ts2 = TrafficSignal(ts1.yellow+ts1.green, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts2) ts3 = TrafficSignal(defaultRed, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts3) ts4 = TrafficSignal(defaultRed, defaultYellow, random.randint(minTime,maxTime)) signals.append(ts4) else: ts1 = TrafficSignal(0, defaultYellow, defaultGreen[0]) signals.append(ts1) ts2 = TrafficSignal(ts1.yellow+ts1.green, defaultYellow, defaultGreen[1]) signals.append(ts2) ts3 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[2]) signals.append(ts3) ts4 = TrafficSignal(defaultRed, defaultYellow, defaultGreen[3]) signals.append(ts4) repeat()" }, { "code": null, "e": 9067, "s": 8810, "text": "The same applies to the repeat() function as well. The only change is that if randomGreenSignalTimer is set to True, we generate a random number between randomGreenSignalTimerRange[0] and randomGreenSignalTimerRange[1], and set it as the green signal time." }, { "code": null, "e": 10027, "s": 9067, "text": "def repeat(): global currentGreen, currentYellow, nextGreen while(signals[currentGreen].green>0): updateValues() time.sleep(1) currentYellow = 1 for i in range(0,3): for vehicle in vehicles[directionNumbers[currentGreen]][i]: vehicle.stop=defaultStop[directionNumbers[currentGreen]] while(signals[currentGreen].yellow>0): updateValues() time.sleep(1) currentYellow = 0 minTime = randomGreenSignalTimerRange[0] maxTime = randomGreenSignalTimerRange[1] if(randomGreenSignalTimer): signals[currentGreen].green=random.randint(minTime, maxTime) else: signals[currentGreen].green = defaultGreen[currentGreen] signals[currentGreen].yellow = defaultYellow signals[currentGreen].red = defaultRed currentGreen = nextGreen nextGreen = (currentGreen+1)%noOfSignals signals[nextGreen].red = signals[currentGreen].yellow+signals[currentGreen].green repeat()" }, { "code": null, "e": 10503, "s": 10027, "text": "The generateVehicles() function is modified as shown below. The vehicle type is set by generating a random number from allowedVehicleTypesList. This list is populated in the Main class below. We define a new variable will_turn, which is initially set to 0. will_turn is then set to 1 with a 40% chance using random numbers. Lastly, in addition to the existing variables, this will_turn variable is also passed in the constructor while creating an object of the Vehicle class." }, { "code": null, "e": 11378, "s": 10503, "text": "def generateVehicles(): while(True): vehicle_type = random.choice(allowedVehicleTypesList) lane_number = random.randint(1,2) will_turn = 0 if(lane_number == 1): temp = random.randint(0,99) if(temp<40): will_turn = 1 elif(lane_number == 2): temp = random.randint(0,99) if(temp<40): will_turn = 1 temp = random.randint(0,99) direction_number = 0 dist = [25,50,75,100] if(temp<dist[0]): direction_number = 0 elif(temp<dist[1]): direction_number = 1 elif(temp<dist[2]): direction_number = 2 elif(temp<dist[3]): direction_number = 3 Vehicle(lane_number, vehicleTypes[vehicle_type], direction_number, directionNumbers[direction_number], will_turn) time.sleep(1)" }, { "code": null, "e": 11669, "s": 11378, "text": "There is only one small addition here. We just need to populate the allowedVehicleTypesList according to the allowedVehicleTypes dictionary. For this, the following code needs to be added right at the beginning of the Main class, as shown below. The rest of the Main class remains the same." }, { "code": null, "e": 11871, "s": 11669, "text": "class Main: global allowedVehicleTypesList i = 0 for vehicleType in allowedVehicleTypes: if(allowedVehicleTypes[vehicleType]): allowedVehicleTypesList.append(i) i += 1" }, { "code": null, "e": 11940, "s": 11871, "text": "Time to see the results. Fire up a cmd/terminal and run the command:" }, { "code": null, "e": 11963, "s": 11940, "text": "$ python simulation.py" }, { "code": null, "e": 12331, "s": 11963, "text": "And we are done! We have added the three additional features β€” turning functionality, vehicle type controller, and random green signal timer function β€” to our simulation. This makes the simulation more representative of the real-life scenarios and gives us more control to customize it, thus serving as a handy tool for data analysis as well as AI or ML applications." }, { "code": null, "e": 12421, "s": 12331, "text": "Source code: https://github.com/mihir-m-gandhi/Traffic-Intersection-Simulation-with-Turns" }, { "code": null, "e": 12470, "s": 12421, "text": "This is the second part in a series of articles:" }, { "code": null, "e": 12523, "s": 12470, "text": "Traffic Intersection Simulation using Pygame, Part 1" }, { "code": null, "e": 12576, "s": 12523, "text": "Traffic Intersection Simulation using Pygame, Part 2" }, { "code": null, "e": 12629, "s": 12576, "text": "Traffic Intersection Simulation using Pygame, Part 3" }, { "code": null, "e": 12982, "s": 12629, "text": "This simulation was developed as part of a research project titled β€˜Smart Control of Traffic Lights using Artificial Intelligence’. Check out its demonstration video here. This research work was presented at IEEE International Conference on Recent Advances and Innovations in Engineering (ICRAIE) 2020 and published in IEEE Xplore. Read the paper here." } ]
Python MySQL – GROUP BY and HAVING Clause
09 May, 2021 In this article, we will see how to perform groupby() and HAVING() operations on SQL using Python. Here we will consider a college database to perform group by operation on the department with respect to student strength. The GROUP BY statement groups rows that have the same values into single based on the aggregate function used. Aggregate functions are (COUNT(), MAX(), MIN(), SUM(), AVG()). Syntax: SELECT aggregare_function(column1),column2,...,columnn FROM table_name GROUP BY column_name; Database in use: Example: Python3 # Establish connection to MySQL databaseimport mysql.connector database = mysql.connector.connect( host="localhost", user="root", password="", database="sravan") # Creating cursor objectcur_object = database.cursor() # Execute the query find = "SELECT department,sum(strength) from \college_data GROUP BY(department)";cur_object.execute(find) # fetching all resultsdata = cur_object.fetchall() print("Total departments with count : ")print(" ")for res in data: print(res[0],res[1],sep="--") # Close database connection database.close() Output: Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The having clause is always used after the Group By clause. Syntax: SELECT aggregate_function (column_names),column1,column2,...,columnn FROM table_name GROUP BY column_name HAVING aggregate_function(column_name) condition; Database in use: Example: Python3 # Establish connection to MySQL databaseimport mysql.connector # give connection with xamppdatabase = mysql.connector.connect( host="localhost", user="root", password="", database="sravan") # Creating cursor objectcur_object = database.cursor() find = "SELECT department,sum(strength) from college_data\GROUP BY(department) HAVING sum(strength)<=400 "; # Execute the query cur_object.execute(find) # fetching all resultsdata = cur_object.fetchall() print("Total departments with count less than 400 : ")print(" ")for res in data: print(res[0],res[1],sep="--") # Close database connection database.close() Output: Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2021" }, { "code": null, "e": 250, "s": 28, "text": "In this article, we will see how to perform groupby() and HAVING() operations on SQL using Python. Here we will consider a college database to perform group by operation on the department with respect to student strength." }, { "code": null, "e": 424, "s": 250, "text": "The GROUP BY statement groups rows that have the same values into single based on the aggregate function used. Aggregate functions are (COUNT(), MAX(), MIN(), SUM(), AVG())." }, { "code": null, "e": 487, "s": 424, "text": "Syntax: SELECT aggregare_function(column1),column2,...,columnn" }, { "code": null, "e": 503, "s": 487, "text": "FROM table_name" }, { "code": null, "e": 525, "s": 503, "text": "GROUP BY column_name;" }, { "code": null, "e": 542, "s": 525, "text": "Database in use:" }, { "code": null, "e": 551, "s": 542, "text": "Example:" }, { "code": null, "e": 559, "s": 551, "text": "Python3" }, { "code": "# Establish connection to MySQL databaseimport mysql.connector database = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"\", database=\"sravan\") # Creating cursor objectcur_object = database.cursor() # Execute the query find = \"SELECT department,sum(strength) from \\college_data GROUP BY(department)\";cur_object.execute(find) # fetching all resultsdata = cur_object.fetchall() print(\"Total departments with count : \")print(\" \")for res in data: print(res[0],res[1],sep=\"--\") # Close database connection database.close() ", "e": 1127, "s": 559, "text": null }, { "code": null, "e": 1135, "s": 1127, "text": "Output:" }, { "code": null, "e": 1523, "s": 1135, "text": "Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The having clause is always used after the Group By clause." }, { "code": null, "e": 1616, "s": 1523, "text": "Syntax: SELECT aggregate_function (column_names),column1,column2,...,columnn FROM table_name" }, { "code": null, "e": 1637, "s": 1616, "text": "GROUP BY column_name" }, { "code": null, "e": 1687, "s": 1637, "text": "HAVING aggregate_function(column_name) condition;" }, { "code": null, "e": 1704, "s": 1687, "text": "Database in use:" }, { "code": null, "e": 1713, "s": 1704, "text": "Example:" }, { "code": null, "e": 1721, "s": 1713, "text": "Python3" }, { "code": "# Establish connection to MySQL databaseimport mysql.connector # give connection with xamppdatabase = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"\", database=\"sravan\") # Creating cursor objectcur_object = database.cursor() find = \"SELECT department,sum(strength) from college_data\\GROUP BY(department) HAVING sum(strength)<=400 \"; # Execute the query cur_object.execute(find) # fetching all resultsdata = cur_object.fetchall() print(\"Total departments with count less than 400 : \")print(\" \")for res in data: print(res[0],res[1],sep=\"--\") # Close database connection database.close() ", "e": 2359, "s": 1721, "text": null }, { "code": null, "e": 2367, "s": 2359, "text": "Output:" }, { "code": null, "e": 2380, "s": 2367, "text": "Python-mySQL" }, { "code": null, "e": 2387, "s": 2380, "text": "Python" } ]
SQL Query to Rename Database
08 Oct, 2021 ALTER SQL command is a DDL (Data Definition Language) statement. ALTER is used to update the structure of the table in the database (like add, delete, modify the attributes of the tables in the database).In this article, we will look at how to rename a database in the SQL server by using the ALTER-Modify keyword. To rename the database we need to create the database first. So, let us create it. Step 1: Creating Database We are creating the database using CREATE query. Step 2: CREATE query The CREATE query is used to create a new database. Query: CREATE DATABASE Test Output: Step 3: Rename Database For this, we need to use the ALTER command. ALTER keyword is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table. Renaming means we are modifying the data. Hence, we will use ALTER – MODIFY. Query: ALTER DATABASE Test MODIFY NAME = Example Output: The database name is changed from Test to Example. Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Oct, 2021" }, { "code": null, "e": 426, "s": 28, "text": "ALTER SQL command is a DDL (Data Definition Language) statement. ALTER is used to update the structure of the table in the database (like add, delete, modify the attributes of the tables in the database).In this article, we will look at how to rename a database in the SQL server by using the ALTER-Modify keyword. To rename the database we need to create the database first. So, let us create it." }, { "code": null, "e": 452, "s": 426, "text": "Step 1: Creating Database" }, { "code": null, "e": 501, "s": 452, "text": "We are creating the database using CREATE query." }, { "code": null, "e": 522, "s": 501, "text": "Step 2: CREATE query" }, { "code": null, "e": 573, "s": 522, "text": "The CREATE query is used to create a new database." }, { "code": null, "e": 580, "s": 573, "text": "Query:" }, { "code": null, "e": 601, "s": 580, "text": "CREATE DATABASE Test" }, { "code": null, "e": 609, "s": 601, "text": "Output:" }, { "code": null, "e": 633, "s": 609, "text": "Step 3: Rename Database" }, { "code": null, "e": 835, "s": 633, "text": "For this, we need to use the ALTER command. ALTER keyword is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table." }, { "code": null, "e": 877, "s": 835, "text": "Renaming means we are modifying the data." }, { "code": null, "e": 912, "s": 877, "text": "Hence, we will use ALTER – MODIFY." }, { "code": null, "e": 919, "s": 912, "text": "Query:" }, { "code": null, "e": 961, "s": 919, "text": "ALTER DATABASE Test MODIFY NAME = Example" }, { "code": null, "e": 969, "s": 961, "text": "Output:" }, { "code": null, "e": 1020, "s": 969, "text": "The database name is changed from Test to Example." }, { "code": null, "e": 1027, "s": 1020, "text": "Picked" }, { "code": null, "e": 1037, "s": 1027, "text": "SQL-Query" }, { "code": null, "e": 1048, "s": 1037, "text": "SQL-Server" }, { "code": null, "e": 1052, "s": 1048, "text": "SQL" }, { "code": null, "e": 1056, "s": 1052, "text": "SQL" } ]
Find number of days between two given dates
05 Nov, 2021 Given two dates, find total number of days between them. The count of days must be calculated in O(1) time and O(1) auxiliary space. Examples: Input: dt1 = {10, 2, 2014} dt2 = {10, 3, 2015} Output: 393 dt1 represents "10-Feb-2014" and dt2 represents "10-Mar-2015" The difference is 365 + 28 Input: dt1 = {10, 2, 2000} dt2 = {10, 3, 2000} Output: 29 Note that 2000 is a leap year Input: dt1 = {10, 2, 2000} dt2 = {10, 2, 2000} Output: 0 Both dates are same Input: dt1 = {1, 2, 2000}; dt2 = {1, 2, 2004}; Output: 1461 Number of days is 365*4 + 1 One Naive Solution is to start from dt1 and keep counting days till dt2 is reached. This solution requires more than O(1) time. A Better and Simple solution is to count total number of days before dt1 from i.e., total days from 00/00/0000 to dt1, then count total number of days before dt2. Finally return the difference between two counts. Let the given two dates be "1-Feb-2000" and "1-Feb-2004" dt1 = {1, 2, 2000}; dt2 = {1, 2, 2004}; Count number of days before dt1. Let this count be n1. Every leap year adds one extra day (29 Feb) to total days. n1 = 2000*365 + 31 + 1 + Number of leap years Count of leap years for a date 'd/m/y' can be calculated using the following formula: Number leap years = floor(y/4) - floor(y/100) + floor(y/400) if m > 2 = floor((y-1)/4) - floor((y-1)/100) + floor((y-1)/400) if m <= 2 All above divisions must be done using integer arithmetic So that the remainder is ignored. For 01/01/2000, leap year count is 1999/4 - 1999/100 + 1999/400 which is 499 - 19 + 4 = 484 Therefore n1 is 2000*365 + 31 + 1 + 484 Similarly, the count number of days before dt2. Let this the count be n2.Finally, return n2-n1 Below is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program two find number of// days between two given dates#include <iostream>using namespace std; // A date has day 'd', month 'm' and year 'y'struct Date { int d, m, y;}; // To store number of days in// all months from January to Dec.const int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // This function counts number of// leap years before the given dateint countLeapYears(Date d){ int years = d.y; // Check if the current year needs to be // considered for the count of leap years // or not if (d.m <= 2) years--; // An year is a leap year if it // is a multiple of 4, // multiple of 400 and not a // multiple of 100. return years / 4 - years / 100 + years / 400;} // This function returns number of// days between two given datesint getDifference(Date dt1, Date dt2){ // COUNT TOTAL NUMBER OF DAYS // BEFORE FIRST DATE 'dt1' // initialize count using years and day long int n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (int i = 0; i < dt1.m - 1; i++) n1 += monthDays[i]; // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL NUMBER OF // DAYS BEFORE 'dt2' long int n2 = dt2.y * 365 + dt2.d; for (int i = 0; i < dt2.m - 1; i++) n2 += monthDays[i]; n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1);} // Driver codeint main(){ Date dt1 = { 1, 2, 2000 }; Date dt2 = { 1, 2, 2004 }; // Function call cout << "Difference between two dates is " << getDifference(dt1, dt2); return 0;} // Java program two find number of// days between two given dates class GFG{ // A date has day 'd', month 'm' and year 'y' static class Date { int d, m, y; public Date(int d, int m, int y) { this.d = d; this.m = m; this.y = y; } }; // To store number of days in // all months from January to Dec. static int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // This function counts number of // leap years before the given date static int countLeapYears(Date d) { int years = d.y; // Check if the current year needs to be considered // for the count of leap years or not if (d.m <= 2) { years--; } // An year is a leap year if it is a multiple of 4, // multiple of 400 and not a multiple of 100. return years / 4 - years / 100 + years / 400; } // This function returns number // of days between two given dates static int getDifference(Date dt1, Date dt2) { // COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' // initialize count using years and day int n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (int i = 0; i < dt1.m - 1; i++) { n1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' int n2 = dt2.y * 365 + dt2.d; for (int i = 0; i < dt2.m - 1; i++) { n2 += monthDays[i]; } n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1); } // Driver code public static void main(String[] args) { Date dt1 = new Date(1, 2, 2000); Date dt2 = new Date(1, 2, 2004); System.out.println("Difference between two dates is " + getDifference(dt1, dt2)); }} // This code is contributed by 29AjayKumar # Python3 program two find number of# days between two given dates # A date has day 'd', month# 'm' and year 'y' class Date: def __init__(self, d, m, y): self.d = d self.m = m self.y = y # To store number of days in# all months from January to Dec.monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This function counts number of# leap years before the given date def countLeapYears(d): years = d.y # Check if the current year needs # to be considered for the count # of leap years or not if (d.m <= 2): years -= 1 # An year is a leap year if it is a # multiple of 4, multiple of 400 and # not a multiple of 100. ans = int(years / 4) ans -= int(years / 100) ans += int(years / 400) return ans # This function returns number of# days between two given dates def getDifference(dt1, dt2): # COUNT TOTAL NUMBER OF DAYS # BEFORE FIRST DATE 'dt1' # initialize count using years and day n1 = dt1.y * 365 + dt1.d # Add days for months in given date for i in range(0, dt1.m - 1): n1 += monthDays[i] # Since every leap year is of 366 days, # Add a day for every leap year n1 += countLeapYears(dt1) # SIMILARLY, COUNT TOTAL NUMBER # OF DAYS BEFORE 'dt2' n2 = dt2.y * 365 + dt2.d for i in range(0, dt2.m - 1): n2 += monthDays[i] n2 += countLeapYears(dt2) # return difference between # two counts return (n2 - n1) # Driver Codedt1 = Date(1, 9, 2014)dt2 = Date(3, 9, 2020) # Function callprint("Difference between two dates is", getDifference(dt1, dt2)) # This code is contributed by Smitha // C# program two find number of// days between two given datesusing System; class GFG { // A date has day 'd', month 'm' and year 'y' public class Date { public int d, m, y; public Date(int d, int m, int y) { this.d = d; this.m = m; this.y = y; } }; // To store number of days in // all months from January to Dec. static int[] monthDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // This function counts number of // leap years before the given date static int countLeapYears(Date d) { int years = d.y; // Check if the current year // needs to be considered // for the count of leap years or not if (d.m <= 2) { years--; } // An year is a leap year if it is // a multiple of 4, multiple of 400 // and not a multiple of 100. return years / 4 - years / 100 + years / 400; } // This function returns number // of days between two given dates static int getDifference(Date dt1, Date dt2) { // COUNT TOTAL NUMBER OF DAYS // BEFORE FIRST DATE 'dt1' // initialize count using years and day int n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (int i = 0; i < dt1.m - 1; i++) { n1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL // NUMBER OF DAYS BEFORE 'dt2' int n2 = dt2.y * 365 + dt2.d; for (int i = 0; i < dt2.m - 1; i++) { n2 += monthDays[i]; } n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1); } // Driver code public static void Main(String[] args) { Date dt1 = new Date(1, 2, 2000); Date dt2 = new Date(1, 2, 2004); // Function call Console.WriteLine("Difference between two dates is " + getDifference(dt1, dt2)); }} // This code is contributed by PrinciRaj1992 <script> // JavaScript program two find number of// days between two given dates // A date has day 'd', month 'm' and year 'y'class Date{ constructor(d,m,y) { this.d = d; this.m = m; this.y = y; }} // To store number of days in // all months from January to Dec.let monthDays=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];// This function counts number of // leap years before the given date function countLeapYears(d){ let years = d.y; // Check if the current year needs to be considered // for the count of leap years or not if (d.m <= 2) { years--; } // An year is a leap year if it is a multiple of 4, // multiple of 400 and not a multiple of 100. return Math.floor(years / 4) - Math.floor(years / 100) + Math.floor(years / 400);} // This function returns number // of days between two given datesfunction getDifference(dt1,dt2){// COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' // initialize count using years and day let n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (let i = 0; i < dt1.m - 1; i++) { n1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' let n2 = dt2.y * 365 + dt2.d; for (let i = 0; i < dt2.m - 1; i++) { n2 += monthDays[i]; } n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1);} // Driver codelet dt1 = new Date(1, 2, 2000);let dt2 = new Date(1, 2, 2004);document.write("Difference between two dates is " + getDifference(dt1, dt2)); // This code is contributed by rag2127 </script> Difference between two dates is 1461 Time Complexity: O(1) Auxiliary Space: O(1) Note: The above program follows the Gregorian Calendar from the beginning of the time. This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Smitha Dinesh Semwal 29AjayKumar princiraj1992 KimiRZLin chirags_30 rag2127 simranarora5sos subham348 date-time-program Zoho Mathematical Misc Zoho Misc Mathematical Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operators in C / C++ Find minimum number of coins that make a given value Prime Numbers Modulo 10^9+7 (1000000007) Minimum number of jumps to reach end Overview of Data Structures | Set 1 (Linear Data Structures) vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions How to write Regular Expressions? Program for nth Catalan Number
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Nov, 2021" }, { "code": null, "e": 188, "s": 54, "text": "Given two dates, find total number of days between them. The count of days must be calculated in O(1) time and O(1) auxiliary space. " }, { "code": null, "e": 199, "s": 188, "text": "Examples: " }, { "code": null, "e": 635, "s": 199, "text": "Input: dt1 = {10, 2, 2014}\n dt2 = {10, 3, 2015}\nOutput: 393\ndt1 represents \"10-Feb-2014\" and dt2 represents \"10-Mar-2015\"\nThe difference is 365 + 28\n\nInput: dt1 = {10, 2, 2000}\n dt2 = {10, 3, 2000}\nOutput: 29\nNote that 2000 is a leap year\n\nInput: dt1 = {10, 2, 2000}\n dt2 = {10, 2, 2000}\nOutput: 0\nBoth dates are same\n\nInput: dt1 = {1, 2, 2000};\n dt2 = {1, 2, 2004};\nOutput: 1461\nNumber of days is 365*4 + 1" }, { "code": null, "e": 977, "s": 635, "text": "One Naive Solution is to start from dt1 and keep counting days till dt2 is reached. This solution requires more than O(1) time. A Better and Simple solution is to count total number of days before dt1 from i.e., total days from 00/00/0000 to dt1, then count total number of days before dt2. Finally return the difference between two counts. " }, { "code": null, "e": 1783, "s": 977, "text": "Let the given two dates be \"1-Feb-2000\" and \"1-Feb-2004\"\ndt1 = {1, 2, 2000};\ndt2 = {1, 2, 2004};\nCount number of days before dt1. Let this count be n1.\nEvery leap year adds one extra day (29 Feb) to total days.\nn1 = 2000*365 + 31 + 1 + Number of leap years \nCount of leap years for a date 'd/m/y' can be calculated \nusing the following formula:\nNumber leap years \n = floor(y/4) - floor(y/100) + floor(y/400) if m > 2\n = floor((y-1)/4) - floor((y-1)/100) + floor((y-1)/400) if m <= 2\nAll above divisions must be done using integer arithmetic\nSo that the remainder is ignored.\nFor 01/01/2000, leap year count is 1999/4 - 1999/100 \n+ 1999/400 which is 499 - 19 + 4 = 484\nTherefore n1 is 2000*365 + 31 + 1 + 484\n\nSimilarly, the count number of days before dt2. \nLet this the count be n2.Finally, return n2-n1" }, { "code": null, "e": 1831, "s": 1783, "text": "Below is the implementation of the above idea. " }, { "code": null, "e": 1835, "s": 1831, "text": "C++" }, { "code": null, "e": 1840, "s": 1835, "text": "Java" }, { "code": null, "e": 1848, "s": 1840, "text": "Python3" }, { "code": null, "e": 1851, "s": 1848, "text": "C#" }, { "code": null, "e": 1862, "s": 1851, "text": "Javascript" }, { "code": "// C++ program two find number of// days between two given dates#include <iostream>using namespace std; // A date has day 'd', month 'm' and year 'y'struct Date { int d, m, y;}; // To store number of days in// all months from January to Dec.const int monthDays[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // This function counts number of// leap years before the given dateint countLeapYears(Date d){ int years = d.y; // Check if the current year needs to be // considered for the count of leap years // or not if (d.m <= 2) years--; // An year is a leap year if it // is a multiple of 4, // multiple of 400 and not a // multiple of 100. return years / 4 - years / 100 + years / 400;} // This function returns number of// days between two given datesint getDifference(Date dt1, Date dt2){ // COUNT TOTAL NUMBER OF DAYS // BEFORE FIRST DATE 'dt1' // initialize count using years and day long int n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (int i = 0; i < dt1.m - 1; i++) n1 += monthDays[i]; // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL NUMBER OF // DAYS BEFORE 'dt2' long int n2 = dt2.y * 365 + dt2.d; for (int i = 0; i < dt2.m - 1; i++) n2 += monthDays[i]; n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1);} // Driver codeint main(){ Date dt1 = { 1, 2, 2000 }; Date dt2 = { 1, 2, 2004 }; // Function call cout << \"Difference between two dates is \" << getDifference(dt1, dt2); return 0;}", "e": 3570, "s": 1862, "text": null }, { "code": "// Java program two find number of// days between two given dates class GFG{ // A date has day 'd', month 'm' and year 'y' static class Date { int d, m, y; public Date(int d, int m, int y) { this.d = d; this.m = m; this.y = y; } }; // To store number of days in // all months from January to Dec. static int monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // This function counts number of // leap years before the given date static int countLeapYears(Date d) { int years = d.y; // Check if the current year needs to be considered // for the count of leap years or not if (d.m <= 2) { years--; } // An year is a leap year if it is a multiple of 4, // multiple of 400 and not a multiple of 100. return years / 4 - years / 100 + years / 400; } // This function returns number // of days between two given dates static int getDifference(Date dt1, Date dt2) { // COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' // initialize count using years and day int n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (int i = 0; i < dt1.m - 1; i++) { n1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' int n2 = dt2.y * 365 + dt2.d; for (int i = 0; i < dt2.m - 1; i++) { n2 += monthDays[i]; } n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1); } // Driver code public static void main(String[] args) { Date dt1 = new Date(1, 2, 2000); Date dt2 = new Date(1, 2, 2004); System.out.println(\"Difference between two dates is \" + getDifference(dt1, dt2)); }} // This code is contributed by 29AjayKumar", "e": 5680, "s": 3570, "text": null }, { "code": "# Python3 program two find number of# days between two given dates # A date has day 'd', month# 'm' and year 'y' class Date: def __init__(self, d, m, y): self.d = d self.m = m self.y = y # To store number of days in# all months from January to Dec.monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # This function counts number of# leap years before the given date def countLeapYears(d): years = d.y # Check if the current year needs # to be considered for the count # of leap years or not if (d.m <= 2): years -= 1 # An year is a leap year if it is a # multiple of 4, multiple of 400 and # not a multiple of 100. ans = int(years / 4) ans -= int(years / 100) ans += int(years / 400) return ans # This function returns number of# days between two given dates def getDifference(dt1, dt2): # COUNT TOTAL NUMBER OF DAYS # BEFORE FIRST DATE 'dt1' # initialize count using years and day n1 = dt1.y * 365 + dt1.d # Add days for months in given date for i in range(0, dt1.m - 1): n1 += monthDays[i] # Since every leap year is of 366 days, # Add a day for every leap year n1 += countLeapYears(dt1) # SIMILARLY, COUNT TOTAL NUMBER # OF DAYS BEFORE 'dt2' n2 = dt2.y * 365 + dt2.d for i in range(0, dt2.m - 1): n2 += monthDays[i] n2 += countLeapYears(dt2) # return difference between # two counts return (n2 - n1) # Driver Codedt1 = Date(1, 9, 2014)dt2 = Date(3, 9, 2020) # Function callprint(\"Difference between two dates is\", getDifference(dt1, dt2)) # This code is contributed by Smitha", "e": 7332, "s": 5680, "text": null }, { "code": "// C# program two find number of// days between two given datesusing System; class GFG { // A date has day 'd', month 'm' and year 'y' public class Date { public int d, m, y; public Date(int d, int m, int y) { this.d = d; this.m = m; this.y = y; } }; // To store number of days in // all months from January to Dec. static int[] monthDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // This function counts number of // leap years before the given date static int countLeapYears(Date d) { int years = d.y; // Check if the current year // needs to be considered // for the count of leap years or not if (d.m <= 2) { years--; } // An year is a leap year if it is // a multiple of 4, multiple of 400 // and not a multiple of 100. return years / 4 - years / 100 + years / 400; } // This function returns number // of days between two given dates static int getDifference(Date dt1, Date dt2) { // COUNT TOTAL NUMBER OF DAYS // BEFORE FIRST DATE 'dt1' // initialize count using years and day int n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (int i = 0; i < dt1.m - 1; i++) { n1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL // NUMBER OF DAYS BEFORE 'dt2' int n2 = dt2.y * 365 + dt2.d; for (int i = 0; i < dt2.m - 1; i++) { n2 += monthDays[i]; } n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1); } // Driver code public static void Main(String[] args) { Date dt1 = new Date(1, 2, 2000); Date dt2 = new Date(1, 2, 2004); // Function call Console.WriteLine(\"Difference between two dates is \" + getDifference(dt1, dt2)); }} // This code is contributed by PrinciRaj1992", "e": 9613, "s": 7332, "text": null }, { "code": "<script> // JavaScript program two find number of// days between two given dates // A date has day 'd', month 'm' and year 'y'class Date{ constructor(d,m,y) { this.d = d; this.m = m; this.y = y; }} // To store number of days in // all months from January to Dec.let monthDays=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];// This function counts number of // leap years before the given date function countLeapYears(d){ let years = d.y; // Check if the current year needs to be considered // for the count of leap years or not if (d.m <= 2) { years--; } // An year is a leap year if it is a multiple of 4, // multiple of 400 and not a multiple of 100. return Math.floor(years / 4) - Math.floor(years / 100) + Math.floor(years / 400);} // This function returns number // of days between two given datesfunction getDifference(dt1,dt2){// COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1' // initialize count using years and day let n1 = dt1.y * 365 + dt1.d; // Add days for months in given date for (let i = 0; i < dt1.m - 1; i++) { n1 += monthDays[i]; } // Since every leap year is of 366 days, // Add a day for every leap year n1 += countLeapYears(dt1); // SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2' let n2 = dt2.y * 365 + dt2.d; for (let i = 0; i < dt2.m - 1; i++) { n2 += monthDays[i]; } n2 += countLeapYears(dt2); // return difference between two counts return (n2 - n1);} // Driver codelet dt1 = new Date(1, 2, 2000);let dt2 = new Date(1, 2, 2004);document.write(\"Difference between two dates is \" + getDifference(dt1, dt2)); // This code is contributed by rag2127 </script>", "e": 11566, "s": 9613, "text": null }, { "code": null, "e": 11603, "s": 11566, "text": "Difference between two dates is 1461" }, { "code": null, "e": 11625, "s": 11603, "text": "Time Complexity: O(1)" }, { "code": null, "e": 11647, "s": 11625, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 11734, "s": 11647, "text": "Note: The above program follows the Gregorian Calendar from the beginning of the time." }, { "code": null, "e": 11902, "s": 11734, "text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 11923, "s": 11902, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 11935, "s": 11923, "text": "29AjayKumar" }, { "code": null, "e": 11949, "s": 11935, "text": "princiraj1992" }, { "code": null, "e": 11959, "s": 11949, "text": "KimiRZLin" }, { "code": null, "e": 11970, "s": 11959, "text": "chirags_30" }, { "code": null, "e": 11978, "s": 11970, "text": "rag2127" }, { "code": null, "e": 11994, "s": 11978, "text": "simranarora5sos" }, { "code": null, "e": 12004, "s": 11994, "text": "subham348" }, { "code": null, "e": 12022, "s": 12004, "text": "date-time-program" }, { "code": null, "e": 12027, "s": 12022, "text": "Zoho" }, { "code": null, "e": 12040, "s": 12027, "text": "Mathematical" }, { "code": null, "e": 12045, "s": 12040, "text": "Misc" }, { "code": null, "e": 12050, "s": 12045, "text": "Zoho" }, { "code": null, "e": 12055, "s": 12050, "text": "Misc" }, { "code": null, "e": 12068, "s": 12055, "text": "Mathematical" }, { "code": null, "e": 12073, "s": 12068, "text": "Misc" }, { "code": null, "e": 12171, "s": 12073, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12192, "s": 12171, "text": "Operators in C / C++" }, { "code": null, "e": 12245, "s": 12192, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 12259, "s": 12245, "text": "Prime Numbers" }, { "code": null, "e": 12286, "s": 12259, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 12323, "s": 12286, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 12384, "s": 12323, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 12438, "s": 12384, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 12479, "s": 12438, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 12513, "s": 12479, "text": "How to write Regular Expressions?" } ]
Create Array of Zeros in MATLAB
04 Jul, 2021 MATLAB generally stores its variables in matrix forms, also in array and vector form. Sometimes, we often need a matrix(or array or vector) of zero(s) for some specific operations. We can create a matrix of zero(s) manually or with the help of the in-built function of MATLAB. The in-built function that is used to create an array or matrix of zero(s) is called the zeros() function. We generally prefer this in-built function for the ease of the task rather than create an array of zeros manually. The following part contains the two methods of creating an array or matrix of zeros. If we want to create an array of zeros we can simply do that manually by using the following code: Example: Matlab % MATLAB Code for create % an array of zeros X = [0 0 0 0 0];disp(X) It is basically a row vector of size 1X5 as well as an array of 5 zeros. Output: Output Screenshot Creating a column vector manually: If we want to create a column vector we can just use the following code: Matlab % MATLAB code to create a % column vector withe zero'sX = [0; 0; 0; 0; 0] It basically creates a column vector of size 5X1. Output: Output Screenshot Creating a (n x m) matrix of zeros: In this section, we are going to create an (n x m) dimensional matrix. For example, let n = 3 and m = 4. Basically, the following line of code will generate a matrix with 3 rows and 4 columns. Matlab % MATLAB code for create an % (n x m) dimensional matrixX = [0 0 0 0; 0 0 0 0; 0 0 0 0] Output: Output Screenshot There are several matrices and arrays that we can create using the zeros() function. We are going to describe each of them elaborately in the following section: Creating scalar zero Syntax: variable_name = zeros Return value: In this case, the return value is only scalar zero(β€˜0’). Example: Matlab % MATLAB Code for Creating scalar zeroX = zeros Output: Output Screenshot Creating a (n x n) matrix of zeros syntax: matrix = zeros(n) // Here n is the size of matrix. Return value: zeros(n) function returns a (n x n) matrix of zeros: Input Arguments: Size of square matrix, specified as an integer value.If n is 0 then it returns an empty matrix.If n is negative, it also returns an empty matrix. Size of square matrix, specified as an integer value. If n is 0 then it returns an empty matrix. If n is negative, it also returns an empty matrix. Example: Matlab % MATLAB code for Creating a (n x n) matrix of zerosmatrix = zeros(3) This code returns a 3 x 3 matrix of zeros. Output: Output Screenshot Creating a (sz1 by sz2 by-.......-szn) array of zeros syntax: matrix = zeros(sz1, sz2,.......,szn) Return value: This function returns an sz1-by-...-by-szN array of zeros where sz1,...,szN indicate the size of each dimension. For example, zeros(2, 3, 4) returns a 2 X 3 X 4 matrix of zeros. Input Arguments: all the input arguments are specified as an integer value.If any of the argument is 0, it returns an empty matrix.If any of the argument is negative then it is treated as 0.Beyond the second dimension, zeros() ignores trailing dimensions with a size of 1. For example, zeros(4,1,1, 1) produces a 4-by-1 vector of zeros. all the input arguments are specified as an integer value. If any of the argument is 0, it returns an empty matrix. If any of the argument is negative then it is treated as 0. Beyond the second dimension, zeros() ignores trailing dimensions with a size of 1. For example, zeros(4,1,1, 1) produces a 4-by-1 vector of zeros. Example: Matlab % MATLAB Code for 3-d matrix of zerosmatrix = zeros(2, 3, 4) The above code creates a 2-by-3-by-4 array of zeros. Creating a matrix of a specific size Syntax: matrix = zeros(sz) // Here sz is the dimension of the matrix in the form [m n]. Return value: It returns an array of zeros where size vector sz defines size(matrix). For example, zeros([2 3]) returns a 2-by-3 matrix. Input Arguments: Size of each dimension, specified as a row vector of integer values. The rest of the characteristics of this syntax are as same as the previous one. Example: Matlab % MATLAB Code for clone the size of % another matrixmatrix = zeros([2 3]) or we can also clone the size of another matrix like the following: Matlab % MATLAB code for clone the another% matrix in different wayA = ones(2, 3);matrix = zeros(size(A)) The above code basically returns a matrix of 2 X 3 with zeros as every element. Output: Output Screenshot Creating specified data types of zeros syntax: matrix = zeros(___,typename) // Here the first argument may be any of the previous types. Return value: It returns an array of zeros of the specified data type named typename. Input Arguments: Data type (class) to create, specified as β€˜double’, β€˜single’, β€˜logical’,’int8β€², β€˜uint8’, β€˜int16’, β€˜uint16’, β€˜int32’, β€˜uint32’, β€˜int64’, β€˜uint64’, or the name of another class that provides zeros support. Example: Matlab % CodeA = ones(2, 3);matrix = zeros(size(A), 'uint32') This code creates a 2-by-3 matrix of datatype β€˜uint32’. Output: Output Screenshot Creating matrix using a prototype of an array syntax: matrix = zeros(___,’like’,p) // Here the first argument may be any of the previous types. Return value: It returns an array of zeros like p; i.e, of the same data type (class), sparsity, and complexity (real or complex) as p. The user can specify typename or β€˜like’, but not both. Input Arguments: Prototype of array to create, specified as an array. Example Matlab % MATLAB Code for clone complexity% of an arrayp = [2+2i 13i];X = zeros('like',p) Output: Example: Matlab % MATLAB code for clone Size and% Data Type from Existing Array p = uint8([4 5 6; 14 15 16; 12 13 14]);matrix = zeros(size(p),'like',p) Output: Picked MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2021" }, { "code": null, "e": 612, "s": 28, "text": "MATLAB generally stores its variables in matrix forms, also in array and vector form. Sometimes, we often need a matrix(or array or vector) of zero(s) for some specific operations. We can create a matrix of zero(s) manually or with the help of the in-built function of MATLAB. The in-built function that is used to create an array or matrix of zero(s) is called the zeros() function. We generally prefer this in-built function for the ease of the task rather than create an array of zeros manually. The following part contains the two methods of creating an array or matrix of zeros." }, { "code": null, "e": 711, "s": 612, "text": "If we want to create an array of zeros we can simply do that manually by using the following code:" }, { "code": null, "e": 720, "s": 711, "text": "Example:" }, { "code": null, "e": 727, "s": 720, "text": "Matlab" }, { "code": "% MATLAB Code for create % an array of zeros X = [0 0 0 0 0];disp(X)", "e": 797, "s": 727, "text": null }, { "code": null, "e": 870, "s": 797, "text": "It is basically a row vector of size 1X5 as well as an array of 5 zeros." }, { "code": null, "e": 878, "s": 870, "text": "Output:" }, { "code": null, "e": 896, "s": 878, "text": "Output Screenshot" }, { "code": null, "e": 1004, "s": 896, "text": "Creating a column vector manually: If we want to create a column vector we can just use the following code:" }, { "code": null, "e": 1011, "s": 1004, "text": "Matlab" }, { "code": "% MATLAB code to create a % column vector withe zero'sX = [0; 0; 0; 0; 0]", "e": 1085, "s": 1011, "text": null }, { "code": null, "e": 1135, "s": 1085, "text": "It basically creates a column vector of size 5X1." }, { "code": null, "e": 1143, "s": 1135, "text": "Output:" }, { "code": null, "e": 1161, "s": 1143, "text": "Output Screenshot" }, { "code": null, "e": 1391, "s": 1161, "text": "Creating a (n x m) matrix of zeros: In this section, we are going to create an (n x m) dimensional matrix. For example, let n = 3 and m = 4. Basically, the following line of code will generate a matrix with 3 rows and 4 columns." }, { "code": null, "e": 1398, "s": 1391, "text": "Matlab" }, { "code": "% MATLAB code for create an % (n x m) dimensional matrixX = [0 0 0 0; 0 0 0 0; 0 0 0 0]", "e": 1487, "s": 1398, "text": null }, { "code": null, "e": 1495, "s": 1487, "text": "Output:" }, { "code": null, "e": 1513, "s": 1495, "text": "Output Screenshot" }, { "code": null, "e": 1674, "s": 1513, "text": "There are several matrices and arrays that we can create using the zeros() function. We are going to describe each of them elaborately in the following section:" }, { "code": null, "e": 1695, "s": 1674, "text": "Creating scalar zero" }, { "code": null, "e": 1725, "s": 1695, "text": "Syntax: variable_name = zeros" }, { "code": null, "e": 1796, "s": 1725, "text": "Return value: In this case, the return value is only scalar zero(β€˜0’)." }, { "code": null, "e": 1805, "s": 1796, "text": "Example:" }, { "code": null, "e": 1812, "s": 1805, "text": "Matlab" }, { "code": "% MATLAB Code for Creating scalar zeroX = zeros", "e": 1860, "s": 1812, "text": null }, { "code": null, "e": 1868, "s": 1860, "text": "Output:" }, { "code": null, "e": 1886, "s": 1868, "text": "Output Screenshot" }, { "code": null, "e": 1921, "s": 1886, "text": "Creating a (n x n) matrix of zeros" }, { "code": null, "e": 1981, "s": 1921, "text": "syntax: matrix = zeros(n) // Here n is the size of matrix." }, { "code": null, "e": 2048, "s": 1981, "text": "Return value: zeros(n) function returns a (n x n) matrix of zeros:" }, { "code": null, "e": 2065, "s": 2048, "text": "Input Arguments:" }, { "code": null, "e": 2211, "s": 2065, "text": "Size of square matrix, specified as an integer value.If n is 0 then it returns an empty matrix.If n is negative, it also returns an empty matrix." }, { "code": null, "e": 2265, "s": 2211, "text": "Size of square matrix, specified as an integer value." }, { "code": null, "e": 2308, "s": 2265, "text": "If n is 0 then it returns an empty matrix." }, { "code": null, "e": 2359, "s": 2308, "text": "If n is negative, it also returns an empty matrix." }, { "code": null, "e": 2368, "s": 2359, "text": "Example:" }, { "code": null, "e": 2375, "s": 2368, "text": "Matlab" }, { "code": "% MATLAB code for Creating a (n x n) matrix of zerosmatrix = zeros(3)", "e": 2445, "s": 2375, "text": null }, { "code": null, "e": 2488, "s": 2445, "text": "This code returns a 3 x 3 matrix of zeros." }, { "code": null, "e": 2496, "s": 2488, "text": "Output:" }, { "code": null, "e": 2514, "s": 2496, "text": "Output Screenshot" }, { "code": null, "e": 2568, "s": 2514, "text": "Creating a (sz1 by sz2 by-.......-szn) array of zeros" }, { "code": null, "e": 2615, "s": 2568, "text": "syntax: matrix = zeros(sz1, sz2,.......,szn) " }, { "code": null, "e": 2808, "s": 2615, "text": "Return value: This function returns an sz1-by-...-by-szN array of zeros where sz1,...,szN indicate the size of each dimension. For example, zeros(2, 3, 4) returns a 2 X 3 X 4 matrix of zeros." }, { "code": null, "e": 2826, "s": 2808, "text": "Input Arguments: " }, { "code": null, "e": 3146, "s": 2826, "text": "all the input arguments are specified as an integer value.If any of the argument is 0, it returns an empty matrix.If any of the argument is negative then it is treated as 0.Beyond the second dimension, zeros() ignores trailing dimensions with a size of 1. For example, zeros(4,1,1, 1) produces a 4-by-1 vector of zeros." }, { "code": null, "e": 3205, "s": 3146, "text": "all the input arguments are specified as an integer value." }, { "code": null, "e": 3262, "s": 3205, "text": "If any of the argument is 0, it returns an empty matrix." }, { "code": null, "e": 3322, "s": 3262, "text": "If any of the argument is negative then it is treated as 0." }, { "code": null, "e": 3469, "s": 3322, "text": "Beyond the second dimension, zeros() ignores trailing dimensions with a size of 1. For example, zeros(4,1,1, 1) produces a 4-by-1 vector of zeros." }, { "code": null, "e": 3478, "s": 3469, "text": "Example:" }, { "code": null, "e": 3485, "s": 3478, "text": "Matlab" }, { "code": "% MATLAB Code for 3-d matrix of zerosmatrix = zeros(2, 3, 4)", "e": 3546, "s": 3485, "text": null }, { "code": null, "e": 3599, "s": 3546, "text": "The above code creates a 2-by-3-by-4 array of zeros." }, { "code": null, "e": 3636, "s": 3599, "text": "Creating a matrix of a specific size" }, { "code": null, "e": 3724, "s": 3636, "text": "Syntax: matrix = zeros(sz) // Here sz is the dimension of the matrix in the form [m n]." }, { "code": null, "e": 3862, "s": 3724, "text": "Return value: It returns an array of zeros where size vector sz defines size(matrix). For example, zeros([2 3]) returns a 2-by-3 matrix." }, { "code": null, "e": 3880, "s": 3862, "text": "Input Arguments: " }, { "code": null, "e": 4029, "s": 3880, "text": "Size of each dimension, specified as a row vector of integer values. The rest of the characteristics of this syntax are as same as the previous one." }, { "code": null, "e": 4038, "s": 4029, "text": "Example:" }, { "code": null, "e": 4045, "s": 4038, "text": "Matlab" }, { "code": "% MATLAB Code for clone the size of % another matrixmatrix = zeros([2 3])", "e": 4119, "s": 4045, "text": null }, { "code": null, "e": 4187, "s": 4119, "text": "or we can also clone the size of another matrix like the following:" }, { "code": null, "e": 4194, "s": 4187, "text": "Matlab" }, { "code": "% MATLAB code for clone the another% matrix in different wayA = ones(2, 3);matrix = zeros(size(A))", "e": 4293, "s": 4194, "text": null }, { "code": null, "e": 4373, "s": 4293, "text": "The above code basically returns a matrix of 2 X 3 with zeros as every element." }, { "code": null, "e": 4381, "s": 4373, "text": "Output:" }, { "code": null, "e": 4399, "s": 4381, "text": "Output Screenshot" }, { "code": null, "e": 4438, "s": 4399, "text": "Creating specified data types of zeros" }, { "code": null, "e": 4537, "s": 4438, "text": "syntax: matrix = zeros(___,typename) // Here the first argument may be any of the previous types." }, { "code": null, "e": 4625, "s": 4537, "text": "Return value: It returns an array of zeros of the specified data type named typename." }, { "code": null, "e": 4643, "s": 4625, "text": "Input Arguments: " }, { "code": null, "e": 4847, "s": 4643, "text": "Data type (class) to create, specified as β€˜double’, β€˜single’, β€˜logical’,’int8β€², β€˜uint8’, β€˜int16’, β€˜uint16’, β€˜int32’, β€˜uint32’, β€˜int64’, β€˜uint64’, or the name of another class that provides zeros support." }, { "code": null, "e": 4856, "s": 4847, "text": "Example:" }, { "code": null, "e": 4863, "s": 4856, "text": "Matlab" }, { "code": "% CodeA = ones(2, 3);matrix = zeros(size(A), 'uint32')", "e": 4918, "s": 4863, "text": null }, { "code": null, "e": 4974, "s": 4918, "text": "This code creates a 2-by-3 matrix of datatype β€˜uint32’." }, { "code": null, "e": 4982, "s": 4974, "text": "Output:" }, { "code": null, "e": 5000, "s": 4982, "text": "Output Screenshot" }, { "code": null, "e": 5046, "s": 5000, "text": "Creating matrix using a prototype of an array" }, { "code": null, "e": 5145, "s": 5046, "text": "syntax: matrix = zeros(___,’like’,p) // Here the first argument may be any of the previous types." }, { "code": null, "e": 5337, "s": 5145, "text": "Return value: It returns an array of zeros like p; i.e, of the same data type (class), sparsity, and complexity (real or complex) as p. The user can specify typename or β€˜like’, but not both." }, { "code": null, "e": 5354, "s": 5337, "text": "Input Arguments:" }, { "code": null, "e": 5407, "s": 5354, "text": "Prototype of array to create, specified as an array." }, { "code": null, "e": 5415, "s": 5407, "text": "Example" }, { "code": null, "e": 5422, "s": 5415, "text": "Matlab" }, { "code": "% MATLAB Code for clone complexity% of an arrayp = [2+2i 13i];X = zeros('like',p)", "e": 5504, "s": 5422, "text": null }, { "code": null, "e": 5516, "s": 5504, "text": "Output: " }, { "code": null, "e": 5525, "s": 5516, "text": "Example:" }, { "code": null, "e": 5532, "s": 5525, "text": "Matlab" }, { "code": "% MATLAB code for clone Size and% Data Type from Existing Array p = uint8([4 5 6; 14 15 16; 12 13 14]);matrix = zeros(size(p),'like',p)", "e": 5668, "s": 5532, "text": null }, { "code": null, "e": 5676, "s": 5668, "text": "Output:" }, { "code": null, "e": 5683, "s": 5676, "text": "Picked" }, { "code": null, "e": 5690, "s": 5683, "text": "MATLAB" } ]
Python – Replace vowels by next vowel
14 Oct, 2020 Given a String replace each vowel with next vowel in series. Input : test_str = β€˜geekforgeeks’Output : giikfurgiiksExplanation : After e, next vowel is i, all e replaced by i. Input : test_str = β€˜geekforgeeks is best’Output : giikfurgiiks os bistExplanation : After e, next vowel is i, all e replaced by i. Method #1 : Using zip() + list comprehension This is one of the ways in which this task can be performed. In this we perform the task of forming replace dictionary using zip() and then list comprehension is used to perform the task of replacement with next vowel. Python3 # Python3 code to demonstrate working of # Replace vowels by next vowel# Using list comprehension + zip() # initializing stringtest_str = 'geekforgeeks' # printing original stringprint("The original string is : " + str(test_str)) # constructing dictionary using zip()vow = 'a e i o u'.split()temp = dict(zip(vow, vow[1:] + [vow[0]])) # list comprehension to perform replacementres = "".join([temp.get(ele, ele) for ele in test_str]) # printing result print("The replaced string : " + str(res)) The original string is : geekforgeeks The replaced string : giikfurgiiks Method #2 : Using dictionary comprehension + list comprehension This is yet another way in which this task can be performed. In this we perform the task of mapping using dictionary comprehension and list comprehension is used to perform task of replacement. Python3 # Python3 code to demonstrate working of # Replace vowels by next vowel# Using list comprehension + dictionary comprehension # initializing stringtest_str = 'geekforgeeks' # printing original stringprint("The original string is : " + str(test_str)) # constructing dictionary using dictionary comprehensionvow = "aeiou"temp = {vow[idx] : vow[(idx + 1) % len(vow)] for idx in range(len(vow))} # using get() to map elements to dictionary and join to convertres = "".join([temp.get(ele, ele) for ele in test_str]) # printing result print("The replaced string : " + str(res)) The original string is : geekforgeeks The replaced string : giikfurgiiks Python string-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": "\n14 Oct, 2020" }, { "code": null, "e": 89, "s": 28, "text": "Given a String replace each vowel with next vowel in series." }, { "code": null, "e": 204, "s": 89, "text": "Input : test_str = β€˜geekforgeeks’Output : giikfurgiiksExplanation : After e, next vowel is i, all e replaced by i." }, { "code": null, "e": 335, "s": 204, "text": "Input : test_str = β€˜geekforgeeks is best’Output : giikfurgiiks os bistExplanation : After e, next vowel is i, all e replaced by i." }, { "code": null, "e": 380, "s": 335, "text": "Method #1 : Using zip() + list comprehension" }, { "code": null, "e": 599, "s": 380, "text": "This is one of the ways in which this task can be performed. In this we perform the task of forming replace dictionary using zip() and then list comprehension is used to perform the task of replacement with next vowel." }, { "code": null, "e": 607, "s": 599, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Replace vowels by next vowel# Using list comprehension + zip() # initializing stringtest_str = 'geekforgeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # constructing dictionary using zip()vow = 'a e i o u'.split()temp = dict(zip(vow, vow[1:] + [vow[0]])) # list comprehension to perform replacementres = \"\".join([temp.get(ele, ele) for ele in test_str]) # printing result print(\"The replaced string : \" + str(res)) ", "e": 1107, "s": 607, "text": null }, { "code": null, "e": 1181, "s": 1107, "text": "The original string is : geekforgeeks\nThe replaced string : giikfurgiiks\n" }, { "code": null, "e": 1245, "s": 1181, "text": "Method #2 : Using dictionary comprehension + list comprehension" }, { "code": null, "e": 1439, "s": 1245, "text": "This is yet another way in which this task can be performed. In this we perform the task of mapping using dictionary comprehension and list comprehension is used to perform task of replacement." }, { "code": null, "e": 1447, "s": 1439, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Replace vowels by next vowel# Using list comprehension + dictionary comprehension # initializing stringtest_str = 'geekforgeeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # constructing dictionary using dictionary comprehensionvow = \"aeiou\"temp = {vow[idx] : vow[(idx + 1) % len(vow)] for idx in range(len(vow))} # using get() to map elements to dictionary and join to convertres = \"\".join([temp.get(ele, ele) for ele in test_str]) # printing result print(\"The replaced string : \" + str(res)) ", "e": 2024, "s": 1447, "text": null }, { "code": null, "e": 2098, "s": 2024, "text": "The original string is : geekforgeeks\nThe replaced string : giikfurgiiks\n" }, { "code": null, "e": 2121, "s": 2098, "text": "Python string-programs" }, { "code": null, "e": 2128, "s": 2121, "text": "Python" }, { "code": null, "e": 2144, "s": 2128, "text": "Python Programs" } ]
How to iterate through a Vector without using Iterators in C++
01 Jun, 2020 Prerequisite: C++ STL, Iterators in C++ STL The iterator is not the only way to iterate through any STL container. There exists a better and efficient way to iterate through vector without using iterators. It can be iterated using the values stored in any container. Below is the syntax for the same for vectors: Syntax: for(auto itr : vector_name) Explanation: Here itr is the value stored in vector which is used to traverse vectors. Below is the program to illustrate the same: // C++ program to illustrate the above// topic#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the vector vector<int> arr = { 1, 2, 3, 4 }; // Traversing the vector using // values directly for (auto& it : arr) { // Print the values cout << it << ' '; } return 0;} 1 2 3 4 Updating values in vector: For updating values in a vector without using iterators traverse the values stored in vector using reference and updated the value. Below is the syntax for the same: Syntax: for(auto &itr : vector_name) Explanation: Here itr is an address to the value stored in vector which is used to traverse vectors. Below is the program to illustrate the same: // C++ program to illustrate the updation// in vector without using iterator#include <bits/stdc++.h>using namespace std; // Function to update the value in vectorvoid updateVector(vector<int> arr){ cout << "Vector Before Update: "; for (auto& it : arr) { cout << it << ' '; } // Traverse using the reference to value // and multiply each value by 2 for (auto& it : arr) { it *= 2; } cout << "\nVector After Update: "; // Print vector elements for (auto& it : arr) { cout << it << ' '; }} // Driver Codeint main(){ // Declare the vector vector<int> arr = { 1, 2, 3, 4 }; // Function Call updateVector(arr); return 0;} Vector Before Update: 1 2 3 4 Vector After Update: 2 4 6 8 Advantages: Simple and easy to write code. Better and efficient than using iterators method. Disadvantages: It iterates only in forward direction. Keeps no counter i.e., We cannot find the index of any element with this traversal. For counting the element, the counter have to taken explicitly. We can also iterate using the same traversal in many different Containers in C++. Below are the illustration for the same: Map:// C++ program to illustrate the iteration// in Map without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map map<int, int> Mp; // Inserting values in Map Mp[1] = 1; Mp[2] = 2; Mp[3] = 3; // Iterate using value in Map for (auto it : Mp) { // Print the elements cout << it.first << ' ' << it.second << endl; } return 0;}Output:1 1 2 2 3 3 Map of Vectors:// C++ program to illustrate the iteration// in Map of vectors without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map of vectors map<int, vector<int> > Mp; // Temporary vector vector<int> temp = { 1, 2, 3 }; // Inserting values in Map Mp[1] = temp; temp = { 2, 3, 8, 9 }; Mp[2] = temp; temp = { 10, -2 }; Mp[3] = temp; // Iterate using value in Map of vectors for (auto it : Mp) { // Print the elements cout << it.first << " -> "; // Traverse each vector map // with it.first and print the // elements for (auto jt : it.second) { cout << jt << ' '; } cout << endl; } return 0;}Output:1 -> 1 2 3 2 -> 2 3 8 9 3 -> 10 -2 Set:// C++ program to illustrate the iteration// in set without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the set set<int> S; // Inserting values in set S.insert(3); S.insert(-1); S.insert(3); S.insert(4); // Iterate using value in set for (auto it : S) { // Print the elements cout << it << ' '; } return 0;}Output:-1 3 4 Deque:// C++ program to illustrate the iteration// in deque without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the deque deque<int> dq; // Inserting values in deque dq.push_front(1); dq.push_front(2); dq.push_front(3); dq.push_back(4); dq.push_back(5); // Iterate using value in set for (auto it : dq) { // Print the elements cout << it << ' '; } return 0;}Output:3 2 1 4 5 Map:// C++ program to illustrate the iteration// in Map without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map map<int, int> Mp; // Inserting values in Map Mp[1] = 1; Mp[2] = 2; Mp[3] = 3; // Iterate using value in Map for (auto it : Mp) { // Print the elements cout << it.first << ' ' << it.second << endl; } return 0;}Output:1 1 2 2 3 3 // C++ program to illustrate the iteration// in Map without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map map<int, int> Mp; // Inserting values in Map Mp[1] = 1; Mp[2] = 2; Mp[3] = 3; // Iterate using value in Map for (auto it : Mp) { // Print the elements cout << it.first << ' ' << it.second << endl; } return 0;} 1 1 2 2 3 3 Map of Vectors:// C++ program to illustrate the iteration// in Map of vectors without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map of vectors map<int, vector<int> > Mp; // Temporary vector vector<int> temp = { 1, 2, 3 }; // Inserting values in Map Mp[1] = temp; temp = { 2, 3, 8, 9 }; Mp[2] = temp; temp = { 10, -2 }; Mp[3] = temp; // Iterate using value in Map of vectors for (auto it : Mp) { // Print the elements cout << it.first << " -> "; // Traverse each vector map // with it.first and print the // elements for (auto jt : it.second) { cout << jt << ' '; } cout << endl; } return 0;}Output:1 -> 1 2 3 2 -> 2 3 8 9 3 -> 10 -2 // C++ program to illustrate the iteration// in Map of vectors without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map of vectors map<int, vector<int> > Mp; // Temporary vector vector<int> temp = { 1, 2, 3 }; // Inserting values in Map Mp[1] = temp; temp = { 2, 3, 8, 9 }; Mp[2] = temp; temp = { 10, -2 }; Mp[3] = temp; // Iterate using value in Map of vectors for (auto it : Mp) { // Print the elements cout << it.first << " -> "; // Traverse each vector map // with it.first and print the // elements for (auto jt : it.second) { cout << jt << ' '; } cout << endl; } return 0;} 1 -> 1 2 3 2 -> 2 3 8 9 3 -> 10 -2 Set:// C++ program to illustrate the iteration// in set without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the set set<int> S; // Inserting values in set S.insert(3); S.insert(-1); S.insert(3); S.insert(4); // Iterate using value in set for (auto it : S) { // Print the elements cout << it << ' '; } return 0;}Output:-1 3 4 // C++ program to illustrate the iteration// in set without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the set set<int> S; // Inserting values in set S.insert(3); S.insert(-1); S.insert(3); S.insert(4); // Iterate using value in set for (auto it : S) { // Print the elements cout << it << ' '; } return 0;} -1 3 4 Deque:// C++ program to illustrate the iteration// in deque without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the deque deque<int> dq; // Inserting values in deque dq.push_front(1); dq.push_front(2); dq.push_front(3); dq.push_back(4); dq.push_back(5); // Iterate using value in set for (auto it : dq) { // Print the elements cout << it << ' '; } return 0;}Output:3 2 1 4 5 // C++ program to illustrate the iteration// in deque without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the deque deque<int> dq; // Inserting values in deque dq.push_front(1); dq.push_front(2); dq.push_front(3); dq.push_back(4); dq.push_back(5); // Iterate using value in set for (auto it : dq) { // Print the elements cout << it << ' '; } return 0;} 3 2 1 4 5 cpp-containers-library cpp-iterator CPP-Library cpp-map cpp-vector STL Traversal C++ C++ Programs Traversal STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2020" }, { "code": null, "e": 96, "s": 52, "text": "Prerequisite: C++ STL, Iterators in C++ STL" }, { "code": null, "e": 365, "s": 96, "text": "The iterator is not the only way to iterate through any STL container. There exists a better and efficient way to iterate through vector without using iterators. It can be iterated using the values stored in any container. Below is the syntax for the same for vectors:" }, { "code": null, "e": 373, "s": 365, "text": "Syntax:" }, { "code": null, "e": 402, "s": 373, "text": "for(auto itr : vector_name)\n" }, { "code": null, "e": 534, "s": 402, "text": "Explanation: Here itr is the value stored in vector which is used to traverse vectors. Below is the program to illustrate the same:" }, { "code": "// C++ program to illustrate the above// topic#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the vector vector<int> arr = { 1, 2, 3, 4 }; // Traversing the vector using // values directly for (auto& it : arr) { // Print the values cout << it << ' '; } return 0;}", "e": 874, "s": 534, "text": null }, { "code": null, "e": 883, "s": 874, "text": "1 2 3 4\n" }, { "code": null, "e": 1076, "s": 883, "text": "Updating values in vector: For updating values in a vector without using iterators traverse the values stored in vector using reference and updated the value. Below is the syntax for the same:" }, { "code": null, "e": 1084, "s": 1076, "text": "Syntax:" }, { "code": null, "e": 1114, "s": 1084, "text": "for(auto &itr : vector_name)\n" }, { "code": null, "e": 1260, "s": 1114, "text": "Explanation: Here itr is an address to the value stored in vector which is used to traverse vectors. Below is the program to illustrate the same:" }, { "code": "// C++ program to illustrate the updation// in vector without using iterator#include <bits/stdc++.h>using namespace std; // Function to update the value in vectorvoid updateVector(vector<int> arr){ cout << \"Vector Before Update: \"; for (auto& it : arr) { cout << it << ' '; } // Traverse using the reference to value // and multiply each value by 2 for (auto& it : arr) { it *= 2; } cout << \"\\nVector After Update: \"; // Print vector elements for (auto& it : arr) { cout << it << ' '; }} // Driver Codeint main(){ // Declare the vector vector<int> arr = { 1, 2, 3, 4 }; // Function Call updateVector(arr); return 0;}", "e": 1958, "s": 1260, "text": null }, { "code": null, "e": 2019, "s": 1958, "text": "Vector Before Update: 1 2 3 4 \nVector After Update: 2 4 6 8\n" }, { "code": null, "e": 2031, "s": 2019, "text": "Advantages:" }, { "code": null, "e": 2062, "s": 2031, "text": "Simple and easy to write code." }, { "code": null, "e": 2112, "s": 2062, "text": "Better and efficient than using iterators method." }, { "code": null, "e": 2127, "s": 2112, "text": "Disadvantages:" }, { "code": null, "e": 2166, "s": 2127, "text": "It iterates only in forward direction." }, { "code": null, "e": 2314, "s": 2166, "text": "Keeps no counter i.e., We cannot find the index of any element with this traversal. For counting the element, the counter have to taken explicitly." }, { "code": null, "e": 2437, "s": 2314, "text": "We can also iterate using the same traversal in many different Containers in C++. Below are the illustration for the same:" }, { "code": null, "e": 4643, "s": 2437, "text": "Map:// C++ program to illustrate the iteration// in Map without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map map<int, int> Mp; // Inserting values in Map Mp[1] = 1; Mp[2] = 2; Mp[3] = 3; // Iterate using value in Map for (auto it : Mp) { // Print the elements cout << it.first << ' ' << it.second << endl; } return 0;}Output:1 1\n2 2\n3 3\nMap of Vectors:// C++ program to illustrate the iteration// in Map of vectors without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map of vectors map<int, vector<int> > Mp; // Temporary vector vector<int> temp = { 1, 2, 3 }; // Inserting values in Map Mp[1] = temp; temp = { 2, 3, 8, 9 }; Mp[2] = temp; temp = { 10, -2 }; Mp[3] = temp; // Iterate using value in Map of vectors for (auto it : Mp) { // Print the elements cout << it.first << \" -> \"; // Traverse each vector map // with it.first and print the // elements for (auto jt : it.second) { cout << jt << ' '; } cout << endl; } return 0;}Output:1 -> 1 2 3 \n2 -> 2 3 8 9 \n3 -> 10 -2\nSet:// C++ program to illustrate the iteration// in set without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the set set<int> S; // Inserting values in set S.insert(3); S.insert(-1); S.insert(3); S.insert(4); // Iterate using value in set for (auto it : S) { // Print the elements cout << it << ' '; } return 0;}Output:-1 3 4\nDeque:// C++ program to illustrate the iteration// in deque without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the deque deque<int> dq; // Inserting values in deque dq.push_front(1); dq.push_front(2); dq.push_front(3); dq.push_back(4); dq.push_back(5); // Iterate using value in set for (auto it : dq) { // Print the elements cout << it << ' '; } return 0;}Output:3 2 1 4 5\n" }, { "code": null, "e": 5107, "s": 4643, "text": "Map:// C++ program to illustrate the iteration// in Map without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map map<int, int> Mp; // Inserting values in Map Mp[1] = 1; Mp[2] = 2; Mp[3] = 3; // Iterate using value in Map for (auto it : Mp) { // Print the elements cout << it.first << ' ' << it.second << endl; } return 0;}Output:1 1\n2 2\n3 3\n" }, { "code": "// C++ program to illustrate the iteration// in Map without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map map<int, int> Mp; // Inserting values in Map Mp[1] = 1; Mp[2] = 2; Mp[3] = 3; // Iterate using value in Map for (auto it : Mp) { // Print the elements cout << it.first << ' ' << it.second << endl; } return 0;}", "e": 5548, "s": 5107, "text": null }, { "code": null, "e": 5561, "s": 5548, "text": "1 1\n2 2\n3 3\n" }, { "code": null, "e": 6385, "s": 5561, "text": "Map of Vectors:// C++ program to illustrate the iteration// in Map of vectors without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map of vectors map<int, vector<int> > Mp; // Temporary vector vector<int> temp = { 1, 2, 3 }; // Inserting values in Map Mp[1] = temp; temp = { 2, 3, 8, 9 }; Mp[2] = temp; temp = { 10, -2 }; Mp[3] = temp; // Iterate using value in Map of vectors for (auto it : Mp) { // Print the elements cout << it.first << \" -> \"; // Traverse each vector map // with it.first and print the // elements for (auto jt : it.second) { cout << jt << ' '; } cout << endl; } return 0;}Output:1 -> 1 2 3 \n2 -> 2 3 8 9 \n3 -> 10 -2\n" }, { "code": "// C++ program to illustrate the iteration// in Map of vectors without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the map of vectors map<int, vector<int> > Mp; // Temporary vector vector<int> temp = { 1, 2, 3 }; // Inserting values in Map Mp[1] = temp; temp = { 2, 3, 8, 9 }; Mp[2] = temp; temp = { 10, -2 }; Mp[3] = temp; // Iterate using value in Map of vectors for (auto it : Mp) { // Print the elements cout << it.first << \" -> \"; // Traverse each vector map // with it.first and print the // elements for (auto jt : it.second) { cout << jt << ' '; } cout << endl; } return 0;}", "e": 7150, "s": 6385, "text": null }, { "code": null, "e": 7188, "s": 7150, "text": "1 -> 1 2 3 \n2 -> 2 3 8 9 \n3 -> 10 -2\n" }, { "code": null, "e": 7622, "s": 7188, "text": "Set:// C++ program to illustrate the iteration// in set without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the set set<int> S; // Inserting values in set S.insert(3); S.insert(-1); S.insert(3); S.insert(4); // Iterate using value in set for (auto it : S) { // Print the elements cout << it << ' '; } return 0;}Output:-1 3 4\n" }, { "code": "// C++ program to illustrate the iteration// in set without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the set set<int> S; // Inserting values in set S.insert(3); S.insert(-1); S.insert(3); S.insert(4); // Iterate using value in set for (auto it : S) { // Print the elements cout << it << ' '; } return 0;}", "e": 8038, "s": 7622, "text": null }, { "code": null, "e": 8046, "s": 8038, "text": "-1 3 4\n" }, { "code": null, "e": 8533, "s": 8046, "text": "Deque:// C++ program to illustrate the iteration// in deque without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the deque deque<int> dq; // Inserting values in deque dq.push_front(1); dq.push_front(2); dq.push_front(3); dq.push_back(4); dq.push_back(5); // Iterate using value in set for (auto it : dq) { // Print the elements cout << it << ' '; } return 0;}Output:3 2 1 4 5\n" }, { "code": "// C++ program to illustrate the iteration// in deque without using iterator#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // Declare the deque deque<int> dq; // Inserting values in deque dq.push_front(1); dq.push_front(2); dq.push_front(3); dq.push_back(4); dq.push_back(5); // Iterate using value in set for (auto it : dq) { // Print the elements cout << it << ' '; } return 0;}", "e": 8997, "s": 8533, "text": null }, { "code": null, "e": 9008, "s": 8997, "text": "3 2 1 4 5\n" }, { "code": null, "e": 9031, "s": 9008, "text": "cpp-containers-library" }, { "code": null, "e": 9044, "s": 9031, "text": "cpp-iterator" }, { "code": null, "e": 9056, "s": 9044, "text": "CPP-Library" }, { "code": null, "e": 9064, "s": 9056, "text": "cpp-map" }, { "code": null, "e": 9075, "s": 9064, "text": "cpp-vector" }, { "code": null, "e": 9079, "s": 9075, "text": "STL" }, { "code": null, "e": 9089, "s": 9079, "text": "Traversal" }, { "code": null, "e": 9093, "s": 9089, "text": "C++" }, { "code": null, "e": 9106, "s": 9093, "text": "C++ Programs" }, { "code": null, "e": 9116, "s": 9106, "text": "Traversal" }, { "code": null, "e": 9120, "s": 9116, "text": "STL" }, { "code": null, "e": 9124, "s": 9120, "text": "CPP" } ]
NumPy – 3D matrix multiplication
12 Nov, 2020 A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors. Let us consider an example matrix A of shape (3,3,2) multiplied with another 3D matrix B of shape (3,2,4). Python import numpy as np np.random.seed(42) A = np.random.randint(0, 10, size=(3, 3, 2))B = np.random.randint(0, 10, size=(3, 2, 4)) print("A:\n{}, shape={}\nB:\n{}, shape={}".format( A, A.shape, B, B.shape)) OUTPUT: The first matrix is a stack of three 2D matrices each of shape (3,2), and the second matrix is a stack of 3 2D matrices, each of shape (2,4). The matrix multiplication between these two will involve three multiplications between corresponding 2D matrices of A and B having shapes (3,2) and (2,4) respectively. Specifically, the first multiplication will be between A[0] and B[0], the second multiplication will be between A[1] and B[1], and finally, the third multiplication will be between A[2] and B[2]. The result of each individual multiplication of 2D matrices will be of shape (3,4). Hence, the final product of the two 3D matrices will be a matrix of shape (3,3,4). Let’s realize this using code. Python C = np.matmul(A, B) print("Product C:\n{}, shape={}".format(C, C.shape)) Output: Python numpy-Linear Algebra Python-numpy 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 Python | os.path.join() method 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 Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Nov, 2020" }, { "code": null, "e": 364, "s": 52, "text": "A 3D matrix is nothing but a collection (or a stack) of many 2D matrices, just like how a 2D matrix is a collection/stack of many 1D vectors. So, matrix multiplication of 3D matrices involves multiple multiplications of 2D matrices, which eventually boils down to a dot product between their row/column vectors." }, { "code": null, "e": 471, "s": 364, "text": "Let us consider an example matrix A of shape (3,3,2) multiplied with another 3D matrix B of shape (3,2,4)." }, { "code": null, "e": 478, "s": 471, "text": "Python" }, { "code": "import numpy as np np.random.seed(42) A = np.random.randint(0, 10, size=(3, 3, 2))B = np.random.randint(0, 10, size=(3, 2, 4)) print(\"A:\\n{}, shape={}\\nB:\\n{}, shape={}\".format( A, A.shape, B, B.shape))", "e": 685, "s": 478, "text": null }, { "code": null, "e": 693, "s": 685, "text": "OUTPUT:" }, { "code": null, "e": 835, "s": 693, "text": "The first matrix is a stack of three 2D matrices each of shape (3,2), and the second matrix is a stack of 3 2D matrices, each of shape (2,4)." }, { "code": null, "e": 1366, "s": 835, "text": "The matrix multiplication between these two will involve three multiplications between corresponding 2D matrices of A and B having shapes (3,2) and (2,4) respectively. Specifically, the first multiplication will be between A[0] and B[0], the second multiplication will be between A[1] and B[1], and finally, the third multiplication will be between A[2] and B[2]. The result of each individual multiplication of 2D matrices will be of shape (3,4). Hence, the final product of the two 3D matrices will be a matrix of shape (3,3,4)." }, { "code": null, "e": 1397, "s": 1366, "text": "Let’s realize this using code." }, { "code": null, "e": 1404, "s": 1397, "text": "Python" }, { "code": "C = np.matmul(A, B) print(\"Product C:\\n{}, shape={}\".format(C, C.shape))", "e": 1478, "s": 1404, "text": null }, { "code": null, "e": 1486, "s": 1478, "text": "Output:" }, { "code": null, "e": 1514, "s": 1486, "text": "Python numpy-Linear Algebra" }, { "code": null, "e": 1527, "s": 1514, "text": "Python-numpy" }, { "code": null, "e": 1534, "s": 1527, "text": "Python" }, { "code": null, "e": 1632, "s": 1534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1664, "s": 1632, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1691, "s": 1664, "text": "Python Classes and Objects" }, { "code": null, "e": 1712, "s": 1691, "text": "Python OOPs Concepts" }, { "code": null, "e": 1735, "s": 1712, "text": "Introduction To PYTHON" }, { "code": null, "e": 1766, "s": 1735, "text": "Python | os.path.join() method" }, { "code": null, "e": 1822, "s": 1766, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1864, "s": 1822, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1906, "s": 1864, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1945, "s": 1906, "text": "Python | Get unique values from a list" } ]
numpy matrix operations | repmat() function
21 Feb, 2019 numpy.matlib.repmat() is another function for doing matrix operations in numpy. It returns Repeat a 0-D, 1-D or 2-D array or matrix M x N times. Syntax : numpy.matlib.repmat(a, m, n) Parameters :a : [array_like] The input array or matrix which to be repeated.m, n : [int] The number of times a is repeated along the first and second axes. Return : [ndarray] repeating array. Code #1 : # Python program explaining# numpy.matlib.repmat() function # importing numpy and matrix libraryimport numpy as geekimport numpy.matlib # creating input array using # array function in_arr = geek.array([[1, 0, 2], [3, 4, 5]])print("Input array", in_arr) # making a new array # using repmat() function out_mat = geek.matlib.repmat(in_arr, 2, 3) print ("Output repeated matrix : ", out_mat) Input array [[1 0 2] [3 4 5]] Output repeated matrix : [[1 0 2 1 0 2 1 0 2] [3 4 5 3 4 5 3 4 5] [1 0 2 1 0 2 1 0 2] [3 4 5 3 4 5 3 4 5]] Code #2 : # Python program explaining# numpy.matlib.repmat() function # importing numpy and matrix libraryimport numpy as geekimport numpy.matlib # creating input array using # arange function in_arr = geek.arange(3)print("Input array", in_arr) # making a new array # using repmat() function out_mat = geek.matlib.repmat(in_arr, 2, 2) print ("Output repeated matrix : ", out_mat) Input array [0 1 2] Output repeated matrix : [[0 1 2 0 1 2] [0 1 2 0 1 2]] Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 173, "s": 28, "text": "numpy.matlib.repmat() is another function for doing matrix operations in numpy. It returns Repeat a 0-D, 1-D or 2-D array or matrix M x N times." }, { "code": null, "e": 211, "s": 173, "text": "Syntax : numpy.matlib.repmat(a, m, n)" }, { "code": null, "e": 367, "s": 211, "text": "Parameters :a : [array_like] The input array or matrix which to be repeated.m, n : [int] The number of times a is repeated along the first and second axes." }, { "code": null, "e": 403, "s": 367, "text": "Return : [ndarray] repeating array." }, { "code": null, "e": 413, "s": 403, "text": "Code #1 :" }, { "code": "# Python program explaining# numpy.matlib.repmat() function # importing numpy and matrix libraryimport numpy as geekimport numpy.matlib # creating input array using # array function in_arr = geek.array([[1, 0, 2], [3, 4, 5]])print(\"Input array\", in_arr) # making a new array # using repmat() function out_mat = geek.matlib.repmat(in_arr, 2, 3) print (\"Output repeated matrix : \", out_mat) ", "e": 808, "s": 413, "text": null }, { "code": null, "e": 951, "s": 808, "text": "Input array [[1 0 2]\n [3 4 5]]\nOutput repeated matrix : [[1 0 2 1 0 2 1 0 2]\n [3 4 5 3 4 5 3 4 5]\n [1 0 2 1 0 2 1 0 2]\n [3 4 5 3 4 5 3 4 5]]\n" }, { "code": null, "e": 963, "s": 953, "text": "Code #2 :" }, { "code": "# Python program explaining# numpy.matlib.repmat() function # importing numpy and matrix libraryimport numpy as geekimport numpy.matlib # creating input array using # arange function in_arr = geek.arange(3)print(\"Input array\", in_arr) # making a new array # using repmat() function out_mat = geek.matlib.repmat(in_arr, 2, 2) print (\"Output repeated matrix : \", out_mat) ", "e": 1339, "s": 963, "text": null }, { "code": null, "e": 1417, "s": 1339, "text": "Input array [0 1 2]\nOutput repeated matrix : [[0 1 2 0 1 2]\n [0 1 2 0 1 2]]\n" }, { "code": null, "e": 1446, "s": 1417, "text": "Python numpy-Matrix Function" }, { "code": null, "e": 1459, "s": 1446, "text": "Python-numpy" }, { "code": null, "e": 1466, "s": 1459, "text": "Python" } ]
Function Interface in Java with Examples
08 Dec, 2021 The Function Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. Hence this functional interface takes in 2 generics namely as follows: T: denotes the type of the input argument R: denotes the return type of the function The lambda expression assigned to an object of Function type is used to define its apply() which eventually applies the given function on the argument. The Function interface consists of the following 4 methods as listed which are later discussed as follows: apply()andThen()compose()identity() apply() andThen() compose() identity() Method 1: apply() Syntax: R apply(T t) Parameters: This method takes in only one parameter t which is the function argument Return Type: This method returns the function result which is of type R. Example Java // Java Program to Illustrate Functional Interface// Via apply() method // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number // and returns half of it Function<Integer, Double> half = a -> a / 2.0; // Applying the function to get the result System.out.println(half.apply(10)); }} 5.0 Method 2: andThen() It returns a composed function wherein the parameterized function will be executed after the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed function. Syntax: default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) where V is the type of output of the after function, and of the composed function Parameters: This method accepts a parameter after which is the function to be applied after the current one.\ Return Value: This method returns a composed function that applies the current function first and then the after function Exception: This method throws NullPointerException if the after function is null. Example 1: Java // Java Program to illustrate addThen() method // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG { // main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // Now treble the output of half function half = half.andThen(a -> 3 * a); // Applying the function to get the result // and printing on console System.out.println(half.apply(10)); }} 15.0 Example 2: To demonstrate when NullPointerException is returned. Java // Java Program to illustrate addThen() method// When NullPointerException occurs // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // Try block to check for exce3ptions try { // Trying to pass null as parameter half = half.andThen(null); } // Catch block to handle exceptions catch (Exception e) { // Print statement System.out.println("Exception thrown " + "while passing null: " + e); } }} Exception thrown while passing null: java.lang.NullPointerException Method 3: compose() It returns a composed function wherein the parameterized function will be executed first and then the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed function. Syntax: default <V> Function<V, R> compose(Function<? super V, ? extends T> before) Where V is the type of input of the before function, and of the composed function Parameters: This method accepts a parameter before which is the function to be applied first and then the current one Return Value: This method returns a composed function that applies the current function after the parameterized function Exception: This method throws NullPointerException if the before function is null. Example 1: Java // Java Program to illustrate compose() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // However treble the value given to half function half = half.compose(a -> 3 * a); // Applying the function to get the result System.out.println(half.apply(5)); }} 7.5 Example 2: When NullPointerException is returned. Java // Java Program to illustrate compose() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // Try bloc kto check for exceptions try { // Trying to pass null as parameter half = half.compose(null); } // Catch block to handle exceptions catch (Exception e) { // Print statement System.out.println("Exception thrown " + "while passing null: " + e); } }} Exception thrown while passing null: java.lang.NullPointerException Method 4: identity() This method returns a function that returns its only argument. Syntax: static <T> Function<T, T> identity() where T denotes the type of the argument and the value to be returned Returns: This method returns a function that returns its own argument Example Java // Java Program to Illustrate identity() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns it Function<Integer, Integer> i = Function.identity(); // Print statement System.out.println(i.apply(10)); }} 10 hristinag popliparul20 sumitgumber28 Java - util package Java 8 java-basics Java-Functions java-interfaces 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 How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Dec, 2021" }, { "code": null, "e": 353, "s": 54, "text": "The Function Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in one argument and produces a result. Hence this functional interface takes in 2 generics namely as follows:" }, { "code": null, "e": 395, "s": 353, "text": "T: denotes the type of the input argument" }, { "code": null, "e": 438, "s": 395, "text": "R: denotes the return type of the function" }, { "code": null, "e": 591, "s": 438, "text": "The lambda expression assigned to an object of Function type is used to define its apply() which eventually applies the given function on the argument. " }, { "code": null, "e": 698, "s": 591, "text": "The Function interface consists of the following 4 methods as listed which are later discussed as follows:" }, { "code": null, "e": 734, "s": 698, "text": "apply()andThen()compose()identity()" }, { "code": null, "e": 742, "s": 734, "text": "apply()" }, { "code": null, "e": 752, "s": 742, "text": "andThen()" }, { "code": null, "e": 762, "s": 752, "text": "compose()" }, { "code": null, "e": 773, "s": 762, "text": "identity()" }, { "code": null, "e": 791, "s": 773, "text": "Method 1: apply()" }, { "code": null, "e": 800, "s": 791, "text": "Syntax: " }, { "code": null, "e": 813, "s": 800, "text": "R apply(T t)" }, { "code": null, "e": 898, "s": 813, "text": "Parameters: This method takes in only one parameter t which is the function argument" }, { "code": null, "e": 971, "s": 898, "text": "Return Type: This method returns the function result which is of type R." }, { "code": null, "e": 980, "s": 971, "text": "Example " }, { "code": null, "e": 985, "s": 980, "text": "Java" }, { "code": "// Java Program to Illustrate Functional Interface// Via apply() method // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number // and returns half of it Function<Integer, Double> half = a -> a / 2.0; // Applying the function to get the result System.out.println(half.apply(10)); }}", "e": 1450, "s": 985, "text": null }, { "code": null, "e": 1454, "s": 1450, "text": "5.0" }, { "code": null, "e": 1474, "s": 1454, "text": "Method 2: andThen()" }, { "code": null, "e": 1682, "s": 1474, "text": "It returns a composed function wherein the parameterized function will be executed after the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed function." }, { "code": null, "e": 1692, "s": 1682, "text": "Syntax: " }, { "code": null, "e": 1768, "s": 1692, "text": "default <V> Function<T, V> \nandThen(Function<? super R, ? extends V> after)" }, { "code": null, "e": 1850, "s": 1768, "text": "where V is the type of output of the after function, and of the composed function" }, { "code": null, "e": 1960, "s": 1850, "text": "Parameters: This method accepts a parameter after which is the function to be applied after the current one.\\" }, { "code": null, "e": 2082, "s": 1960, "text": "Return Value: This method returns a composed function that applies the current function first and then the after function" }, { "code": null, "e": 2164, "s": 2082, "text": "Exception: This method throws NullPointerException if the after function is null." }, { "code": null, "e": 2175, "s": 2164, "text": "Example 1:" }, { "code": null, "e": 2180, "s": 2175, "text": "Java" }, { "code": "// Java Program to illustrate addThen() method // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG { // main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // Now treble the output of half function half = half.andThen(a -> 3 * a); // Applying the function to get the result // and printing on console System.out.println(half.apply(10)); }}", "e": 2744, "s": 2180, "text": null }, { "code": null, "e": 2749, "s": 2744, "text": "15.0" }, { "code": null, "e": 2815, "s": 2749, "text": "Example 2: To demonstrate when NullPointerException is returned. " }, { "code": null, "e": 2820, "s": 2815, "text": "Java" }, { "code": "// Java Program to illustrate addThen() method// When NullPointerException occurs // Importing interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // Try block to check for exce3ptions try { // Trying to pass null as parameter half = half.andThen(null); } // Catch block to handle exceptions catch (Exception e) { // Print statement System.out.println(\"Exception thrown \" + \"while passing null: \" + e); } }}", "e": 3610, "s": 2820, "text": null }, { "code": null, "e": 3678, "s": 3610, "text": "Exception thrown while passing null: java.lang.NullPointerException" }, { "code": null, "e": 3698, "s": 3678, "text": "Method 3: compose()" }, { "code": null, "e": 3915, "s": 3698, "text": "It returns a composed function wherein the parameterized function will be executed first and then the first one. If evaluation of either function throws an error, it is relayed to the caller of the composed function." }, { "code": null, "e": 3925, "s": 3915, "text": "Syntax: " }, { "code": null, "e": 4002, "s": 3925, "text": "default <V> Function<V, R> \ncompose(Function<? super V, ? extends T> before)" }, { "code": null, "e": 4084, "s": 4002, "text": "Where V is the type of input of the before function, and of the composed function" }, { "code": null, "e": 4202, "s": 4084, "text": "Parameters: This method accepts a parameter before which is the function to be applied first and then the current one" }, { "code": null, "e": 4323, "s": 4202, "text": "Return Value: This method returns a composed function that applies the current function after the parameterized function" }, { "code": null, "e": 4406, "s": 4323, "text": "Exception: This method throws NullPointerException if the before function is null." }, { "code": null, "e": 4417, "s": 4406, "text": "Example 1:" }, { "code": null, "e": 4422, "s": 4417, "text": "Java" }, { "code": "// Java Program to illustrate compose() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // However treble the value given to half function half = half.compose(a -> 3 * a); // Applying the function to get the result System.out.println(half.apply(5)); }}", "e": 4969, "s": 4422, "text": null }, { "code": null, "e": 4973, "s": 4969, "text": "7.5" }, { "code": null, "e": 5024, "s": 4973, "text": "Example 2: When NullPointerException is returned. " }, { "code": null, "e": 5029, "s": 5024, "text": "Java" }, { "code": "// Java Program to illustrate compose() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns half of it Function<Integer, Double> half = a -> a / 2.0; // Try bloc kto check for exceptions try { // Trying to pass null as parameter half = half.compose(null); } // Catch block to handle exceptions catch (Exception e) { // Print statement System.out.println(\"Exception thrown \" + \"while passing null: \" + e); } }}", "e": 5791, "s": 5029, "text": null }, { "code": null, "e": 5859, "s": 5791, "text": "Exception thrown while passing null: java.lang.NullPointerException" }, { "code": null, "e": 5880, "s": 5859, "text": "Method 4: identity()" }, { "code": null, "e": 5943, "s": 5880, "text": "This method returns a function that returns its only argument." }, { "code": null, "e": 5953, "s": 5943, "text": "Syntax: " }, { "code": null, "e": 5990, "s": 5953, "text": "static <T> Function<T, T> identity()" }, { "code": null, "e": 6060, "s": 5990, "text": "where T denotes the type of the argument and the value to be returned" }, { "code": null, "e": 6130, "s": 6060, "text": "Returns: This method returns a function that returns its own argument" }, { "code": null, "e": 6139, "s": 6130, "text": "Example " }, { "code": null, "e": 6144, "s": 6139, "text": "Java" }, { "code": "// Java Program to Illustrate identity() method // Importing Function interfaceimport java.util.function.Function; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Function which takes in a number and // returns it Function<Integer, Integer> i = Function.identity(); // Print statement System.out.println(i.apply(10)); }}", "e": 6564, "s": 6144, "text": null }, { "code": null, "e": 6567, "s": 6564, "text": "10" }, { "code": null, "e": 6577, "s": 6567, "text": "hristinag" }, { "code": null, "e": 6590, "s": 6577, "text": "popliparul20" }, { "code": null, "e": 6604, "s": 6590, "text": "sumitgumber28" }, { "code": null, "e": 6624, "s": 6604, "text": "Java - util package" }, { "code": null, "e": 6631, "s": 6624, "text": "Java 8" }, { "code": null, "e": 6643, "s": 6631, "text": "java-basics" }, { "code": null, "e": 6658, "s": 6643, "text": "Java-Functions" }, { "code": null, "e": 6674, "s": 6658, "text": "java-interfaces" }, { "code": null, "e": 6679, "s": 6674, "text": "Java" }, { "code": null, "e": 6684, "s": 6679, "text": "Java" }, { "code": null, "e": 6782, "s": 6684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6833, "s": 6782, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 6864, "s": 6833, "text": "How to iterate any Map in Java" }, { "code": null, "e": 6883, "s": 6864, "text": "Interfaces in Java" }, { "code": null, "e": 6913, "s": 6883, "text": "HashMap in Java with Examples" }, { "code": null, "e": 6931, "s": 6913, "text": "ArrayList in Java" }, { "code": null, "e": 6951, "s": 6931, "text": "Collections in Java" }, { "code": null, "e": 6975, "s": 6951, "text": "Singleton Class in Java" }, { "code": null, "e": 7007, "s": 6975, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 7019, "s": 7007, "text": "Set in Java" } ]
Observer Pattern | Set 2 (Implementation)
12 Feb, 2018 We strongly recommend to refer below Set 1 before moving on to this post. Observer Pattern -Introduction In Set 1, we discussed below problem, a solution for the problem without Observer pattern and problems with the solution. Suppose we are building a cricket app that notifies viewers about the information such as current score, run rate etc. Suppose we have made two display elements CurrentScoreDisplay and AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the display elements are notified with new data and they display the latest data accordingly Applying Observer pattern to above problem:Let us see how we can improve the design of our application using observer pattern. If we observe the flow of data we can easily see that the CricketData and display elements follow subject-observers relationship. New Class Diagram: Java Implementation: // Java program to demonstrate working of// onserver patternimport java.util.ArrayList;import java.util.Iterator; // Implemented by Cricket data to communicate// with observersinterface Subject{ public void registerObserver(Observer o); public void unregisterObserver(Observer o); public void notifyObservers();} class CricketData implements Subject{ int runs; int wickets; float overs; ArrayList<Observer> observerList; public CricketData() { observerList = new ArrayList<Observer>(); } @Override public void registerObserver(Observer o) { observerList.add(o); } @Override public void unregisterObserver(Observer o) { observerList.remove(observerList.indexOf(o)); } @Override public void notifyObservers() { for (Iterator<Observer> it = observerList.iterator(); it.hasNext();) { Observer o = it.next(); o.update(runs,wickets,overs); } } // get latest runs from stadium private int getLatestRuns() { // return 90 for simplicity return 90; } // get latest wickets from stadium private int getLatestWickets() { // return 2 for simplicity return 2; } // get latest overs from stadium private float getLatestOvers() { // return 90 for simplicity return (float)10.2; } // This method is used update displays // when data changes public void dataChanged() { //get latest data runs = getLatestRuns(); wickets = getLatestWickets(); overs = getLatestOvers(); notifyObservers(); }} // This interface is implemented by all those// classes that are to be updated whenever there// is an update from CricketDatainterface Observer{ public void update(int runs, int wickets, float overs);} class AverageScoreDisplay implements Observer{ private float runRate; private int predictedScore; public void update(int runs, int wickets, float overs) { this.runRate =(float)runs/overs; this.predictedScore = (int)(this.runRate * 50); display(); } public void display() { System.out.println("\nAverage Score Display: \n" + "Run Rate: " + runRate + "\nPredictedScore: " + predictedScore); }} class CurrentScoreDisplay implements Observer{ private int runs, wickets; private float overs; public void update(int runs, int wickets, float overs) { this.runs = runs; this.wickets = wickets; this.overs = overs; display(); } public void display() { System.out.println("\nCurrent Score Display:\n" + "Runs: " + runs + "\nWickets:" + wickets + "\nOvers: " + overs ); }} // Driver Classclass Main{ public static void main(String args[]) { // create objects for testing AverageScoreDisplay averageScoreDisplay = new AverageScoreDisplay(); CurrentScoreDisplay currentScoreDisplay = new CurrentScoreDisplay(); // pass the displays to Cricket data CricketData cricketData = new CricketData(); // register display elements cricketData.registerObserver(averageScoreDisplay); cricketData.registerObserver(currentScoreDisplay); // in real app you would have some logic to // call this function when data changes cricketData.dataChanged(); //remove an observer cricketData.unregisterObserver(averageScoreDisplay); // now only currentScoreDisplay gets the // notification cricketData.dataChanged(); }} Output: Average Score Display: Run Rate: 8.823529 PredictedScore: 441 Current Score Display: Runs: 90 Wickets:2 Overs: 10.2 Current Score Display: Runs: 90 Wickets:2 Overs: 10.2 Note: Now we can add/delete as many observers without changing the subject. References: https://en.wikipedia.org/wiki/Observer_patternHead First Design Patterns book (highly recommended) https://en.wikipedia.org/wiki/Observer_pattern Head First Design Patterns book (highly recommended) This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Design Pattern Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Builder Design Pattern Unified Modeling Language (UML) | An Introduction MVC Design Pattern Introduction of Programming Paradigms Abstract Factory Pattern Monolithic vs Microservices architecture Composite Design Pattern Unified Modeling Language (UML) | Activity Diagrams Unified Modeling Language (UML) | State Diagrams
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Feb, 2018" }, { "code": null, "e": 126, "s": 52, "text": "We strongly recommend to refer below Set 1 before moving on to this post." }, { "code": null, "e": 157, "s": 126, "text": "Observer Pattern -Introduction" }, { "code": null, "e": 279, "s": 157, "text": "In Set 1, we discussed below problem, a solution for the problem without Observer pattern and problems with the solution." }, { "code": null, "e": 652, "s": 279, "text": "Suppose we are building a cricket app that notifies viewers about the information such as current score, run rate etc. Suppose we have made two display elements CurrentScoreDisplay and AverageScoreDisplay. CricketData has all the data (runs, bowls etc.) and whenever data changes the display elements are notified with new data and they display the latest data accordingly" }, { "code": null, "e": 909, "s": 652, "text": "Applying Observer pattern to above problem:Let us see how we can improve the design of our application using observer pattern. If we observe the flow of data we can easily see that the CricketData and display elements follow subject-observers relationship." }, { "code": null, "e": 929, "s": 909, "text": "New Class Diagram: " }, { "code": null, "e": 950, "s": 929, "text": "Java Implementation:" }, { "code": "// Java program to demonstrate working of// onserver patternimport java.util.ArrayList;import java.util.Iterator; // Implemented by Cricket data to communicate// with observersinterface Subject{ public void registerObserver(Observer o); public void unregisterObserver(Observer o); public void notifyObservers();} class CricketData implements Subject{ int runs; int wickets; float overs; ArrayList<Observer> observerList; public CricketData() { observerList = new ArrayList<Observer>(); } @Override public void registerObserver(Observer o) { observerList.add(o); } @Override public void unregisterObserver(Observer o) { observerList.remove(observerList.indexOf(o)); } @Override public void notifyObservers() { for (Iterator<Observer> it = observerList.iterator(); it.hasNext();) { Observer o = it.next(); o.update(runs,wickets,overs); } } // get latest runs from stadium private int getLatestRuns() { // return 90 for simplicity return 90; } // get latest wickets from stadium private int getLatestWickets() { // return 2 for simplicity return 2; } // get latest overs from stadium private float getLatestOvers() { // return 90 for simplicity return (float)10.2; } // This method is used update displays // when data changes public void dataChanged() { //get latest data runs = getLatestRuns(); wickets = getLatestWickets(); overs = getLatestOvers(); notifyObservers(); }} // This interface is implemented by all those// classes that are to be updated whenever there// is an update from CricketDatainterface Observer{ public void update(int runs, int wickets, float overs);} class AverageScoreDisplay implements Observer{ private float runRate; private int predictedScore; public void update(int runs, int wickets, float overs) { this.runRate =(float)runs/overs; this.predictedScore = (int)(this.runRate * 50); display(); } public void display() { System.out.println(\"\\nAverage Score Display: \\n\" + \"Run Rate: \" + runRate + \"\\nPredictedScore: \" + predictedScore); }} class CurrentScoreDisplay implements Observer{ private int runs, wickets; private float overs; public void update(int runs, int wickets, float overs) { this.runs = runs; this.wickets = wickets; this.overs = overs; display(); } public void display() { System.out.println(\"\\nCurrent Score Display:\\n\" + \"Runs: \" + runs + \"\\nWickets:\" + wickets + \"\\nOvers: \" + overs ); }} // Driver Classclass Main{ public static void main(String args[]) { // create objects for testing AverageScoreDisplay averageScoreDisplay = new AverageScoreDisplay(); CurrentScoreDisplay currentScoreDisplay = new CurrentScoreDisplay(); // pass the displays to Cricket data CricketData cricketData = new CricketData(); // register display elements cricketData.registerObserver(averageScoreDisplay); cricketData.registerObserver(currentScoreDisplay); // in real app you would have some logic to // call this function when data changes cricketData.dataChanged(); //remove an observer cricketData.unregisterObserver(averageScoreDisplay); // now only currentScoreDisplay gets the // notification cricketData.dataChanged(); }}", "e": 4817, "s": 950, "text": null }, { "code": null, "e": 4825, "s": 4817, "text": "Output:" }, { "code": null, "e": 5000, "s": 4825, "text": "Average Score Display: \nRun Rate: 8.823529\nPredictedScore: 441\n\nCurrent Score Display:\nRuns: 90\nWickets:2\nOvers: 10.2\n\nCurrent Score Display:\nRuns: 90\nWickets:2\nOvers: 10.2\n\n" }, { "code": null, "e": 5076, "s": 5000, "text": "Note: Now we can add/delete as many observers without changing the subject." }, { "code": null, "e": 5088, "s": 5076, "text": "References:" }, { "code": null, "e": 5187, "s": 5088, "text": "https://en.wikipedia.org/wiki/Observer_patternHead First Design Patterns book (highly recommended)" }, { "code": null, "e": 5234, "s": 5187, "text": "https://en.wikipedia.org/wiki/Observer_pattern" }, { "code": null, "e": 5287, "s": 5234, "text": "Head First Design Patterns book (highly recommended)" }, { "code": null, "e": 5553, "s": 5287, "text": "This article is contributed by Sulabh Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5677, "s": 5553, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 5692, "s": 5677, "text": "Design Pattern" }, { "code": null, "e": 5790, "s": 5692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5828, "s": 5790, "text": "Factory method design pattern in Java" }, { "code": null, "e": 5851, "s": 5828, "text": "Builder Design Pattern" }, { "code": null, "e": 5901, "s": 5851, "text": "Unified Modeling Language (UML) | An Introduction" }, { "code": null, "e": 5920, "s": 5901, "text": "MVC Design Pattern" }, { "code": null, "e": 5958, "s": 5920, "text": "Introduction of Programming Paradigms" }, { "code": null, "e": 5983, "s": 5958, "text": "Abstract Factory Pattern" }, { "code": null, "e": 6024, "s": 5983, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 6049, "s": 6024, "text": "Composite Design Pattern" }, { "code": null, "e": 6101, "s": 6049, "text": "Unified Modeling Language (UML) | Activity Diagrams" } ]
Python – seaborn.swarmplot() method
18 Aug, 2020 Prerequisite : Fundamentals of Seaborn Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. There is just something extraordinary about a well-designed visualization. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well. Draw a categorical scatterplot with non-overlapping points. A swarm plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution. Arranging the points properly requires an accurate transformation between data and point coordinates. This means that non-default axis limits must be set *before* drawing the plot. Syntax : seaborn.swarmplot(parameters) Parameters : x, y, hue : Inputs for plotting long-form data. data : Dataset for plotting. order, hue_order : Order to plot the categorical levels in, otherwise the levels are inferred from the data objects. dodge : To separate the strips for different hue levels along the categorical axis orient : Orientation of the plot (vertical or horizontal). color : Color for all of the elements, or seed for a gradient palette. palette : Colors to use for the different levels of the hue variable. size : Radius of the markers, in points. edgecolor : Color of the lines around each point. linewidth : Width of the gray lines that frame the plot elements. ax : Axes object to draw the plot onto, otherwise uses the current Axes. kwargs : Other keyword arguments Returns : Returns the Axes object with the plot drawn onto it. Below is the implementation of above method with some examples : Example 1 : # importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # plot the swarmplot# size set to 5sns.swarmplot(x ="day", y = "total_bill", data = data, size = 5)plt.show() Output : Example 2 : # importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # plot the swarmplot# hue by size# oriented to horizontalsns.swarmplot(y = "day", x = "total_bill", hue = "size", orient = "h", data = data)plt.show() Output : Example 3 : # importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset("tips") # plot the swarmplot# hue by smoker# dodge = Truesns.swarmplot(x = "sex", y = "total_bill", hue = "smoker", data = data, dodge = True)plt.show() Output : Python-Seaborn Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2020" }, { "code": null, "e": 91, "s": 52, "text": "Prerequisite : Fundamentals of Seaborn" }, { "code": null, "e": 530, "s": 91, "text": "Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. There is just something extraordinary about a well-designed visualization. The colors stand out, the layers blend nicely together, the contours flow throughout, and the overall package not only has a nice aesthetic quality, but it provides meaningful insights to us as well." }, { "code": null, "e": 978, "s": 530, "text": "Draw a categorical scatterplot with non-overlapping points. A swarm plot can be drawn on its own, but it is also a good complement to a box or violin plot in cases where you want to show all observations along with some representation of the underlying distribution. Arranging the points properly requires an accurate transformation between data and point coordinates. This means that non-default axis limits must be set *before* drawing the plot." }, { "code": null, "e": 1017, "s": 978, "text": "Syntax : seaborn.swarmplot(parameters)" }, { "code": null, "e": 1030, "s": 1017, "text": "Parameters :" }, { "code": null, "e": 1078, "s": 1030, "text": "x, y, hue : Inputs for plotting long-form data." }, { "code": null, "e": 1107, "s": 1078, "text": "data : Dataset for plotting." }, { "code": null, "e": 1224, "s": 1107, "text": "order, hue_order : Order to plot the categorical levels in, otherwise the levels are inferred from the data objects." }, { "code": null, "e": 1307, "s": 1224, "text": "dodge : To separate the strips for different hue levels along the categorical axis" }, { "code": null, "e": 1366, "s": 1307, "text": "orient : Orientation of the plot (vertical or horizontal)." }, { "code": null, "e": 1437, "s": 1366, "text": "color : Color for all of the elements, or seed for a gradient palette." }, { "code": null, "e": 1507, "s": 1437, "text": "palette : Colors to use for the different levels of the hue variable." }, { "code": null, "e": 1548, "s": 1507, "text": "size : Radius of the markers, in points." }, { "code": null, "e": 1598, "s": 1548, "text": "edgecolor : Color of the lines around each point." }, { "code": null, "e": 1664, "s": 1598, "text": "linewidth : Width of the gray lines that frame the plot elements." }, { "code": null, "e": 1737, "s": 1664, "text": "ax : Axes object to draw the plot onto, otherwise uses the current Axes." }, { "code": null, "e": 1770, "s": 1737, "text": "kwargs : Other keyword arguments" }, { "code": null, "e": 1833, "s": 1770, "text": "Returns : Returns the Axes object with the plot drawn onto it." }, { "code": null, "e": 1898, "s": 1833, "text": "Below is the implementation of above method with some examples :" }, { "code": null, "e": 1910, "s": 1898, "text": "Example 1 :" }, { "code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # plot the swarmplot# size set to 5sns.swarmplot(x =\"day\", y = \"total_bill\", data = data, size = 5)plt.show()", "e": 2158, "s": 1910, "text": null }, { "code": null, "e": 2167, "s": 2158, "text": "Output :" }, { "code": null, "e": 2179, "s": 2167, "text": "Example 2 :" }, { "code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # plot the swarmplot# hue by size# oriented to horizontalsns.swarmplot(y = \"day\", x = \"total_bill\", hue = \"size\", orient = \"h\", data = data)plt.show()", "e": 2468, "s": 2179, "text": null }, { "code": null, "e": 2477, "s": 2468, "text": "Output :" }, { "code": null, "e": 2489, "s": 2477, "text": "Example 3 :" }, { "code": "# importing packagesimport seaborn as snsimport matplotlib.pyplot as plt # loading datasetdata = sns.load_dataset(\"tips\") # plot the swarmplot# hue by smoker# dodge = Truesns.swarmplot(x = \"sex\", y = \"total_bill\", hue = \"smoker\", data = data, dodge = True)plt.show()", "e": 2772, "s": 2489, "text": null }, { "code": null, "e": 2781, "s": 2772, "text": "Output :" }, { "code": null, "e": 2796, "s": 2781, "text": "Python-Seaborn" }, { "code": null, "e": 2803, "s": 2796, "text": "Python" } ]
MongoDB insertMany() Method – db.Collection.insertMany()
28 Jan, 2021 The insertMany() method inserts one or more documents in the collection. It takes array of documents to insert in the collection. By default, documents are inserted in the given order if you want to insert documents in unordered, then set the value of ordered to false. Using this method you can also create a collection by inserting documents. You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error. This method can also throw a BulkWriteError exception. This method can also be used inside multi-document transactions. Syntax: db.Collection_name.insertMany( [<document 1>, <document 2>, ...], { writeConcern: <document>, ordered: <boolean> }) Parameters: The first parameter is the array of documents to insert into the collection. The second parameter is optional. Optional Parameters: writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document. ordered: The type of this parameter is boolean that specifies whether the MongoDB instance should perform an ordered or unordered insertion. If it is true insertion will be in ordered manner otherwise in unordered manner. Default it is true. Return: This method returns : Boolean acknowledged as true if write concern was enabled or false if write concern was disabled. The insertedId field with the _id value of the inserted document. Examples: In the following examples, we are working with: Database: gfg Collection: student Document: Empty Example 1: Inserts the one document that contains the name and age of the student db.student.insertMany([{name:"Akshay",age:18}]) Example 2: Insert the array of documents that contains the name and age of the students db.student.insertMany([{name:"Ajay",age:20}, {name:"Bina",age:24}, {name:"Ram",age:23}]) Example 3: Insert multiple documents with _id field db.student.insertMany([{_id:"stu200", name:"Ammu", age:18}, {_id:"stu201", name:"Priya", age:29}]) Example 4: Insert unordered documents by setting the value of ordered option to false db.student.insertMany([{_id:"stu203",name:"Soniya",age:28}, {_id:"stu202", name:"Priya", age:25}], {ordered: false}) MongoDB-method Picked MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - sort() Method MongoDB - FindOne() Method MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Regex MongoDB - Compound Indexes MongoDB updateMany() Method - db.Collection.updateMany() MongoDB Cursor Spring Boot - CRUD Operations using MongoDB
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jan, 2021" }, { "code": null, "e": 183, "s": 52, "text": "The insertMany() method inserts one or more documents in the collection. It takes array of documents to insert in the collection. " }, { "code": null, "e": 323, "s": 183, "text": "By default, documents are inserted in the given order if you want to insert documents in unordered, then set the value of ordered to false." }, { "code": null, "e": 398, "s": 323, "text": "Using this method you can also create a collection by inserting documents." }, { "code": null, "e": 725, "s": 398, "text": "You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error." }, { "code": null, "e": 780, "s": 725, "text": "This method can also throw a BulkWriteError exception." }, { "code": null, "e": 845, "s": 780, "text": "This method can also be used inside multi-document transactions." }, { "code": null, "e": 853, "s": 845, "text": "Syntax:" }, { "code": null, "e": 884, "s": 853, "text": "db.Collection_name.insertMany(" }, { "code": null, "e": 919, "s": 884, "text": "[<document 1>, <document 2>, ...]," }, { "code": null, "e": 921, "s": 919, "text": "{" }, { "code": null, "e": 951, "s": 921, "text": " writeConcern: <document>," }, { "code": null, "e": 974, "s": 951, "text": " ordered: <boolean>" }, { "code": null, "e": 977, "s": 974, "text": "})" }, { "code": null, "e": 989, "s": 977, "text": "Parameters:" }, { "code": null, "e": 1066, "s": 989, "text": "The first parameter is the array of documents to insert into the collection." }, { "code": null, "e": 1100, "s": 1066, "text": "The second parameter is optional." }, { "code": null, "e": 1121, "s": 1100, "text": "Optional Parameters:" }, { "code": null, "e": 1248, "s": 1121, "text": "writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document." }, { "code": null, "e": 1490, "s": 1248, "text": "ordered: The type of this parameter is boolean that specifies whether the MongoDB instance should perform an ordered or unordered insertion. If it is true insertion will be in ordered manner otherwise in unordered manner. Default it is true." }, { "code": null, "e": 1498, "s": 1490, "text": "Return:" }, { "code": null, "e": 1520, "s": 1498, "text": "This method returns :" }, { "code": null, "e": 1618, "s": 1520, "text": "Boolean acknowledged as true if write concern was enabled or false if write concern was disabled." }, { "code": null, "e": 1684, "s": 1618, "text": "The insertedId field with the _id value of the inserted document." }, { "code": null, "e": 1694, "s": 1684, "text": "Examples:" }, { "code": null, "e": 1742, "s": 1694, "text": "In the following examples, we are working with:" }, { "code": null, "e": 1756, "s": 1742, "text": "Database: gfg" }, { "code": null, "e": 1776, "s": 1756, "text": "Collection: student" }, { "code": null, "e": 1792, "s": 1776, "text": "Document: Empty" }, { "code": null, "e": 1874, "s": 1792, "text": "Example 1: Inserts the one document that contains the name and age of the student" }, { "code": null, "e": 1922, "s": 1874, "text": "db.student.insertMany([{name:\"Akshay\",age:18}])" }, { "code": null, "e": 2010, "s": 1922, "text": "Example 2: Insert the array of documents that contains the name and age of the students" }, { "code": null, "e": 2145, "s": 2010, "text": "db.student.insertMany([{name:\"Ajay\",age:20},\n {name:\"Bina\",age:24},\n {name:\"Ram\",age:23}])" }, { "code": null, "e": 2197, "s": 2145, "text": "Example 3: Insert multiple documents with _id field" }, { "code": null, "e": 2319, "s": 2197, "text": "db.student.insertMany([{_id:\"stu200\", name:\"Ammu\", age:18},\n {_id:\"stu201\", name:\"Priya\", age:29}])" }, { "code": null, "e": 2405, "s": 2319, "text": "Example 4: Insert unordered documents by setting the value of ordered option to false" }, { "code": null, "e": 2570, "s": 2405, "text": "db.student.insertMany([{_id:\"stu203\",name:\"Soniya\",age:28}, \n {_id:\"stu202\", name:\"Priya\", age:25}], \n {ordered: false})" }, { "code": null, "e": 2585, "s": 2570, "text": "MongoDB-method" }, { "code": null, "e": 2592, "s": 2585, "text": "Picked" }, { "code": null, "e": 2600, "s": 2592, "text": "MongoDB" }, { "code": null, "e": 2698, "s": 2600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2736, "s": 2698, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 2761, "s": 2736, "text": "MongoDB - limit() Method" }, { "code": null, "e": 2785, "s": 2761, "text": "MongoDB - sort() Method" }, { "code": null, "e": 2812, "s": 2785, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 2867, "s": 2812, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 2883, "s": 2867, "text": "MongoDB - Regex" }, { "code": null, "e": 2910, "s": 2883, "text": "MongoDB - Compound Indexes" }, { "code": null, "e": 2967, "s": 2910, "text": "MongoDB updateMany() Method - db.Collection.updateMany()" }, { "code": null, "e": 2982, "s": 2967, "text": "MongoDB Cursor" } ]
Exchange first and last nodes in Circular Linked List
23 Jun, 2022 Given Circular linked list exchange the first and the last node. The task should be done with only one extra node, you can not declare more than one extra node, and also you are not allowed to declare any other temporary variable. Note: Extra node means the need of a node to traverse a list. Examples: Input : 5 4 3 2 1 Output : 1 4 3 2 5 Input : 6 1 2 3 4 5 6 7 8 9 Output : 9 1 2 3 4 5 6 7 8 6 Method 1: (By Changing Links of First and Last Nodes)We first find a pointer to the previous to the last node. Let this node be p. Now we change the next links so that the last and first nodes are swapped. C++ Java Python3 C# Javascript // CPP program to exchange first and// last node in circular linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; struct Node* addToEmpty(struct Node* head, int data){ // This function is only for empty list if (head != NULL) return head; // Creating a node dynamically. struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; head = temp; // Creating the link. head->next = head; return head;} struct Node* addBegin(struct Node* head, int data){ if (head == NULL) return addToEmpty(head, data); struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head->next; head->next = temp; return head;} /* function for traversing the list */void traverse(struct Node* head){ struct Node* p; // If list is empty, return. if (head == NULL) { cout << "List is empty." << endl; return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { cout << p->data << " "; p = p->next; } while (p != head);} /* Function to exchange first and last node*/struct Node* exchangeNodes(struct Node* head){ // If list is of length 2 if (head->next->next == head) { head = head->next; return head; } // Find pointer to previous of last node struct Node* p = head; while (p->next->next != head) p = p->next; /* Exchange first and last nodes using head and p */ p->next->next = head->next; head->next = p->next; p->next = head; head = head->next; return head;} // Driven Programint main(){ int i; struct Node* head = NULL; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); cout << "List Before: "; traverse(head); cout << endl; cout << "List After: "; head = exchangeNodes(head); traverse(head); return 0;} // Java program to exchange// first and last node in// circular linked listclass GFG { static class Node { int data; Node next; }; static Node addToEmpty(Node head, int data) { // This function is only // for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } static Node addBegin(Node head, int data) { if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } // function for traversing the list static void traverse(Node head) { Node p; // If list is empty, return. if (head == null) { System.out.print("List is empty."); return; } // Pointing to first // Node of the list. p = head; // Traversing the list. do { System.out.print(p.data + " "); p = p.next; } while (p != head); } // Function to exchange // first and last node static Node exchangeNodes(Node head) { // If list is of length 2 if (head.next.next == head) { head = head.next; return head; } // Find pointer to previous // of last node Node p = head; while (p.next.next != head) p = p.next; // Exchange first and last // nodes using head and p p.next.next = head.next; head.next = p.next; p.next = head; head = head.next; return head; } // Driver Code public static void main(String args[]) { int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); System.out.print("List Before: "); traverse(head); System.out.println(); System.out.print("List After: "); head = exchangeNodes(head); traverse(head); }} // This code is contributed// by Arnab Kundu # Python3 program to exchange first and# last node in circular linked listimport math class Node: def __init__(self, data): self.data = data self.next = None def addToEmpty(head, data): # This function is only for empty list if (head != None): return head # Creating a node dynamically. temp = Node(data) # Assigning the data. temp.data = data head = temp # Creating the link. head.next = head return head def addBegin(head, data): if (head == None): return addToEmpty(head, data) temp = Node(data) temp.data = data temp.next = head.next head.next = temp return head # function for traversing the list def traverse(head): # If list is empty, return. if (head == None): print("List is empty.") return # Pointing to first Node of the list. p = head print(p.data, end=" ") p = p.next # Traversing the list. while(p != head): print(p.data, end=" ") p = p.next def exchangeNodes(head): # Cases Handled: Linked List either empty or containing single node. if head == None or head.next == head: return head # Cases Handled: Linked List containing only two nodes elif head.next.next == head: head = head.next return head # Cases Handled: Linked List containing multiple nodes else: prev = None curr = head temp = head # finding last and second last nodes in linkedlist list while curr.next != head: prev = curr curr = curr.next # point the last node to second node of the list curr.next = temp.next # point the second last node to first node prev.next = temp # point the end of node to start ( make linked list circular ) temp.next = curr # mark the starting of linked list head = curr return head # Driver Codeif __name__ == '__main__': head = None head = addToEmpty(head, 6) for x in range(5, 0, -1): head = addBegin(head, x) print("List Before: ", end="") traverse(head) print() print("List After: ", end="") head = exchangeNodes(head) traverse(head) # This code is contributed by Srathore# Improved by Vinay Kumar (vinaykumar71) // C# program to exchange// first and last node in// circular linked listusing System; public class GFG { class Node { public int data; public Node next; }; static Node addToEmpty(Node head, int data) { // This function is only // for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } static Node addBegin(Node head, int data) { if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } // function for traversing the list static void traverse(Node head) { Node p; // If list is empty, return. if (head == null) { Console.Write("List is empty."); return; } // Pointing to first // Node of the list. p = head; // Traversing the list. do { Console.Write(p.data + " "); p = p.next; } while (p != head); } // Function to exchange // first and last node static Node exchangeNodes(Node head) { // If list is of length 2 if (head.next.next == head) { head = head.next; return head; } // Find pointer to previous // of last node Node p = head; while (p.next.next != head) p = p.next; // Exchange first and last // nodes using head and p p.next.next = head.next; head.next = p.next; p.next = head; head = head.next; return head; } // Driver Code public static void Main() { int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); Console.Write("List Before: "); traverse(head); Console.WriteLine(); Console.Write("List After: "); head = exchangeNodes(head); traverse(head); }} /* This code is contributed PrinciRaj1992 */ <script>// javascript program to exchange// first and last node in// circular linked list class Node { constructor() { this.data = 0; this.next = null; }} function addToEmpty(head , data) { // This function is only // for empty list if (head != null) return head; // Creating a node dynamically. var temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } function addBegin(head , data) { if (head == null) return addToEmpty(head, data); var temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } // function for traversing the list function traverse(head) { var p; // If list is empty, return. if (head == null) { document.write("List is empty."); return; } // Pointing to first // Node of the list. p = head; // Traversing the list. do { document.write(p.data + " "); p = p.next; } while (p != head); } // Function to exchange // first and last node function exchangeNodes(head) { // If list is of length 2 if (head.next.next == head) { head = head.next; return head; } // Find pointer to previous // of last node var p = head; while (p.next.next != head) p = p.next; // Exchange first and last // nodes using head and p p.next.next = head.next; head.next = p.next; p.next = head; head = head.next; return head; } // Driver Code var i; var head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); document.write("List Before: "); traverse(head); document.write("<br/>"); document.write("List After: "); head = exchangeNodes(head); traverse(head); // This code is contributed by umadevi9616</script> List Before: 6 1 2 3 4 5 List After: 5 1 2 3 4 6 Method 2: (By Swapping Values of First and Last nodes) Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list. Auxiliary Space: O(1), as we are not using any extra space. Algorithm: Traverse the list and find the last node(tail).Swap data of head and tail. Traverse the list and find the last node(tail). Swap data of head and tail. Below is the implementation of the algorithm: C++ Java Python3 C# Javascript // CPP program to exchange first and// last node in circular linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; struct Node* addToEmpty(struct Node* head, int data){ // This function is only for empty list if (head != NULL) return head; // Creating a node dynamically. struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; head = temp; // Creating the link. head->next = head; return head;} struct Node* addBegin(struct Node* head, int data){ if (head == NULL) return addToEmpty(head, data); struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head->next; head->next = temp; return head;} /* function for traversing the list */void traverse(struct Node* head){ struct Node* p; // If list is empty, return. if (head == NULL) { cout << "List is empty." << endl; return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { cout << p->data << " "; p = p->next; } while (p != head);} /* Function to exchange first and last node*/struct Node* exchangeNodes(struct Node* head){ // If list is of length less than 2 if (head == NULL || head->next == NULL) { return head; } Node* tail = head; // Find pointer to the last node while (tail->next != head) { tail = tail->next; } /* Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail->data; tail->data = head->data; head->data = temp; return head;} // Driven Programint main(){ int i; struct Node* head = NULL; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); cout << "List Before: "; traverse(head); cout << endl; cout << "List After: "; head = exchangeNodes(head); traverse(head); return 0;} // JAVA program to exchange first and// last node in circular linked listclass GFG{ static class Node { int data; Node next;}; static Node addToEmpty(Node head, int data){ // This function is only for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head;} static Node addBegin(Node head, int data){ if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head;} /* function for traversing the list */static void traverse(Node head){ Node p; // If list is empty, return. if (head == null) { System.out.print("List is empty." +"\n"); return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { System.out.print(p.data+ " "); p = p.next; } while (p != head);} /* Function to exchange first and last node*/static Node exchangeNodes(Node head){ // If list is of length less than 2 if (head == null || head.next == null) { return head; } Node tail = head; // Find pointer to the last node while (tail.next != head) { tail = tail.next; } /* Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail.data; tail.data = head.data; head.data = temp; return head;} // Driven Programpublic static void main(String[] args){ int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); System.out.print("List Before: "); traverse(head); System.out.println(); System.out.print("List After: "); head = exchangeNodes(head); traverse(head); }} // This code is contributed by umadevi9616 # Python program to exchange first and# last node in circular linked list class Node {class Node: def __init__(self): self.data = 0 self.next = None def addToEmpty(head, data): # This function is only for empty list if (head != None): return head # Creating a node dynamically. temp = Node() # Assigning the data. temp.data = data head = temp # Creating the link. head.next = head return head def addBegin(head, data): if (head == None): return addToEmpty(head, data) temp = Node() temp.data = data temp.next = head.next head.next = temp return head # function for traversing the listdef traverse(head): # If list is empty, return. if (head == None): print("List is empty.") return # Pointing to first Node of the list. p = head # Traversing the list. while (True): print(p.data, end=" ") p = p.next if(p == head): break # Function to exchange first and last nodedef exchangeNodes(head): # If list is of length less than 2 if (head == None or head.next == None): return head tail = head # Find pointer to the last node while (tail.next != head): tail = tail.next # Exchange first and last nodes using head and p # temporary variable to store # head data temp = tail.data tail.data = head.data head.data = temp return head # Driven Programhead = Nonehead = addToEmpty(head, 6) for i in range(5, 0, -1): head = addBegin(head, i) print("List Before: ")traverse(head)print("") print("List After: ")head = exchangeNodes(head)traverse(head) # This code is contributed by Saurabh Jaiswal // C# program to exchange first and// last node in circular linked listusing System; public class GFG { public class Node { public int data; public Node next; }; static Node addToEmpty(Node head, int data) { // This function is only for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } static Node addBegin(Node head, int data) { if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } /* function for traversing the list */ static void traverse(Node head) { Node p; // If list is empty, return. if (head == null) { Console.Write("List is empty." + "\n"); return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { Console.Write(p.data + " "); p = p.next; } while (p != head); } /* Function to exchange first and last node */ static Node exchangeNodes(Node head) { // If list is of length less than 2 if (head == null || head.next == null) { return head; } Node tail = head; // Find pointer to the last node while (tail.next != head) { tail = tail.next; } /* * Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail.data; tail.data = head.data; head.data = temp; return head; } // Driven Program public static void Main(String[] args) { int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); Console.Write("List Before: "); traverse(head); Console.WriteLine(); Console.Write("List After: "); head = exchangeNodes(head); traverse(head); }} // This code is contributed by umadevi9616 <script>// javascript program to exchange first and// last node in circular linked list class Node {class Node { constructor() { this.data = 0; this.next = null; }} function addToEmpty(head , data) { // This function is only for empty list if (head != null) return head; // Creating a node dynamically. var temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } function addBegin(head , data) { if (head == null) return addToEmpty(head, data); var temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } /* function for traversing the list */ function traverse(head) { var p; // If list is empty, return. if (head == null) { document.write("List is empty." + "\n"); return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { document.write(p.data + " "); p = p.next; } while (p != head); } /* Function to exchange first and last node */ function exchangeNodes(head) { // If list is of length less than 2 if (head == null || head.next == null) { return head; }var tail = head; // Find pointer to the last node while (tail.next != head) { tail = tail.next; } /* * Exchange first and last nodes using head and p */ // temporary variable to store // head data var temp = tail.data; tail.data = head.data; head.data = temp; return head; } // Driven Program var i; var head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); document.write("List Before: <br/>"); traverse(head); document.write("<br/>"); document.write("List After: <br/>"); head = exchangeNodes(head); traverse(head); // This code is contributed by umadevi9616</script> List Before: 6 1 2 3 4 5 List After: 5 1 2 3 4 6 Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list. Auxiliary Space: O(1), as we are not using any extra space. This article is contributed by R_Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. andrew1234 princiraj1992 sapnasingh4991 vinaykumar71 ritwikneema651 prathamjha5683 umadevi9616 _saurabh_jaiswal rohan07 circular linked list Linked List Linked List circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Types of Linked List Circular Singly Linked List | Insertion Find first node of loop in a linked list Add two numbers represented by linked lists | Set 2 Flattening a Linked List Real-time application of Data Structures Insert a node at a specific position in a linked list Clone a linked list with next and random pointer | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 347, "s": 52, "text": "Given Circular linked list exchange the first and the last node. The task should be done with only one extra node, you can not declare more than one extra node, and also you are not allowed to declare any other temporary variable. Note: Extra node means the need of a node to traverse a list. " }, { "code": null, "e": 358, "s": 347, "text": "Examples: " }, { "code": null, "e": 454, "s": 358, "text": "Input : 5 4 3 2 1\nOutput : 1 4 3 2 5\n\nInput : 6 1 2 3 4 5 6 7 8 9\nOutput : 9 1 2 3 4 5 6 7 8 6" }, { "code": null, "e": 662, "s": 454, "text": "Method 1: (By Changing Links of First and Last Nodes)We first find a pointer to the previous to the last node. Let this node be p. Now we change the next links so that the last and first nodes are swapped. " }, { "code": null, "e": 666, "s": 662, "text": "C++" }, { "code": null, "e": 671, "s": 666, "text": "Java" }, { "code": null, "e": 679, "s": 671, "text": "Python3" }, { "code": null, "e": 682, "s": 679, "text": "C#" }, { "code": null, "e": 693, "s": 682, "text": "Javascript" }, { "code": "// CPP program to exchange first and// last node in circular linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; struct Node* addToEmpty(struct Node* head, int data){ // This function is only for empty list if (head != NULL) return head; // Creating a node dynamically. struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; head = temp; // Creating the link. head->next = head; return head;} struct Node* addBegin(struct Node* head, int data){ if (head == NULL) return addToEmpty(head, data); struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head->next; head->next = temp; return head;} /* function for traversing the list */void traverse(struct Node* head){ struct Node* p; // If list is empty, return. if (head == NULL) { cout << \"List is empty.\" << endl; return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { cout << p->data << \" \"; p = p->next; } while (p != head);} /* Function to exchange first and last node*/struct Node* exchangeNodes(struct Node* head){ // If list is of length 2 if (head->next->next == head) { head = head->next; return head; } // Find pointer to previous of last node struct Node* p = head; while (p->next->next != head) p = p->next; /* Exchange first and last nodes using head and p */ p->next->next = head->next; head->next = p->next; p->next = head; head = head->next; return head;} // Driven Programint main(){ int i; struct Node* head = NULL; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); cout << \"List Before: \"; traverse(head); cout << endl; cout << \"List After: \"; head = exchangeNodes(head); traverse(head); return 0;}", "e": 2718, "s": 693, "text": null }, { "code": "// Java program to exchange// first and last node in// circular linked listclass GFG { static class Node { int data; Node next; }; static Node addToEmpty(Node head, int data) { // This function is only // for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } static Node addBegin(Node head, int data) { if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } // function for traversing the list static void traverse(Node head) { Node p; // If list is empty, return. if (head == null) { System.out.print(\"List is empty.\"); return; } // Pointing to first // Node of the list. p = head; // Traversing the list. do { System.out.print(p.data + \" \"); p = p.next; } while (p != head); } // Function to exchange // first and last node static Node exchangeNodes(Node head) { // If list is of length 2 if (head.next.next == head) { head = head.next; return head; } // Find pointer to previous // of last node Node p = head; while (p.next.next != head) p = p.next; // Exchange first and last // nodes using head and p p.next.next = head.next; head.next = p.next; p.next = head; head = head.next; return head; } // Driver Code public static void main(String args[]) { int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); System.out.print(\"List Before: \"); traverse(head); System.out.println(); System.out.print(\"List After: \"); head = exchangeNodes(head); traverse(head); }} // This code is contributed// by Arnab Kundu", "e": 4990, "s": 2718, "text": null }, { "code": "# Python3 program to exchange first and# last node in circular linked listimport math class Node: def __init__(self, data): self.data = data self.next = None def addToEmpty(head, data): # This function is only for empty list if (head != None): return head # Creating a node dynamically. temp = Node(data) # Assigning the data. temp.data = data head = temp # Creating the link. head.next = head return head def addBegin(head, data): if (head == None): return addToEmpty(head, data) temp = Node(data) temp.data = data temp.next = head.next head.next = temp return head # function for traversing the list def traverse(head): # If list is empty, return. if (head == None): print(\"List is empty.\") return # Pointing to first Node of the list. p = head print(p.data, end=\" \") p = p.next # Traversing the list. while(p != head): print(p.data, end=\" \") p = p.next def exchangeNodes(head): # Cases Handled: Linked List either empty or containing single node. if head == None or head.next == head: return head # Cases Handled: Linked List containing only two nodes elif head.next.next == head: head = head.next return head # Cases Handled: Linked List containing multiple nodes else: prev = None curr = head temp = head # finding last and second last nodes in linkedlist list while curr.next != head: prev = curr curr = curr.next # point the last node to second node of the list curr.next = temp.next # point the second last node to first node prev.next = temp # point the end of node to start ( make linked list circular ) temp.next = curr # mark the starting of linked list head = curr return head # Driver Codeif __name__ == '__main__': head = None head = addToEmpty(head, 6) for x in range(5, 0, -1): head = addBegin(head, x) print(\"List Before: \", end=\"\") traverse(head) print() print(\"List After: \", end=\"\") head = exchangeNodes(head) traverse(head) # This code is contributed by Srathore# Improved by Vinay Kumar (vinaykumar71)", "e": 7262, "s": 4990, "text": null }, { "code": "// C# program to exchange// first and last node in// circular linked listusing System; public class GFG { class Node { public int data; public Node next; }; static Node addToEmpty(Node head, int data) { // This function is only // for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } static Node addBegin(Node head, int data) { if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } // function for traversing the list static void traverse(Node head) { Node p; // If list is empty, return. if (head == null) { Console.Write(\"List is empty.\"); return; } // Pointing to first // Node of the list. p = head; // Traversing the list. do { Console.Write(p.data + \" \"); p = p.next; } while (p != head); } // Function to exchange // first and last node static Node exchangeNodes(Node head) { // If list is of length 2 if (head.next.next == head) { head = head.next; return head; } // Find pointer to previous // of last node Node p = head; while (p.next.next != head) p = p.next; // Exchange first and last // nodes using head and p p.next.next = head.next; head.next = p.next; p.next = head; head = head.next; return head; } // Driver Code public static void Main() { int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); Console.Write(\"List Before: \"); traverse(head); Console.WriteLine(); Console.Write(\"List After: \"); head = exchangeNodes(head); traverse(head); }} /* This code is contributed PrinciRaj1992 */", "e": 9534, "s": 7262, "text": null }, { "code": "<script>// javascript program to exchange// first and last node in// circular linked list class Node { constructor() { this.data = 0; this.next = null; }} function addToEmpty(head , data) { // This function is only // for empty list if (head != null) return head; // Creating a node dynamically. var temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } function addBegin(head , data) { if (head == null) return addToEmpty(head, data); var temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } // function for traversing the list function traverse(head) { var p; // If list is empty, return. if (head == null) { document.write(\"List is empty.\"); return; } // Pointing to first // Node of the list. p = head; // Traversing the list. do { document.write(p.data + \" \"); p = p.next; } while (p != head); } // Function to exchange // first and last node function exchangeNodes(head) { // If list is of length 2 if (head.next.next == head) { head = head.next; return head; } // Find pointer to previous // of last node var p = head; while (p.next.next != head) p = p.next; // Exchange first and last // nodes using head and p p.next.next = head.next; head.next = p.next; p.next = head; head = head.next; return head; } // Driver Code var i; var head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); document.write(\"List Before: \"); traverse(head); document.write(\"<br/>\"); document.write(\"List After: \"); head = exchangeNodes(head); traverse(head); // This code is contributed by umadevi9616</script>", "e": 11726, "s": 9534, "text": null }, { "code": null, "e": 11777, "s": 11726, "text": "List Before: 6 1 2 3 4 5 \nList After: 5 1 2 3 4 6 " }, { "code": null, "e": 11832, "s": 11777, "text": "Method 2: (By Swapping Values of First and Last nodes)" }, { "code": null, "e": 11950, "s": 11832, "text": "Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list." }, { "code": null, "e": 12010, "s": 11950, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 12022, "s": 12010, "text": "Algorithm: " }, { "code": null, "e": 12097, "s": 12022, "text": "Traverse the list and find the last node(tail).Swap data of head and tail." }, { "code": null, "e": 12145, "s": 12097, "text": "Traverse the list and find the last node(tail)." }, { "code": null, "e": 12173, "s": 12145, "text": "Swap data of head and tail." }, { "code": null, "e": 12219, "s": 12173, "text": "Below is the implementation of the algorithm:" }, { "code": null, "e": 12223, "s": 12219, "text": "C++" }, { "code": null, "e": 12228, "s": 12223, "text": "Java" }, { "code": null, "e": 12236, "s": 12228, "text": "Python3" }, { "code": null, "e": 12239, "s": 12236, "text": "C#" }, { "code": null, "e": 12250, "s": 12239, "text": "Javascript" }, { "code": "// CPP program to exchange first and// last node in circular linked list#include <bits/stdc++.h>using namespace std; struct Node { int data; struct Node* next;}; struct Node* addToEmpty(struct Node* head, int data){ // This function is only for empty list if (head != NULL) return head; // Creating a node dynamically. struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); // Assigning the data. temp->data = data; head = temp; // Creating the link. head->next = head; return head;} struct Node* addBegin(struct Node* head, int data){ if (head == NULL) return addToEmpty(head, data); struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = data; temp->next = head->next; head->next = temp; return head;} /* function for traversing the list */void traverse(struct Node* head){ struct Node* p; // If list is empty, return. if (head == NULL) { cout << \"List is empty.\" << endl; return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { cout << p->data << \" \"; p = p->next; } while (p != head);} /* Function to exchange first and last node*/struct Node* exchangeNodes(struct Node* head){ // If list is of length less than 2 if (head == NULL || head->next == NULL) { return head; } Node* tail = head; // Find pointer to the last node while (tail->next != head) { tail = tail->next; } /* Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail->data; tail->data = head->data; head->data = temp; return head;} // Driven Programint main(){ int i; struct Node* head = NULL; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); cout << \"List Before: \"; traverse(head); cout << endl; cout << \"List After: \"; head = exchangeNodes(head); traverse(head); return 0;}", "e": 14304, "s": 12250, "text": null }, { "code": "// JAVA program to exchange first and// last node in circular linked listclass GFG{ static class Node { int data; Node next;}; static Node addToEmpty(Node head, int data){ // This function is only for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head;} static Node addBegin(Node head, int data){ if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head;} /* function for traversing the list */static void traverse(Node head){ Node p; // If list is empty, return. if (head == null) { System.out.print(\"List is empty.\" +\"\\n\"); return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { System.out.print(p.data+ \" \"); p = p.next; } while (p != head);} /* Function to exchange first and last node*/static Node exchangeNodes(Node head){ // If list is of length less than 2 if (head == null || head.next == null) { return head; } Node tail = head; // Find pointer to the last node while (tail.next != head) { tail = tail.next; } /* Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail.data; tail.data = head.data; head.data = temp; return head;} // Driven Programpublic static void main(String[] args){ int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); System.out.print(\"List Before: \"); traverse(head); System.out.println(); System.out.print(\"List After: \"); head = exchangeNodes(head); traverse(head); }} // This code is contributed by umadevi9616", "e": 16291, "s": 14304, "text": null }, { "code": "# Python program to exchange first and# last node in circular linked list class Node {class Node: def __init__(self): self.data = 0 self.next = None def addToEmpty(head, data): # This function is only for empty list if (head != None): return head # Creating a node dynamically. temp = Node() # Assigning the data. temp.data = data head = temp # Creating the link. head.next = head return head def addBegin(head, data): if (head == None): return addToEmpty(head, data) temp = Node() temp.data = data temp.next = head.next head.next = temp return head # function for traversing the listdef traverse(head): # If list is empty, return. if (head == None): print(\"List is empty.\") return # Pointing to first Node of the list. p = head # Traversing the list. while (True): print(p.data, end=\" \") p = p.next if(p == head): break # Function to exchange first and last nodedef exchangeNodes(head): # If list is of length less than 2 if (head == None or head.next == None): return head tail = head # Find pointer to the last node while (tail.next != head): tail = tail.next # Exchange first and last nodes using head and p # temporary variable to store # head data temp = tail.data tail.data = head.data head.data = temp return head # Driven Programhead = Nonehead = addToEmpty(head, 6) for i in range(5, 0, -1): head = addBegin(head, i) print(\"List Before: \")traverse(head)print(\"\") print(\"List After: \")head = exchangeNodes(head)traverse(head) # This code is contributed by Saurabh Jaiswal", "e": 17988, "s": 16291, "text": null }, { "code": "// C# program to exchange first and// last node in circular linked listusing System; public class GFG { public class Node { public int data; public Node next; }; static Node addToEmpty(Node head, int data) { // This function is only for empty list if (head != null) return head; // Creating a node dynamically. Node temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } static Node addBegin(Node head, int data) { if (head == null) return addToEmpty(head, data); Node temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } /* function for traversing the list */ static void traverse(Node head) { Node p; // If list is empty, return. if (head == null) { Console.Write(\"List is empty.\" + \"\\n\"); return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { Console.Write(p.data + \" \"); p = p.next; } while (p != head); } /* Function to exchange first and last node */ static Node exchangeNodes(Node head) { // If list is of length less than 2 if (head == null || head.next == null) { return head; } Node tail = head; // Find pointer to the last node while (tail.next != head) { tail = tail.next; } /* * Exchange first and last nodes using head and p */ // temporary variable to store // head data int temp = tail.data; tail.data = head.data; head.data = temp; return head; } // Driven Program public static void Main(String[] args) { int i; Node head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); Console.Write(\"List Before: \"); traverse(head); Console.WriteLine(); Console.Write(\"List After: \"); head = exchangeNodes(head); traverse(head); }} // This code is contributed by umadevi9616", "e": 20288, "s": 17988, "text": null }, { "code": "<script>// javascript program to exchange first and// last node in circular linked list class Node {class Node { constructor() { this.data = 0; this.next = null; }} function addToEmpty(head , data) { // This function is only for empty list if (head != null) return head; // Creating a node dynamically. var temp = new Node(); // Assigning the data. temp.data = data; head = temp; // Creating the link. head.next = head; return head; } function addBegin(head , data) { if (head == null) return addToEmpty(head, data); var temp = new Node(); temp.data = data; temp.next = head.next; head.next = temp; return head; } /* function for traversing the list */ function traverse(head) { var p; // If list is empty, return. if (head == null) { document.write(\"List is empty.\" + \"\\n\"); return; } // Pointing to first Node of the list. p = head; // Traversing the list. do { document.write(p.data + \" \"); p = p.next; } while (p != head); } /* Function to exchange first and last node */ function exchangeNodes(head) { // If list is of length less than 2 if (head == null || head.next == null) { return head; }var tail = head; // Find pointer to the last node while (tail.next != head) { tail = tail.next; } /* * Exchange first and last nodes using head and p */ // temporary variable to store // head data var temp = tail.data; tail.data = head.data; head.data = temp; return head; } // Driven Program var i; var head = null; head = addToEmpty(head, 6); for (i = 5; i > 0; i--) head = addBegin(head, i); document.write(\"List Before: <br/>\"); traverse(head); document.write(\"<br/>\"); document.write(\"List After: <br/>\"); head = exchangeNodes(head); traverse(head); // This code is contributed by umadevi9616</script>", "e": 22524, "s": 20288, "text": null }, { "code": null, "e": 22578, "s": 22527, "text": "List Before: 6 1 2 3 4 5 \nList After: 5 1 2 3 4 6 " }, { "code": null, "e": 22698, "s": 22580, "text": "Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list." }, { "code": null, "e": 22758, "s": 22698, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 23177, "s": 22760, "text": " This article is contributed by R_Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 23190, "s": 23179, "text": "andrew1234" }, { "code": null, "e": 23204, "s": 23190, "text": "princiraj1992" }, { "code": null, "e": 23219, "s": 23204, "text": "sapnasingh4991" }, { "code": null, "e": 23232, "s": 23219, "text": "vinaykumar71" }, { "code": null, "e": 23247, "s": 23232, "text": "ritwikneema651" }, { "code": null, "e": 23262, "s": 23247, "text": "prathamjha5683" }, { "code": null, "e": 23274, "s": 23262, "text": "umadevi9616" }, { "code": null, "e": 23291, "s": 23274, "text": "_saurabh_jaiswal" }, { "code": null, "e": 23299, "s": 23291, "text": "rohan07" }, { "code": null, "e": 23320, "s": 23299, "text": "circular linked list" }, { "code": null, "e": 23332, "s": 23320, "text": "Linked List" }, { "code": null, "e": 23344, "s": 23332, "text": "Linked List" }, { "code": null, "e": 23365, "s": 23344, "text": "circular linked list" }, { "code": null, "e": 23463, "s": 23365, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23495, "s": 23463, "text": "Introduction to Data Structures" }, { "code": null, "e": 23559, "s": 23495, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 23580, "s": 23559, "text": "Types of Linked List" }, { "code": null, "e": 23620, "s": 23580, "text": "Circular Singly Linked List | Insertion" }, { "code": null, "e": 23661, "s": 23620, "text": "Find first node of loop in a linked list" }, { "code": null, "e": 23713, "s": 23661, "text": "Add two numbers represented by linked lists | Set 2" }, { "code": null, "e": 23738, "s": 23713, "text": "Flattening a Linked List" }, { "code": null, "e": 23779, "s": 23738, "text": "Real-time application of Data Structures" }, { "code": null, "e": 23833, "s": 23779, "text": "Insert a node at a specific position in a linked list" } ]
Django Basic App Model – Makemigrations and Migrate
11 Feb, 2020 In this article, we will create a basic model of an app. Say, we have a project geeksforgeeks in which we will create a new app in order to simplify and make independent model units. To create an app run command through terminal : python manage.py startapp geeks and add geeks to INSTALLED_APPS list in settings.py. Now directory structure of the app will be, Now go to models.py in geeks app, Here we will create our first model. To create a model you need to first import the Model from django.db.models library. Now models.py will look like, # importing Model from djangofrom django.db.models import Model According to Django documentation, A model is the single, definitive source of information about your data. It contains the essential fields and behaviours of the data you’re storing. Generally, each model maps to a single database table. Django provides a number of predefined fields and methods to create a Model. To create a model you need to specify a model name first. Enter the following code into models.py from django.db import modelsfrom django.db.models import Model# Created an empty model class GeeksModel(Model): pass The similar syntax would always be used to create a model.After making any change in any of app’s models file you need to run following command from the terminal Python manage.py makemigrations After this command run following command to finally implement database changes accordingly Python manage.py migrate After you run makemigrations and migrate a new table would have been created in database. You can check it from geeks -> makemigrations -> 0001_initial.py. # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID')),], ), ] Let’s understand clearly what Makemigrations and Migrate do. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created apps’ model which you add in installed apps. It does not execute those commands in your database file. So tables are not created after makemigrations. After applying makemigrations you can see those SQL commands with sqlmigrate which shows all the SQL commands which have been generated by makemigrations. To check more about makemigrations visit – Django App Model – Python manage.py makemigrations command migrate executes those SQL commands in the database file. So after executing migrate all the tables of your installed apps are created in your database file. You can confirm this by installing sqlite browser and opening db.sqlite3 you can see all the tables appears in the database file after executing migrate command. To check more about makemigrations visit Django manage.py migrate command | Python NaveenArora Django-basics Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Feb, 2020" }, { "code": null, "e": 235, "s": 52, "text": "In this article, we will create a basic model of an app. Say, we have a project geeksforgeeks in which we will create a new app in order to simplify and make independent model units." }, { "code": null, "e": 283, "s": 235, "text": "To create an app run command through terminal :" }, { "code": null, "e": 315, "s": 283, "text": "python manage.py startapp geeks" }, { "code": null, "e": 412, "s": 315, "text": "and add geeks to INSTALLED_APPS list in settings.py. Now directory structure of the app will be," }, { "code": null, "e": 567, "s": 412, "text": "Now go to models.py in geeks app, Here we will create our first model. To create a model you need to first import the Model from django.db.models library." }, { "code": null, "e": 597, "s": 567, "text": "Now models.py will look like," }, { "code": "# importing Model from djangofrom django.db.models import Model", "e": 661, "s": 597, "text": null }, { "code": null, "e": 900, "s": 661, "text": "According to Django documentation, A model is the single, definitive source of information about your data. It contains the essential fields and behaviours of the data you’re storing. Generally, each model maps to a single database table." }, { "code": null, "e": 1035, "s": 900, "text": "Django provides a number of predefined fields and methods to create a Model. To create a model you need to specify a model name first." }, { "code": null, "e": 1075, "s": 1035, "text": "Enter the following code into models.py" }, { "code": "from django.db import modelsfrom django.db.models import Model# Created an empty model class GeeksModel(Model): pass", "e": 1195, "s": 1075, "text": null }, { "code": null, "e": 1357, "s": 1195, "text": "The similar syntax would always be used to create a model.After making any change in any of app’s models file you need to run following command from the terminal" }, { "code": null, "e": 1390, "s": 1357, "text": " Python manage.py makemigrations" }, { "code": null, "e": 1481, "s": 1390, "text": "After this command run following command to finally implement database changes accordingly" }, { "code": null, "e": 1508, "s": 1481, "text": " Python manage.py migrate " }, { "code": null, "e": 1664, "s": 1508, "text": "After you run makemigrations and migrate a new table would have been created in database. You can check it from geeks -> makemigrations -> 0001_initial.py." }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID')),], ), ]", "e": 2105, "s": 1664, "text": null }, { "code": null, "e": 2166, "s": 2105, "text": "Let’s understand clearly what Makemigrations and Migrate do." }, { "code": null, "e": 2469, "s": 2166, "text": "makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created apps’ model which you add in installed apps. It does not execute those commands in your database file. So tables are not created after makemigrations." }, { "code": null, "e": 2726, "s": 2469, "text": "After applying makemigrations you can see those SQL commands with sqlmigrate which shows all the SQL commands which have been generated by makemigrations. To check more about makemigrations visit – Django App Model – Python manage.py makemigrations command" }, { "code": null, "e": 2884, "s": 2726, "text": "migrate executes those SQL commands in the database file. So after executing migrate all the tables of your installed apps are created in your database file." }, { "code": null, "e": 3129, "s": 2884, "text": "You can confirm this by installing sqlite browser and opening db.sqlite3 you can see all the tables appears in the database file after executing migrate command. To check more about makemigrations visit Django manage.py migrate command | Python" }, { "code": null, "e": 3141, "s": 3129, "text": "NaveenArora" }, { "code": null, "e": 3155, "s": 3141, "text": "Django-basics" }, { "code": null, "e": 3169, "s": 3155, "text": "Python Django" }, { "code": null, "e": 3176, "s": 3169, "text": "Python" } ]
Teradata - Statistics
Teradata optimizer comes up with an execution strategy for every SQL query. This execution strategy is based on the statistics collected on the tables used within the SQL query. Statistics on the table is collected using COLLECT STATISTICS command. Optimizer requires environment information and data demographics to come up with optimal execution strategy. Number of Nodes, AMPs and CPUs Amount of memory Number of rows Row size Range of values in the table Number of rows per value Number of Nulls There are three approaches to collect statistics on the table. Random AMP Sampling Full statistics collection Using SAMPLE option COLLECT STATISTICS command is used to collect statistics on a table. Following is the basic syntax to collect statistics on a table. COLLECT [SUMMARY] STATISTICS INDEX (indexname) COLUMN (columnname) ON <tablename>; The following example collects statistics on EmployeeNo column of Employee table. COLLECT STATISTICS COLUMN(EmployeeNo) ON Employee; When the above query is executed, it produces the following output. *** Update completed. 2 rows changed. *** Total elapsed time was 1 second. You can view the collected statistics using HELP STATISTICS command. Following is the syntax to view the statistics collected. HELP STATISTICS <tablename>; Following is an example to view the statistics collected on Employee table. HELP STATISTICS employee; When the above query is executed, it produces the following result. Date Time Unique Values Column Names -------- -------- -------------------- ----------------------- 16/01/01 08:07:04 5 * 16/01/01 07:24:16 3 DepartmentNo 16/01/01 08:07:04 5 EmployeeNo
[ { "code": null, "e": 3122, "s": 2764, "text": "Teradata optimizer comes up with an execution strategy for every SQL query. This execution strategy is based on the statistics collected on the tables used within the SQL query. Statistics on the table is collected using COLLECT STATISTICS command. Optimizer requires environment information and data demographics to come up with optimal execution strategy." }, { "code": null, "e": 3153, "s": 3122, "text": "Number of Nodes, AMPs and CPUs" }, { "code": null, "e": 3170, "s": 3153, "text": "Amount of memory" }, { "code": null, "e": 3185, "s": 3170, "text": "Number of rows" }, { "code": null, "e": 3194, "s": 3185, "text": "Row size" }, { "code": null, "e": 3223, "s": 3194, "text": "Range of values in the table" }, { "code": null, "e": 3248, "s": 3223, "text": "Number of rows per value" }, { "code": null, "e": 3264, "s": 3248, "text": "Number of Nulls" }, { "code": null, "e": 3327, "s": 3264, "text": "There are three approaches to collect statistics on the table." }, { "code": null, "e": 3347, "s": 3327, "text": "Random AMP Sampling" }, { "code": null, "e": 3374, "s": 3347, "text": "Full statistics collection" }, { "code": null, "e": 3394, "s": 3374, "text": "Using SAMPLE option" }, { "code": null, "e": 3463, "s": 3394, "text": "COLLECT STATISTICS command is used to collect statistics on a table." }, { "code": null, "e": 3527, "s": 3463, "text": "Following is the basic syntax to collect statistics on a table." }, { "code": null, "e": 3615, "s": 3527, "text": "COLLECT [SUMMARY] STATISTICS \nINDEX (indexname) COLUMN (columnname) \nON <tablename>;\n" }, { "code": null, "e": 3697, "s": 3615, "text": "The following example collects statistics on EmployeeNo column of Employee table." }, { "code": null, "e": 3748, "s": 3697, "text": "COLLECT STATISTICS COLUMN(EmployeeNo) ON Employee;" }, { "code": null, "e": 3816, "s": 3748, "text": "When the above query is executed, it produces the following output." }, { "code": null, "e": 3893, "s": 3816, "text": "*** Update completed. 2 rows changed. \n*** Total elapsed time was 1 second.\n" }, { "code": null, "e": 3962, "s": 3893, "text": "You can view the collected statistics using HELP STATISTICS command." }, { "code": null, "e": 4020, "s": 3962, "text": "Following is the syntax to view the statistics collected." }, { "code": null, "e": 4051, "s": 4020, "text": "HELP STATISTICS <tablename>; \n" }, { "code": null, "e": 4127, "s": 4051, "text": "Following is an example to view the statistics collected on Employee table." }, { "code": null, "e": 4153, "s": 4127, "text": "HELP STATISTICS employee;" }, { "code": null, "e": 4221, "s": 4153, "text": "When the above query is executed, it produces the following result." } ]
Maximum element in min heap
28 May, 2021 Given a min heap, find the maximum element present in the heap.Examples: Input : 10 / \ 25 23 / \ / \ 45 30 50 40 Output : 50 Input : 20 / \ 40 28 Output : 40 Brute force approach: We can check all the nodes in the min-heap to get the maximum element. Note that this approach works on any binary tree and does not makes use of any property of the min-heap. It has a time and space complexity of O(n). Since min-heap is a complete binary tree, we generally use arrays to store them, so we can check all the nodes by simply traversing the array. If the heap is stored using pointers, then we can use recursion to check all the nodes.Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// maximum element in a// min heapint findMaximumElement(int heap[], int n){ int maximumElement = heap[0]; for (int i = 1; i < n; ++i) maximumElement = max(maximumElement, heap[i]); return maximumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / // 63 65 81 int heap[] = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; cout << findMaximumElement(heap, n); return 0;} // Java implementation of above approachclass GFG {// Function to find the maximum element// in a min heap static int findMaximumElement(int[] heap, int n) { int maximumElement = heap[0]; for (int i = 1; i < n; ++i) { maximumElement = Math.max(maximumElement, heap[i]); } return maximumElement; } // Driver code public static void main(String[] args) { // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / //63 65 81 int[] heap = {10, 25, 23, 45, 50, 30, 35, 63, 65, 81}; System.out.print(findMaximumElement(heap, n)); }}// This code is contributed by PrinciRaj1992 # Python3 implementation of above approach # Function to find the maximum element# in a min heapdef findMaximumElement(heap, n): maximumElement = heap[0]; for i in range(1, n): maximumElement = max(maximumElement, heap[i]); return maximumElement; # Driver codeif __name__ == '__main__': # Number of nodes n = 10; # heap represents the following min heap: # 10 # / \ # 25 23 # / \ / \ # 45 50 30 35 # / \ / #63 65 81 heap = [ 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 ]; print(findMaximumElement(heap, n)); # This code is contributed by Princi Singh // C# implementation of above approachusing System; class GFG{// Function to find the maximum element// in a min heapstatic int findMaximumElement(int[] heap, int n){ int maximumElement = heap[0]; for (int i = 1; i < n; ++i) maximumElement = Math.Max(maximumElement, heap[i]); return maximumElement;} // Driver codepublic static void Main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / //63 65 81 int[] heap = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; Console.Write(findMaximumElement(heap, n));}} // This code is contributed by Akanksha Rai <script> // JavaScript implementation of above approach // Function to find the maximum element// in a min heap function findMaximumElement(heap , n) { var maximumElement = heap[0]; for (i = 1; i < n; ++i) { maximumElement = Math.max(maximumElement, heap[i]); } return maximumElement; } // Driver code // Number of nodes var n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / //63 65 81 var heap = [10, 25, 23, 45, 50, 30, 35, 63, 65, 81]; document.write(findMaximumElement(heap, n)); // This code contributed by aashish1995 </script> Output: 81 Efficient approach: The min heap property requires that the parent node be lesser than its child node(s). Due to this, we can conclude that a non-leaf node cannot be the maximum element as its child node has a higher value. So we can narrow down our search space to only leaf nodes. In a min heap having n elements, there is ceil(n/2) leaf nodes. The time and space complexity remains O(n) as a constant factor of 1/2 does not affect the asymptotic complexity.Below is the implementation of above approach: C++14 Java Python 3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// maximumelement in a// max heapint findMaximumElement(int heap[], int n){ int maximumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) maximumElement = max(maximumElement, heap[i]); return maximumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / //63 65 81 int heap[] = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; cout << findMaximumElement(heap, n); return 0;} // Java implementation of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the// maximumelement in a// max heapstatic int findMaximumElement(int heap[], int n){ int maximumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) maximumElement = Math.max(maximumElement, heap[i]); return maximumElement;} // Driver codepublic static void main(String args[]){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / //63 65 81 int heap[] = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; System.out.println(findMaximumElement(heap, n)); }} # Python 3 implementation of# above approach # Function to find the maximum# element in a max heapdef findMaximumElement(heap, n): maximumElement = heap[n // 2] for i in range(1 + n // 2, n): maximumElement = max(maximumElement, heap[i]) return maximumElement # Driver Coden = 10 # Numbers Of Node # heap represents the following min heap:# 10# / \# 25 23# / \ / \# 45 50 30 35# / \ /# 63 65 81 heap = [10, 25, 23, 45, 50, 30, 35, 63, 65, 81]print(findMaximumElement(heap, n)) # This code is contributed by Yogesh Joshi // C# implementation of above approachusing System; class GFG{ // Function to find the// maximumelement in a// max heapstatic int findMaximumElement(int[] heap, int n){ int maximumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) maximumElement = Math.Max(maximumElement, heap[i]); return maximumElement;} // Driver codepublic static void Main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / //63 65 81 int[] heap = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; Console.WriteLine(findMaximumElement(heap, n));}} // This code is contributed// by Akanksha Rai <script>// javascript implementation of above approach // Function to find the // maximumelement in a // max heap function findMaximumElement(heap , n) { var maximumElement = heap[n / 2]; for (i = 1 + n / 2; i < n; ++i) maximumElement = Math.max(maximumElement, heap[i]); return maximumElement; } // Driver code // Number of nodes var n = 10; // heap represents the following min heap: // 10 // / \ // 25 23 // / \ / \ // 45 50 30 35 // / \ / // 63 65 81 var heap = [ 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 ]; document.write(findMaximumElement(heap, n)); // This code contributed by aashish1995</script> Output: 81 tufan_gupta2000 joshiyogesh Akanksha_Rai princiraj1992 princi singh trusted fabrizzioorderique aashish1995 Technical Scripter 2018 Heap Technical Scripter Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Sliding Window Maximum (Maximum of all subarrays of size k) Building Heap from Array Max Heap in Java Priority Queue in Python Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Insertion and Deletion in Heaps Sort a nearly sorted (or K sorted) array Merge k sorted arrays | Set 1 Heap in C++ STL | make_heap(), push_heap(), pop_heap(), sort_heap(), is_heap, is_heap_until()
[ { "code": null, "e": 54, "s": 26, "text": "\n28 May, 2021" }, { "code": null, "e": 129, "s": 54, "text": "Given a min heap, find the maximum element present in the heap.Examples: " }, { "code": null, "e": 307, "s": 129, "text": "Input : 10 \n / \\ \n 25 23 \n / \\ / \\\n 45 30 50 40\nOutput : 50\n\nInput : 20\n / \\ \n 40 28\nOutput : 40" }, { "code": null, "e": 828, "s": 307, "text": "Brute force approach: We can check all the nodes in the min-heap to get the maximum element. Note that this approach works on any binary tree and does not makes use of any property of the min-heap. It has a time and space complexity of O(n). Since min-heap is a complete binary tree, we generally use arrays to store them, so we can check all the nodes by simply traversing the array. If the heap is stored using pointers, then we can use recursion to check all the nodes.Below is the implementation of above approach: " }, { "code": null, "e": 832, "s": 828, "text": "C++" }, { "code": null, "e": 837, "s": 832, "text": "Java" }, { "code": null, "e": 845, "s": 837, "text": "Python3" }, { "code": null, "e": 848, "s": 845, "text": "C#" }, { "code": null, "e": 859, "s": 848, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// maximum element in a// min heapint findMaximumElement(int heap[], int n){ int maximumElement = heap[0]; for (int i = 1; i < n; ++i) maximumElement = max(maximumElement, heap[i]); return maximumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / // 63 65 81 int heap[] = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; cout << findMaximumElement(heap, n); return 0;}", "e": 1521, "s": 859, "text": null }, { "code": "// Java implementation of above approachclass GFG {// Function to find the maximum element// in a min heap static int findMaximumElement(int[] heap, int n) { int maximumElement = heap[0]; for (int i = 1; i < n; ++i) { maximumElement = Math.max(maximumElement, heap[i]); } return maximumElement; } // Driver code public static void main(String[] args) { // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / //63 65 81 int[] heap = {10, 25, 23, 45, 50, 30, 35, 63, 65, 81}; System.out.print(findMaximumElement(heap, n)); }}// This code is contributed by PrinciRaj1992", "e": 2335, "s": 1521, "text": null }, { "code": "# Python3 implementation of above approach # Function to find the maximum element# in a min heapdef findMaximumElement(heap, n): maximumElement = heap[0]; for i in range(1, n): maximumElement = max(maximumElement, heap[i]); return maximumElement; # Driver codeif __name__ == '__main__': # Number of nodes n = 10; # heap represents the following min heap: # 10 # / \\ # 25 23 # / \\ / \\ # 45 50 30 35 # / \\ / #63 65 81 heap = [ 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 ]; print(findMaximumElement(heap, n)); # This code is contributed by Princi Singh", "e": 2963, "s": 2335, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{// Function to find the maximum element// in a min heapstatic int findMaximumElement(int[] heap, int n){ int maximumElement = heap[0]; for (int i = 1; i < n; ++i) maximumElement = Math.Max(maximumElement, heap[i]); return maximumElement;} // Driver codepublic static void Main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / //63 65 81 int[] heap = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; Console.Write(findMaximumElement(heap, n));}} // This code is contributed by Akanksha Rai", "e": 3707, "s": 2963, "text": null }, { "code": "<script> // JavaScript implementation of above approach // Function to find the maximum element// in a min heap function findMaximumElement(heap , n) { var maximumElement = heap[0]; for (i = 1; i < n; ++i) { maximumElement = Math.max(maximumElement, heap[i]); } return maximumElement; } // Driver code // Number of nodes var n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / //63 65 81 var heap = [10, 25, 23, 45, 50, 30, 35, 63, 65, 81]; document.write(findMaximumElement(heap, n)); // This code contributed by aashish1995 </script>", "e": 4469, "s": 3707, "text": null }, { "code": null, "e": 4479, "s": 4469, "text": "Output: " }, { "code": null, "e": 4482, "s": 4479, "text": "81" }, { "code": null, "e": 4991, "s": 4482, "text": "Efficient approach: The min heap property requires that the parent node be lesser than its child node(s). Due to this, we can conclude that a non-leaf node cannot be the maximum element as its child node has a higher value. So we can narrow down our search space to only leaf nodes. In a min heap having n elements, there is ceil(n/2) leaf nodes. The time and space complexity remains O(n) as a constant factor of 1/2 does not affect the asymptotic complexity.Below is the implementation of above approach: " }, { "code": null, "e": 4997, "s": 4991, "text": "C++14" }, { "code": null, "e": 5002, "s": 4997, "text": "Java" }, { "code": null, "e": 5011, "s": 5002, "text": "Python 3" }, { "code": null, "e": 5014, "s": 5011, "text": "C#" }, { "code": null, "e": 5025, "s": 5014, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to find the// maximumelement in a// max heapint findMaximumElement(int heap[], int n){ int maximumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) maximumElement = max(maximumElement, heap[i]); return maximumElement;} // Driver codeint main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / //63 65 81 int heap[] = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; cout << findMaximumElement(heap, n); return 0;}", "e": 5697, "s": 5025, "text": null }, { "code": "// Java implementation of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find the// maximumelement in a// max heapstatic int findMaximumElement(int heap[], int n){ int maximumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) maximumElement = Math.max(maximumElement, heap[i]); return maximumElement;} // Driver codepublic static void main(String args[]){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / //63 65 81 int heap[] = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; System.out.println(findMaximumElement(heap, n)); }}", "e": 6443, "s": 5697, "text": null }, { "code": "# Python 3 implementation of# above approach # Function to find the maximum# element in a max heapdef findMaximumElement(heap, n): maximumElement = heap[n // 2] for i in range(1 + n // 2, n): maximumElement = max(maximumElement, heap[i]) return maximumElement # Driver Coden = 10 # Numbers Of Node # heap represents the following min heap:# 10# / \\# 25 23# / \\ / \\# 45 50 30 35# / \\ /# 63 65 81 heap = [10, 25, 23, 45, 50, 30, 35, 63, 65, 81]print(findMaximumElement(heap, n)) # This code is contributed by Yogesh Joshi", "e": 7089, "s": 6443, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to find the// maximumelement in a// max heapstatic int findMaximumElement(int[] heap, int n){ int maximumElement = heap[n / 2]; for (int i = 1 + n / 2; i < n; ++i) maximumElement = Math.Max(maximumElement, heap[i]); return maximumElement;} // Driver codepublic static void Main(){ // Number of nodes int n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / //63 65 81 int[] heap = { 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 }; Console.WriteLine(findMaximumElement(heap, n));}} // This code is contributed// by Akanksha Rai", "e": 7882, "s": 7089, "text": null }, { "code": "<script>// javascript implementation of above approach // Function to find the // maximumelement in a // max heap function findMaximumElement(heap , n) { var maximumElement = heap[n / 2]; for (i = 1 + n / 2; i < n; ++i) maximumElement = Math.max(maximumElement, heap[i]); return maximumElement; } // Driver code // Number of nodes var n = 10; // heap represents the following min heap: // 10 // / \\ // 25 23 // / \\ / \\ // 45 50 30 35 // / \\ / // 63 65 81 var heap = [ 10, 25, 23, 45, 50, 30, 35, 63, 65, 81 ]; document.write(findMaximumElement(heap, n)); // This code contributed by aashish1995</script>", "e": 8630, "s": 7882, "text": null }, { "code": null, "e": 8639, "s": 8630, "text": "Output: " }, { "code": null, "e": 8643, "s": 8639, "text": "81 " }, { "code": null, "e": 8659, "s": 8643, "text": "tufan_gupta2000" }, { "code": null, "e": 8671, "s": 8659, "text": "joshiyogesh" }, { "code": null, "e": 8684, "s": 8671, "text": "Akanksha_Rai" }, { "code": null, "e": 8698, "s": 8684, "text": "princiraj1992" }, { "code": null, "e": 8711, "s": 8698, "text": "princi singh" }, { "code": null, "e": 8719, "s": 8711, "text": "trusted" }, { "code": null, "e": 8738, "s": 8719, "text": "fabrizzioorderique" }, { "code": null, "e": 8750, "s": 8738, "text": "aashish1995" }, { "code": null, "e": 8774, "s": 8750, "text": "Technical Scripter 2018" }, { "code": null, "e": 8779, "s": 8774, "text": "Heap" }, { "code": null, "e": 8798, "s": 8779, "text": "Technical Scripter" }, { "code": null, "e": 8803, "s": 8798, "text": "Heap" }, { "code": null, "e": 8901, "s": 8803, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8933, "s": 8901, "text": "Introduction to Data Structures" }, { "code": null, "e": 8993, "s": 8933, "text": "Sliding Window Maximum (Maximum of all subarrays of size k)" }, { "code": null, "e": 9018, "s": 8993, "text": "Building Heap from Array" }, { "code": null, "e": 9035, "s": 9018, "text": "Max Heap in Java" }, { "code": null, "e": 9060, "s": 9035, "text": "Priority Queue in Python" }, { "code": null, "e": 9130, "s": 9060, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 9162, "s": 9130, "text": "Insertion and Deletion in Heaps" }, { "code": null, "e": 9203, "s": 9162, "text": "Sort a nearly sorted (or K sorted) array" }, { "code": null, "e": 9233, "s": 9203, "text": "Merge k sorted arrays | Set 1" } ]
Select First Row of Each Group in DataFrame in R
23 Sep, 2021 In this article, we will discuss how to select the first row of each group in Dataframe using R programming language. The duplicated() method is used to determine which of the elements of a dataframe are duplicates of other elements. The method returns a logical vector which tells which of the rows of the dataframe are duplicates. Syntax: duplicated(data-frame$col-name) The non-duplicated rows are taken using the complemented duplicated() method, and referred to using the dataframe indexing methods, where all the columns are taken and the rows are the ones filtered out using the duplicated() method. The row numbers of the original dataframe are retained in the final output. Example: Selecting first row from each group R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(c(1:3),2), col3=rep(1:2,3) ) print("Original DataFrame")print(data_frame1) print("Modified DataFrame") # computing sum over rest of columnsdata_frame1[!duplicated(data_frame1$col1), ] Output: [1] "Original DataFrame" col1 col2 col3 1 Grp1 1 1 2 Grp1 2 2 3 Grp2 3 1 4 Grp2 1 2 5 Grp3 2 1 6 Grp3 3 2 [1] "Modified DataFrame" col1 col2 col3 1 Grp1 1 1 3 Grp2 3 1 5 Grp3 2 1 The following code snippet illustrates the usage of duplicated function, applied over multiple columns. The columns can be clubbed together using the c() method. Example: Selecting first row of each group R # create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1,2), col3=rep(1,3) ) print("Original DataFrame")print(data_frame1) # grouping by col3print("Modified DataFrame") # computing groups over col3 and col2data_frame1[!duplicated(c(data_frame1$col3,data_frame1$col2)), ] Output: [1] "Original DataFrame" col1 col2 col3 1 Grp1 1 1 2 Grp1 1 1 3 Grp2 1 1 4 Grp2 1 1 5 Grp3 1 1 6 Grp3 1 1 [1] "Modified DataFrame" col1 col2 col3 1 Grp1 1 1 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 146, "s": 28, "text": "In this article, we will discuss how to select the first row of each group in Dataframe using R programming language." }, { "code": null, "e": 362, "s": 146, "text": "The duplicated() method is used to determine which of the elements of a dataframe are duplicates of other elements. The method returns a logical vector which tells which of the rows of the dataframe are duplicates. " }, { "code": null, "e": 370, "s": 362, "text": "Syntax:" }, { "code": null, "e": 402, "s": 370, "text": "duplicated(data-frame$col-name)" }, { "code": null, "e": 713, "s": 402, "text": "The non-duplicated rows are taken using the complemented duplicated() method, and referred to using the dataframe indexing methods, where all the columns are taken and the rows are the ones filtered out using the duplicated() method. The row numbers of the original dataframe are retained in the final output. " }, { "code": null, "e": 758, "s": 713, "text": "Example: Selecting first row from each group" }, { "code": null, "e": 760, "s": 758, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(c(1:3),2), col3=rep(1:2,3) ) print(\"Original DataFrame\")print(data_frame1) print(\"Modified DataFrame\") # computing sum over rest of columnsdata_frame1[!duplicated(data_frame1$col1), ]", "e": 1188, "s": 760, "text": null }, { "code": null, "e": 1196, "s": 1188, "text": "Output:" }, { "code": null, "e": 1442, "s": 1196, "text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 Grp1 1 1 \n2 Grp1 2 2 \n3 Grp2 3 1 \n4 Grp2 1 2 \n5 Grp3 2 1 \n6 Grp3 3 2 \n[1] \"Modified DataFrame\" \n col1 col2 col3 \n1 Grp1 1 1 \n3 Grp2 3 1 \n5 Grp3 2 1" }, { "code": null, "e": 1605, "s": 1442, "text": "The following code snippet illustrates the usage of duplicated function, applied over multiple columns. The columns can be clubbed together using the c() method. " }, { "code": null, "e": 1649, "s": 1605, "text": "Example: Selecting first row of each group " }, { "code": null, "e": 1651, "s": 1649, "text": "R" }, { "code": "# create first dataframedata_frame1<-data.frame(col1=c(rep('Grp1',2), rep('Grp2',2), rep('Grp3',2)), col2=rep(1,2), col3=rep(1,3) ) print(\"Original DataFrame\")print(data_frame1) # grouping by col3print(\"Modified DataFrame\") # computing groups over col3 and col2data_frame1[!duplicated(c(data_frame1$col3,data_frame1$col2)), ]", "e": 2111, "s": 1651, "text": null }, { "code": null, "e": 2119, "s": 2111, "text": "Output:" }, { "code": null, "e": 2328, "s": 2119, "text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1 Grp1 1 1 \n2 Grp1 1 1 \n3 Grp2 1 1 \n4 Grp2 1 1 \n5 Grp3 1 1 \n6 Grp3 1 1 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 \n1 Grp1 1 1" }, { "code": null, "e": 2335, "s": 2328, "text": "Picked" }, { "code": null, "e": 2356, "s": 2335, "text": "R DataFrame-Programs" }, { "code": null, "e": 2368, "s": 2356, "text": "R-DataFrame" }, { "code": null, "e": 2379, "s": 2368, "text": "R Language" }, { "code": null, "e": 2390, "s": 2379, "text": "R Programs" }, { "code": null, "e": 2488, "s": 2390, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2540, "s": 2488, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2598, "s": 2540, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2633, "s": 2598, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2671, "s": 2633, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2720, "s": 2671, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2778, "s": 2720, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2827, "s": 2778, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2870, "s": 2827, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2908, "s": 2870, "text": "Merge DataFrames by Column Names in R" } ]
How to get Pixel from HTML Canvas ?
22 Nov, 2019 To get the pixel of any specific portion from HTML canvas you can use the HTML canvas getImageData() Method. The getImageData() method usually returns an ImageData object that contains the pixel information of the specified object on the HTML canvas. Example 1: This example will display each pixel value of the square box. The boxes color is linear gradient so the pixels will change the color value that will change simultaneously. Program:<!DOCTYPE html><html> <head> <title> Getting pixel information from html canvas. </title></head> <body> <center> <h1 style="color:green;"> GeeksfoGeeks </h1> <h3> Getting pixel information from html canvas </h3> <canvas id="GFG" width="190" height="100" style="border:1px solid black;"> </canvas> <script> /* Retrieve canvas with id GFG, and store it in a */ var a = document.getElementById("GFG"); /* Retrieve a 2D context for the canvas */ var gfg = a.getContext("2d"); var geeks = gfg.createLinearGradient(0, 0, 200, 0); geeks.addColorStop(0, "green"); geeks.addColorStop(1, "yellow"); gfg.fillStyle = geeks; gfg.fillRect(20, 20, 150, 150); /* Define a function find(), that prints the array containing pixel information returned by the getImageData() method */ function find() { /* Store the pixel information of the canvas at (x,y) coordinate of (20,20) */ var ImageData = gfg.getImageData(20, 20, 60, 60); /* Print the array on console */ console.log(ImageData); } find(); </script> </center></body> </html> <!DOCTYPE html><html> <head> <title> Getting pixel information from html canvas. </title></head> <body> <center> <h1 style="color:green;"> GeeksfoGeeks </h1> <h3> Getting pixel information from html canvas </h3> <canvas id="GFG" width="190" height="100" style="border:1px solid black;"> </canvas> <script> /* Retrieve canvas with id GFG, and store it in a */ var a = document.getElementById("GFG"); /* Retrieve a 2D context for the canvas */ var gfg = a.getContext("2d"); var geeks = gfg.createLinearGradient(0, 0, 200, 0); geeks.addColorStop(0, "green"); geeks.addColorStop(1, "yellow"); gfg.fillStyle = geeks; gfg.fillRect(20, 20, 150, 150); /* Define a function find(), that prints the array containing pixel information returned by the getImageData() method */ function find() { /* Store the pixel information of the canvas at (x,y) coordinate of (20,20) */ var ImageData = gfg.getImageData(20, 20, 60, 60); /* Print the array on console */ console.log(ImageData); } find(); </script> </center></body> </html> Output: Example 2: Code for getting color/alpha information of the first pixel. After running the code you can check by changing the color from the line 36. <!DOCTYPE html><html> <head> <title> Getting pixel information from html canvas. </title></head> <body> <center> <h1 style="color:green;"> GeeksfoGeeks </h1> <h3> Getting pixel information from html canvas </h3> <canvas id="GFG" width="100" height="100" style="border:1px solid black;"> </canvas> <script> // Retrieve canvas with id GFG, // and store it in a var a = document.getElementById("GFG"); // Retrieve a 2D context for the canvas var geeks = a.getContext("2d"); // Set the filling style to red colour geeks.fillStyle = "blue"; /* Move the cursor to the (x,y) coordinate of (20,20) and then create a rectangle of height and width 60 */ geeks.fillRect(20, 20, 60, 60); /* Define a function find(), that prints the colour/alpha information of of the first pixel returned by getImageData() method */ function find() { var ImageData = geeks.getImageData(20, 20, 60, 60); /* Stores the red color information of the first pixel */ red = ImageData.data[0]; /* Stores the green color information of the first pixel */ green = ImageData.data[1]; /* Stores the blue color information of the first pixel */ blue = ImageData.data[2]; /* Stores the opacity of the first pixel */ alpha = ImageData.data[3]; console.log(red); console.log(green); console.log(blue); console.log(alpha); } find(); </script> </center></body> </html> Output: JavaScript-Misc Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2019" }, { "code": null, "e": 279, "s": 28, "text": "To get the pixel of any specific portion from HTML canvas you can use the HTML canvas getImageData() Method. The getImageData() method usually returns an ImageData object that contains the pixel information of the specified object on the HTML canvas." }, { "code": null, "e": 462, "s": 279, "text": "Example 1: This example will display each pixel value of the square box. The boxes color is linear gradient so the pixels will change the color value that will change simultaneously." }, { "code": null, "e": 1989, "s": 462, "text": "Program:<!DOCTYPE html><html> <head> <title> Getting pixel information from html canvas. </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksfoGeeks </h1> <h3> Getting pixel information from html canvas </h3> <canvas id=\"GFG\" width=\"190\" height=\"100\" style=\"border:1px solid black;\"> </canvas> <script> /* Retrieve canvas with id GFG, and store it in a */ var a = document.getElementById(\"GFG\"); /* Retrieve a 2D context for the canvas */ var gfg = a.getContext(\"2d\"); var geeks = gfg.createLinearGradient(0, 0, 200, 0); geeks.addColorStop(0, \"green\"); geeks.addColorStop(1, \"yellow\"); gfg.fillStyle = geeks; gfg.fillRect(20, 20, 150, 150); /* Define a function find(), that prints the array containing pixel information returned by the getImageData() method */ function find() { /* Store the pixel information of the canvas at (x,y) coordinate of (20,20) */ var ImageData = gfg.getImageData(20, 20, 60, 60); /* Print the array on console */ console.log(ImageData); } find(); </script> </center></body> </html>" }, { "code": "<!DOCTYPE html><html> <head> <title> Getting pixel information from html canvas. </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksfoGeeks </h1> <h3> Getting pixel information from html canvas </h3> <canvas id=\"GFG\" width=\"190\" height=\"100\" style=\"border:1px solid black;\"> </canvas> <script> /* Retrieve canvas with id GFG, and store it in a */ var a = document.getElementById(\"GFG\"); /* Retrieve a 2D context for the canvas */ var gfg = a.getContext(\"2d\"); var geeks = gfg.createLinearGradient(0, 0, 200, 0); geeks.addColorStop(0, \"green\"); geeks.addColorStop(1, \"yellow\"); gfg.fillStyle = geeks; gfg.fillRect(20, 20, 150, 150); /* Define a function find(), that prints the array containing pixel information returned by the getImageData() method */ function find() { /* Store the pixel information of the canvas at (x,y) coordinate of (20,20) */ var ImageData = gfg.getImageData(20, 20, 60, 60); /* Print the array on console */ console.log(ImageData); } find(); </script> </center></body> </html>", "e": 3508, "s": 1989, "text": null }, { "code": null, "e": 3516, "s": 3508, "text": "Output:" }, { "code": null, "e": 3665, "s": 3516, "text": "Example 2: Code for getting color/alpha information of the first pixel. After running the code you can check by changing the color from the line 36." }, { "code": "<!DOCTYPE html><html> <head> <title> Getting pixel information from html canvas. </title></head> <body> <center> <h1 style=\"color:green;\"> GeeksfoGeeks </h1> <h3> Getting pixel information from html canvas </h3> <canvas id=\"GFG\" width=\"100\" height=\"100\" style=\"border:1px solid black;\"> </canvas> <script> // Retrieve canvas with id GFG, // and store it in a var a = document.getElementById(\"GFG\"); // Retrieve a 2D context for the canvas var geeks = a.getContext(\"2d\"); // Set the filling style to red colour geeks.fillStyle = \"blue\"; /* Move the cursor to the (x,y) coordinate of (20,20) and then create a rectangle of height and width 60 */ geeks.fillRect(20, 20, 60, 60); /* Define a function find(), that prints the colour/alpha information of of the first pixel returned by getImageData() method */ function find() { var ImageData = geeks.getImageData(20, 20, 60, 60); /* Stores the red color information of the first pixel */ red = ImageData.data[0]; /* Stores the green color information of the first pixel */ green = ImageData.data[1]; /* Stores the blue color information of the first pixel */ blue = ImageData.data[2]; /* Stores the opacity of the first pixel */ alpha = ImageData.data[3]; console.log(red); console.log(green); console.log(blue); console.log(alpha); } find(); </script> </center></body> </html> ", "e": 5646, "s": 3665, "text": null }, { "code": null, "e": 5654, "s": 5646, "text": "Output:" }, { "code": null, "e": 5670, "s": 5654, "text": "JavaScript-Misc" }, { "code": null, "e": 5677, "s": 5670, "text": "Picked" }, { "code": null, "e": 5688, "s": 5677, "text": "JavaScript" }, { "code": null, "e": 5705, "s": 5688, "text": "Web Technologies" }, { "code": null, "e": 5732, "s": 5705, "text": "Web technologies Questions" }, { "code": null, "e": 5830, "s": 5732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5891, "s": 5830, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5963, "s": 5891, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6003, "s": 5963, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6044, "s": 6003, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6090, "s": 6044, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 6152, "s": 6090, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6185, "s": 6152, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6246, "s": 6185, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6296, "s": 6246, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
What is the difference between List and IList in C#?
The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index. The IList interface implemented from two interfaces and they are ICollection and IEnumerable. List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList. The major difference between List and IList is that List is a concrete class and IList is an interface. Overall, List is a concrete type that implements the IList interface. using System; using System.Collections.Generic; namespace DemoApplication{ class Demo{ static void Main(string[] args){ IList<string> ilist = new IList<string>(); //This will throw error as we cannot create instance for an IList as it is an interface. ilist.Add("Mark"); ilist.Add("John"); foreach (string list in ilist){ Console.WriteLine(list); } } } } Live Demo using System; using System.Collections.Generic; namespace DemoApplication{ class Demo{ static void Main(string[] args){ IList<string> ilist = new List<string>(); ilist.Add("Mark"); ilist.Add("John"); List<string> list = new List<string>(); ilist.Add("Mark"); ilist.Add("John"); foreach (string lst in ilist){ Console.WriteLine(lst); } foreach (string lst in list){ Console.WriteLine(lst); } Console.ReadLine(); } } } The output of the above code is Mark John Mark John
[ { "code": null, "e": 1519, "s": 1187, "text": "The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index. The IList interface implemented from two interfaces and they are ICollection and IEnumerable." }, { "code": null, "e": 1886, "s": 1519, "text": "List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList. The major difference between List and IList is that List is a concrete class and IList is an interface. Overall, List is a concrete type that implements the IList interface." }, { "code": null, "e": 2325, "s": 1886, "text": "using System;\nusing System.Collections.Generic;\nnamespace DemoApplication{\n class Demo{\n static void Main(string[] args){\n IList<string> ilist = new IList<string>();\n //This will throw error as we cannot create instance for an IList as it is an interface.\n ilist.Add(\"Mark\");\n ilist.Add(\"John\");\n foreach (string list in ilist){\n Console.WriteLine(list);\n }\n }\n }\n}" }, { "code": null, "e": 2336, "s": 2325, "text": " Live Demo" }, { "code": null, "e": 2894, "s": 2336, "text": "using System;\nusing System.Collections.Generic;\nnamespace DemoApplication{\n class Demo{\n static void Main(string[] args){\n IList<string> ilist = new List<string>();\n ilist.Add(\"Mark\");\n ilist.Add(\"John\");\n List<string> list = new List<string>();\n ilist.Add(\"Mark\");\n ilist.Add(\"John\");\n foreach (string lst in ilist){\n Console.WriteLine(lst);\n }\n foreach (string lst in list){\n Console.WriteLine(lst);\n }\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2926, "s": 2894, "text": "The output of the above code is" }, { "code": null, "e": 2946, "s": 2926, "text": "Mark\nJohn\nMark\nJohn" } ]
How can I trigger a JavaScript click event?
To trigger a JavaScript click event, let us see the example of mouse hover. Live Demo <!DOCTYPE html> <html> <body> <p>Hover over the button.</p> <form> <input type="button" id="test" value="Hover" onmouseover="display()" onclick="alert('click event')"> </form> <script> function display() { document.getElementById("test").click(); } </script> </body> </html>
[ { "code": null, "e": 1263, "s": 1187, "text": "To trigger a JavaScript click event, let us see the example of mouse hover." }, { "code": null, "e": 1273, "s": 1263, "text": "Live Demo" }, { "code": null, "e": 1623, "s": 1273, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Hover over the button.</p>\n <form>\n <input type=\"button\" id=\"test\" value=\"Hover\" onmouseover=\"display()\" onclick=\"alert('click event')\">\n </form>\n <script>\n function display() {\n document.getElementById(\"test\").click();\n }\n </script>\n </body>\n</html>" } ]
Python – List of tuples to multiple lists
23 Aug, 2021 In this article, we will discuss how to convert a List of tuples to multiple lists. We can convert lit of tuples to multiple lists by using the map() function Syntax: map(list, zip(*list_of_tuples) Example: Input: [('a', 'b', 'c'), (1,2,3), ('1','3','4')] Output: ['a', 'b', 'c'], [1, 2, 3], ('1', '3', '4') Example 1: Python code to display a list of tuples and display them. Python3 # list of tuple for student data# with both integer and stringsa = [(1, 2,3,4,5), ("sravan","bobby","ojaswi","rohith","Gnanesh"), (96,89,78,90,78)] # displayprint("Original list of tuple")print(a) # list of tuple for student data # with both integer and stringsa = [(1, 2,3,4,5), ("sravan","bobby","ojaswi","rohith","Gnanesh"), (96,89,78,90,78)] # convert list of tuple to multiple listsdata = map(list, zip(*a)) print("") # display print("List")for i in data: print(i) Output: Original list of tuple [(1, 2, 3, 4, 5), (β€˜sravan’, β€˜bobby’, β€˜ojaswi’, β€˜rohith’, β€˜Gnanesh’), (96, 89, 78, 90, 78)] List [1, β€˜sravan’, 96] [2, β€˜bobby’, 89] [3, β€˜ojaswi’, 78] [4, β€˜rohith’, 90] [5, β€˜Gnanesh’, 78] Example 2: Python code to convert a list of tuples to multiple lists Python3 # list of tuple for student# data with both integer and stringsa = [(1, 2,3,4,5), ("sravan","bobby","ojaswi","rohith","Gnanesh"), (96,89,78,90,78), ("kakumanu","kakumanu","hyd","hyd","hyd")] # convert list of tuple to multiple listsdata = map(list, zip(*a)) # display for i in data: print(i) Output: [1, 'sravan', 96, 'kakumanu'] [2, 'bobby', 89, 'kakumanu'] [3, 'ojaswi', 78, 'hyd'] [4, 'rohith', 90, 'hyd'] [5, 'Gnanesh', 78, 'hyd'] Picked Python List-of-Tuples python-list Python Python Programs python-list 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 Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 187, "s": 28, "text": "In this article, we will discuss how to convert a List of tuples to multiple lists. We can convert lit of tuples to multiple lists by using the map() function" }, { "code": null, "e": 226, "s": 187, "text": "Syntax: map(list, zip(*list_of_tuples)" }, { "code": null, "e": 235, "s": 226, "text": "Example:" }, { "code": null, "e": 336, "s": 235, "text": "Input: [('a', 'b', 'c'), (1,2,3), ('1','3','4')]\nOutput: ['a', 'b', 'c'], [1, 2, 3], ('1', '3', '4')" }, { "code": null, "e": 405, "s": 336, "text": "Example 1: Python code to display a list of tuples and display them." }, { "code": null, "e": 413, "s": 405, "text": "Python3" }, { "code": "# list of tuple for student data# with both integer and stringsa = [(1, 2,3,4,5), (\"sravan\",\"bobby\",\"ojaswi\",\"rohith\",\"Gnanesh\"), (96,89,78,90,78)] # displayprint(\"Original list of tuple\")print(a) # list of tuple for student data # with both integer and stringsa = [(1, 2,3,4,5), (\"sravan\",\"bobby\",\"ojaswi\",\"rohith\",\"Gnanesh\"), (96,89,78,90,78)] # convert list of tuple to multiple listsdata = map(list, zip(*a)) print(\"\") # display print(\"List\")for i in data: print(i)", "e": 906, "s": 413, "text": null }, { "code": null, "e": 914, "s": 906, "text": "Output:" }, { "code": null, "e": 937, "s": 914, "text": "Original list of tuple" }, { "code": null, "e": 1029, "s": 937, "text": "[(1, 2, 3, 4, 5), (β€˜sravan’, β€˜bobby’, β€˜ojaswi’, β€˜rohith’, β€˜Gnanesh’), (96, 89, 78, 90, 78)]" }, { "code": null, "e": 1034, "s": 1029, "text": "List" }, { "code": null, "e": 1052, "s": 1034, "text": "[1, β€˜sravan’, 96]" }, { "code": null, "e": 1069, "s": 1052, "text": "[2, β€˜bobby’, 89]" }, { "code": null, "e": 1087, "s": 1069, "text": "[3, β€˜ojaswi’, 78]" }, { "code": null, "e": 1105, "s": 1087, "text": "[4, β€˜rohith’, 90]" }, { "code": null, "e": 1124, "s": 1105, "text": "[5, β€˜Gnanesh’, 78]" }, { "code": null, "e": 1193, "s": 1124, "text": "Example 2: Python code to convert a list of tuples to multiple lists" }, { "code": null, "e": 1201, "s": 1193, "text": "Python3" }, { "code": "# list of tuple for student# data with both integer and stringsa = [(1, 2,3,4,5), (\"sravan\",\"bobby\",\"ojaswi\",\"rohith\",\"Gnanesh\"), (96,89,78,90,78), (\"kakumanu\",\"kakumanu\",\"hyd\",\"hyd\",\"hyd\")] # convert list of tuple to multiple listsdata = map(list, zip(*a)) # display for i in data: print(i)", "e": 1509, "s": 1201, "text": null }, { "code": null, "e": 1517, "s": 1509, "text": "Output:" }, { "code": null, "e": 1652, "s": 1517, "text": "[1, 'sravan', 96, 'kakumanu']\n[2, 'bobby', 89, 'kakumanu']\n[3, 'ojaswi', 78, 'hyd']\n[4, 'rohith', 90, 'hyd']\n[5, 'Gnanesh', 78, 'hyd']" }, { "code": null, "e": 1659, "s": 1652, "text": "Picked" }, { "code": null, "e": 1681, "s": 1659, "text": "Python List-of-Tuples" }, { "code": null, "e": 1693, "s": 1681, "text": "python-list" }, { "code": null, "e": 1700, "s": 1693, "text": "Python" }, { "code": null, "e": 1716, "s": 1700, "text": "Python Programs" }, { "code": null, "e": 1728, "s": 1716, "text": "python-list" }, { "code": null, "e": 1826, "s": 1728, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1858, "s": 1826, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1885, "s": 1858, "text": "Python Classes and Objects" }, { "code": null, "e": 1906, "s": 1885, "text": "Python OOPs Concepts" }, { "code": null, "e": 1929, "s": 1906, "text": "Introduction To PYTHON" }, { "code": null, "e": 1960, "s": 1929, "text": "Python | os.path.join() method" }, { "code": null, "e": 1982, "s": 1960, "text": "Defaultdict in Python" }, { "code": null, "e": 2021, "s": 1982, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2059, "s": 2021, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2108, "s": 2059, "text": "Python | Convert string dictionary to dictionary" } ]
HTML | accesskey Attribute
10 Aug, 2021 The accesskey attribute in HTML is the keyboard shortcuts to activate/focus specific elements. The access key attribute is browser dependent. It may vary from browser to browser.Supported Tags: It supports all HTML elements. Syntax: <element accessKey = "single_character"> Shortcut to use access key: The table describes the shortcut to use access key. Note: In HTML4.1, the accesskey attributes can be used with only few elements which include <a>, <area>, <button>, <input>, <label>, <legend>, and <textarea>. In HTML5, the accesskey attribute can be used with any element. The behavior of the browser differs when dealing with more than one element having the same accesskey: Google Chrome and Safari: The last element with the accesskey will be activated Opera: The first element with the accesskey will be activated Internet Explorer and Mozilla Firefox: The next element with the accesskey will be activated Example: html <!DOCTYPE html><html> <head> <title> accesskey attribute </title> </head> <body style = "text-align:center"> <h1>GeeksforGeeks</h1> <h2>HTML accesskey attribute</h2> <!-- The accesskey attribute used here --> <a href="https://ide.geeksforgeeks.org/tryit.php" accesskey = "g">GeeksforGeeks </a> </body></html> Output: Before using the access key: After using the access key: Supported Browsers: The browser supported by accesskey attribute are listed below: Google Chrome Internet Explorer Firefox Opera Safari ManasChhabra2 HTML-Attributes Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n10 Aug, 2021" }, { "code": null, "e": 279, "s": 53, "text": "The accesskey attribute in HTML is the keyboard shortcuts to activate/focus specific elements. The access key attribute is browser dependent. It may vary from browser to browser.Supported Tags: It supports all HTML elements. " }, { "code": null, "e": 289, "s": 279, "text": "Syntax: " }, { "code": null, "e": 330, "s": 289, "text": "<element accessKey = \"single_character\">" }, { "code": null, "e": 412, "s": 330, "text": "Shortcut to use access key: The table describes the shortcut to use access key. " }, { "code": null, "e": 420, "s": 412, "text": "Note: " }, { "code": null, "e": 573, "s": 420, "text": "In HTML4.1, the accesskey attributes can be used with only few elements which include <a>, <area>, <button>, <input>, <label>, <legend>, and <textarea>." }, { "code": null, "e": 637, "s": 573, "text": "In HTML5, the accesskey attribute can be used with any element." }, { "code": null, "e": 742, "s": 639, "text": "The behavior of the browser differs when dealing with more than one element having the same accesskey:" }, { "code": null, "e": 824, "s": 744, "text": "Google Chrome and Safari: The last element with the accesskey will be activated" }, { "code": null, "e": 886, "s": 824, "text": "Opera: The first element with the accesskey will be activated" }, { "code": null, "e": 979, "s": 886, "text": "Internet Explorer and Mozilla Firefox: The next element with the accesskey will be activated" }, { "code": null, "e": 990, "s": 979, "text": "Example: " }, { "code": null, "e": 995, "s": 990, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> accesskey attribute </title> </head> <body style = \"text-align:center\"> <h1>GeeksforGeeks</h1> <h2>HTML accesskey attribute</h2> <!-- The accesskey attribute used here --> <a href=\"https://ide.geeksforgeeks.org/tryit.php\" accesskey = \"g\">GeeksforGeeks </a> </body></html> ", "e": 1429, "s": 995, "text": null }, { "code": null, "e": 1468, "s": 1429, "text": "Output: Before using the access key: " }, { "code": null, "e": 1498, "s": 1468, "text": "After using the access key: " }, { "code": null, "e": 1583, "s": 1498, "text": "Supported Browsers: The browser supported by accesskey attribute are listed below: " }, { "code": null, "e": 1597, "s": 1583, "text": "Google Chrome" }, { "code": null, "e": 1615, "s": 1597, "text": "Internet Explorer" }, { "code": null, "e": 1623, "s": 1615, "text": "Firefox" }, { "code": null, "e": 1629, "s": 1623, "text": "Opera" }, { "code": null, "e": 1636, "s": 1629, "text": "Safari" }, { "code": null, "e": 1652, "s": 1638, "text": "ManasChhabra2" }, { "code": null, "e": 1668, "s": 1652, "text": "HTML-Attributes" }, { "code": null, "e": 1675, "s": 1668, "text": "Picked" }, { "code": null, "e": 1680, "s": 1675, "text": "HTML" }, { "code": null, "e": 1697, "s": 1680, "text": "Web Technologies" }, { "code": null, "e": 1702, "s": 1697, "text": "HTML" }, { "code": null, "e": 1800, "s": 1702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1848, "s": 1800, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1910, "s": 1848, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1960, "s": 1910, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1984, "s": 1960, "text": "REST API (Introduction)" }, { "code": null, "e": 2037, "s": 1984, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2070, "s": 2037, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2132, "s": 2070, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2193, "s": 2132, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2243, "s": 2193, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Random Forest Approach for Classification in R Programming
08 Jul, 2020 Random forest approach is supervised nonlinear classification and regression algorithm. Classification is a process of classifying a group of datasets in categories or classes. As random forest approach can use classification or regression techniques depending upon the user and target or categories needed. A random forest is a collection of decision trees that specifies the categories with much higher probability. Random forest approach is used over decision trees approach as decision trees lack accuracy and decision trees also show low accuracy during the testing phase due to the process called over-fitting. In R programming, randomForest() function of randomForest package is used to create and analyze the random forest. In this article, let’s discuss the random forest, learn the syntax and implementation of a random forest approach for classification in R programming, and further graph will be plotted for inference. Random forest is a machine learning algorithm that uses a collection of decision trees providing more flexibility, accuracy, and ease of access in the output. This algorithm dominates over decision trees algorithm as decision trees provide poor accuracy as compared to the random forest algorithm. In simple words, the random forest approach increases the performance of decision trees. It is one of the best algorithm as it can use both classification and regression techniques. Being a supervised learning algorithm, random forest uses the bagging method in decision trees and as a result, increases the accuracy of the learning model. Random forest searches for the best feature from a random subset of features providing more randomness to the model and results in a better and accurate model. Let us learn about the random forest approach with an example. Suppose a man named Bob wants to buy a T-shirt from a store. The salesman asks him first about his favourite colour. This constitutes a decision tree based on colour feature. Further, the salesman asks more about the T-shirt like size, type of fabric, type of collar and many more. More criteria of selecting a T-shirt will make more decision trees in machine learning. Together all the decision trees will constitute to random forest approach of selecting a T-shirt based on many features that Bob would like to buy from the store. Classification is a supervised learning approach in which data is classified on the basis of the features provided. As in the above example, data is being classified in different parameters using random forest. It helps in creating more and meaningful observations or classifications. In simple words, classification is a way of categorizing the structured or unstructured data into some categories or classes. There are 8 major classification algorithms: Logistic Regression Naive Bayes K-Nearest Neighbours Decision Trees Random Forest Artificial Neural Networks Support Vector Machine Stochastic Gradient Descent Some real world classification examples are a mail can be specified either spam or non-spam, wastes can be specified as paper waste, plastic waste, organic waste or electronic waste, a disease can be determined on many symptoms, sentiment analysis, determining gender using facial expressions, etc. Syntax:randomForest(formula, data) Parameters:formula: represents formula describing the model to be fitteddata: represents data frame containing the variables in the model Example:In this example, let’s use supervised learning on iris dataset to classify the species of iris plant based on the parameters passed in the function.Step 1: Installing the required library # Install the required# Package for functioninstall.packages("randomForest") Step 2: Loading the required library # Load the librarylibrary(randomForest) Step 3: Using iris dataset in randomForest() function # Create random forest# For classificationiris.rf <- randomForest(Species ~ ., data = iris, importance = TRUE, proximity = TRUE) Step 4: Print the classification model built in above step # Print classification modelprint(iris.rf) Output: Call: randomForest(formula = Species ~ ., data = iris, importance = TRUE, proximity = TRUE) Type of random forest: classification Number of trees: 500 No. of variables tried at each split: 2 OOB estimate of error rate: 5.33% Confusion matrix: setosa versicolor virginica class.error setosa 50 0 0 0.00 versicolor 0 47 3 0.06 virginica 0 5 45 0.10 Step 5: Plotting the graph between error and number of trees # Output to be present# As PNG file png(file = "randomForestClassification.png") # Plot the error vs # The number of trees graphplot(iris.rf) # Saving the filedev.off() Output:Explanation:After executing the above code, the output is produced that shows the number of decision trees developed using the classification model for random forest algorithms, i.e. 500 decision trees. The confusion matrix is also known as the error matrix that shows the visualization of the performance of the classification model. Picked R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Printing Output of an R Program Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column?
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2020" }, { "code": null, "e": 960, "s": 28, "text": "Random forest approach is supervised nonlinear classification and regression algorithm. Classification is a process of classifying a group of datasets in categories or classes. As random forest approach can use classification or regression techniques depending upon the user and target or categories needed. A random forest is a collection of decision trees that specifies the categories with much higher probability. Random forest approach is used over decision trees approach as decision trees lack accuracy and decision trees also show low accuracy during the testing phase due to the process called over-fitting. In R programming, randomForest() function of randomForest package is used to create and analyze the random forest. In this article, let’s discuss the random forest, learn the syntax and implementation of a random forest approach for classification in R programming, and further graph will be plotted for inference." }, { "code": null, "e": 1598, "s": 960, "text": "Random forest is a machine learning algorithm that uses a collection of decision trees providing more flexibility, accuracy, and ease of access in the output. This algorithm dominates over decision trees algorithm as decision trees provide poor accuracy as compared to the random forest algorithm. In simple words, the random forest approach increases the performance of decision trees. It is one of the best algorithm as it can use both classification and regression techniques. Being a supervised learning algorithm, random forest uses the bagging method in decision trees and as a result, increases the accuracy of the learning model." }, { "code": null, "e": 2354, "s": 1598, "text": "Random forest searches for the best feature from a random subset of features providing more randomness to the model and results in a better and accurate model. Let us learn about the random forest approach with an example. Suppose a man named Bob wants to buy a T-shirt from a store. The salesman asks him first about his favourite colour. This constitutes a decision tree based on colour feature. Further, the salesman asks more about the T-shirt like size, type of fabric, type of collar and many more. More criteria of selecting a T-shirt will make more decision trees in machine learning. Together all the decision trees will constitute to random forest approach of selecting a T-shirt based on many features that Bob would like to buy from the store." }, { "code": null, "e": 2810, "s": 2354, "text": "Classification is a supervised learning approach in which data is classified on the basis of the features provided. As in the above example, data is being classified in different parameters using random forest. It helps in creating more and meaningful observations or classifications. In simple words, classification is a way of categorizing the structured or unstructured data into some categories or classes. There are 8 major classification algorithms:" }, { "code": null, "e": 2830, "s": 2810, "text": "Logistic Regression" }, { "code": null, "e": 2842, "s": 2830, "text": "Naive Bayes" }, { "code": null, "e": 2863, "s": 2842, "text": "K-Nearest Neighbours" }, { "code": null, "e": 2878, "s": 2863, "text": "Decision Trees" }, { "code": null, "e": 2892, "s": 2878, "text": "Random Forest" }, { "code": null, "e": 2919, "s": 2892, "text": "Artificial Neural Networks" }, { "code": null, "e": 2942, "s": 2919, "text": "Support Vector Machine" }, { "code": null, "e": 2970, "s": 2942, "text": "Stochastic Gradient Descent" }, { "code": null, "e": 3269, "s": 2970, "text": "Some real world classification examples are a mail can be specified either spam or non-spam, wastes can be specified as paper waste, plastic waste, organic waste or electronic waste, a disease can be determined on many symptoms, sentiment analysis, determining gender using facial expressions, etc." }, { "code": null, "e": 3304, "s": 3269, "text": "Syntax:randomForest(formula, data)" }, { "code": null, "e": 3442, "s": 3304, "text": "Parameters:formula: represents formula describing the model to be fitteddata: represents data frame containing the variables in the model" }, { "code": null, "e": 3638, "s": 3442, "text": "Example:In this example, let’s use supervised learning on iris dataset to classify the species of iris plant based on the parameters passed in the function.Step 1: Installing the required library" }, { "code": "# Install the required# Package for functioninstall.packages(\"randomForest\")", "e": 3715, "s": 3638, "text": null }, { "code": null, "e": 3752, "s": 3715, "text": "Step 2: Loading the required library" }, { "code": "# Load the librarylibrary(randomForest)", "e": 3792, "s": 3752, "text": null }, { "code": null, "e": 3846, "s": 3792, "text": "Step 3: Using iris dataset in randomForest() function" }, { "code": "# Create random forest# For classificationiris.rf <- randomForest(Species ~ ., data = iris, importance = TRUE, proximity = TRUE)", "e": 4046, "s": 3846, "text": null }, { "code": null, "e": 4105, "s": 4046, "text": "Step 4: Print the classification model built in above step" }, { "code": "# Print classification modelprint(iris.rf)", "e": 4148, "s": 4105, "text": null }, { "code": null, "e": 4156, "s": 4148, "text": "Output:" }, { "code": null, "e": 4657, "s": 4156, "text": "Call:\n randomForest(formula = Species ~ ., data = iris, importance = TRUE, proximity = TRUE) \n Type of random forest: classification\n Number of trees: 500\nNo. of variables tried at each split: 2\n\n OOB estimate of error rate: 5.33%\nConfusion matrix:\n setosa versicolor virginica class.error\nsetosa 50 0 0 0.00\nversicolor 0 47 3 0.06\nvirginica 0 5 45 0.10\n" }, { "code": null, "e": 4718, "s": 4657, "text": "Step 5: Plotting the graph between error and number of trees" }, { "code": "# Output to be present# As PNG file png(file = \"randomForestClassification.png\") # Plot the error vs # The number of trees graphplot(iris.rf) # Saving the filedev.off()", "e": 4891, "s": 4718, "text": null }, { "code": null, "e": 5233, "s": 4891, "text": "Output:Explanation:After executing the above code, the output is produced that shows the number of decision trees developed using the classification model for random forest algorithms, i.e. 500 decision trees. The confusion matrix is also known as the error matrix that shows the visualization of the performance of the classification model." }, { "code": null, "e": 5240, "s": 5233, "text": "Picked" }, { "code": null, "e": 5259, "s": 5240, "text": "R Machine-Learning" }, { "code": null, "e": 5270, "s": 5259, "text": "R Language" }, { "code": null, "e": 5368, "s": 5270, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5420, "s": 5368, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 5478, "s": 5420, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 5530, "s": 5478, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 5588, "s": 5530, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5620, "s": 5588, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 5652, "s": 5620, "text": "Printing Output of an R Program" }, { "code": null, "e": 5687, "s": 5652, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 5731, "s": 5687, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 5769, "s": 5731, "text": "How to Change Axis Scales in R Plots?" } ]
Psutil module in Python
21 Sep, 2021 Psutil is a Python cross-platform library used to access system details and process utilities. It is used to keep track of various resources utilization in the system. Usage of resources like CPU, memory, disks, network, sensors can be monitored. Hence, this library is used for system monitoring, profiling, limiting process resources, and the management of running processes. It is supported in Python versions 2.6, 2.7, and 3.4+. sudo pip install psutil 1) psutil.cpu_times() – This function gives system CPU times as a named tuple. Parameters: user – time spent by normal processes executing in user mode system – time spent by processes executing in kernel mode idle – time when system was idle nice – time spent by priority processes executing in user mode iowait – time spent waiting for I/O to complete. This is not accounted in idle time counter. irq – time spent for servicing hardware interrupts softirq – time spent for servicing software interrupts steal – time spent by other operating systems running in a virtualized environment guest – time spent running a virtual CPU for guest operating systems under the control of the Linux kernel Example : Python import psutil print(psutil.cpu_times()) Output scputimes(user=5461.14, nice=2.44, system=1326.65, idle=45502.33, iowait=506.24, irq=0.0, softirq=5.46, steal=0.0, guest=0.0, guest_nice=0.0) 2) psutil.cpu_percent(interval) – This function calculates the current system-wide CPU utilization as a percentage.It is recommended to provide time interval (seconds) as parameter to the function over which the average CPU usage will be calculated, ignoring the interval parameter could result in high variation in usage values. Example : Python import psutil print(psutil.cpu_percent(1)) Output 5.0 3) psutil.cpu_count(logical=True) – This function shows a number of logical CPUs in the system. The logical core is calculated as the number of physical cores multiplied by the number of threads that can run on each core. In the absence of logical core, it only counts a number of physical cores. Example : Python import psutil print("Number of cores in system", psutil.cpu_count())print("\nNumber of physical cores in system",) Output: Number of cores in system 4 Number of physical cores in system 2 4) psutil.cpu_stats() – This function gives CPU statistics as a named tuple. The statistics includes : ctx_switches – number of context switches since boot. interrupts – number of interrupts since boot. soft_interrupts – number of software interrupts since boot. syscalls – number of system calls since boot. Always set to 0 in Ubuntu. Example : Python import psutil print("CPU Statistics", psutil.cpu_stats()) scpustats(ctx_switches=37382771, interrupts=13744347, soft_interrupts=6769413, syscalls=0) 5) psutil.cpu_freq() – This function gives CPU frequency as a tuple that includes current, min and max frequencies expressed in Mhz. On Ubuntu current frequency reports the real-time value. Whereas on all other platforms it represents the nominal β€œfixed” value. Example : Python import psutil print(psutil.cpu_freq()) Output: scpufreq(current=931.42925, min=400.0, max=2000.0) 6) psutil.getloadavg() – This function gives the average system load in last 1, 5, and 15 minutes as a tuple. The load represents the processes which are in a runnable state, either using the CPU or waiting to use the CPU (e.g. waiting for disk I/O). Example : Python import psutil print(psutil.getloadavg()) Output: (0.22, 0.33, 0.35) 1) psutil.virtual_memory() – This function gives system memory usage in bytes. The sum of used and available may or may not be equal to total. In order to get details of free physical memory this function is used. Parameters: total – total physical memory excluding swap. available – the memory that can be given instantly to processes without the system going into swap. used – memory used. free – memory not used at and is readily available active – memory currently in use or very recently used. inactive – memory that is marked as not used. buffers – cache data like file system metadata. cached – cached data shared – memory that may be accessed by multiple processes. Example : Python import psutil print(psutil.virtual_memory()) Output: svmem(total=4028772352, available=1061466112, percent=73.7, used=2401546240, free=412352512, active=2176798720, inactive=1196470272, buffers=70774784, cached=1144098816, shared=313872384, slab=125116416) 2) psutil.swap_memory() – This function provides details of swap memory statistics as a tuple. Parameters: total – total swap memory in bytes used – used swap memory in bytes free – free swap memory in bytes percent – the percentage usage that is calculated as (total – available) / total * 100 sin – the number of bytes the system has swapped in from disk sout – the number of bytes the system has swapped out from disk Example : Python import psutil print(psutil.swap_memory()) Output: sswap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768) 1) psutil.disk_partitions() – This function provides the details of all mounted disk partitions as a list of tuples including device, mount point and filesystem type. Example : Python import psutil print(psutil.disk_partitions()) Output: [sdiskpart(device=’/dev/sda1β€², mountpoint=’/’, fstype=’ext4β€², opts=’rw, relatime, errors=remount-ro, data=ordered’)] 2) psutil.disk_usage(path)- This function gives disk usage statistics as a tuple for a given path. Total, used and free space are expressed in bytes, along with the percentage usage. Example : Python import psutil print(psutil.disk_usage('/')) Output: sdiskusage(total=787310764032, used=26450710528, free=720843354112, percent=3.5) 1) psutil.net_io_counters()- This function gives the details of network Input output statistics as a tuple. Parameters: bytes_sent – number of bytes sent bytes_recv – number of bytes received packets_sent – number of packets sent packets_recv – number of packets received errin – total number of errors while receiving errout – total number of errors while sending dropin – total number of incoming packets which were dropped dropout – total number of outgoing packets which were dropped Example : Python import psutil print(psutil.net_io_counters()) Output: snetio(bytes_sent=14508483, bytes_recv=62749361, packets_sent=84311, packets_recv=94888, errin=0, errout=0, dropin=0, dropout=0) 2) psutil.net_connections() – This function gives the list of socket connections of a system as a named tuples. Parameters: fd – the socket file descriptor. family – the socket family, either AF_INET, AF_INET6 or AF_UNIX. type – the socket type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET. laddr – the local address as a (ip, port) named tuple raddr – the remote address as a (ip, port) named tuple status – represents the status of a TCP connection. pid – the PID of the process which opened the socket, if retrievable, else None. Example : Python import psutil print(psutil.net_connections()) Output: [sconn(fd=118, family=2, type=1, laddr=addr(ip=’192.168.12.184β€², port=59666), raddr=addr(ip=’172.217.166.42β€², port=443), status=’ESTABLISHED’, pid=2428), sconn(fd=-1, family=2, type=2, laddr=addr(ip=’0.0.0.0β€², port=631), raddr=(), status=’NONE’, pid=None), sconn(fd=-1, family=2, type=1, laddr=addr(ip=’127.0.0.1β€², port=3306), raddr=(), status=’LISTEN’, pid=None), sconn(fd=145, family=2, type=1, laddr=addr(ip=’192.168.12.184β€², port=56568), raddr=addr(ip=’172.217.166.35β€², port=443), status=’ESTABLISHED’, pid=2428), sconn(fd=-1, family=2, type=2, laddr=addr(ip=’0.0.0.0β€², port=52253), raddr=(), status=’NONE’, pid=None)] 3) psutil.net_if_addrs() – This function is used to get the addresses of each network interface card installed on the system. It is a dictionary whose keys are the Network Interface Card names and value is a list of named tuples for each address assigned to it. Each tuple includes: family – the socket family, either AF_INET or AF_INET6 address – the primary NIC address netmask – the netmask address broadcast – the broadcast address. ptp – β€œpoint to point” it is the destination address on a point to point interface. Example : Python import psutil print(psutil.net_if_addrs()) Output: {β€˜wlo1β€²: [snicaddr(family=2, address=’192.168.12.184β€², netmask=’255.255.255.0β€², broadcast=’192.168.12.255β€², ptp=None), snicaddr(family=10, address=’fe80::664f:767c:91f0:71c0%wlo1β€², netmask=’ffff:ffff:ffff:ffff::’, broadcast=None, ptp=None), snicaddr(family=17, address=’3c:f8:62:32:b7:70β€², netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)], β€˜lo’: [snicaddr(family=2, address=’127.0.0.1β€², netmask=’255.0.0.0β€², broadcast=None, ptp=None), snicaddr(family=10, address=’::1β€², netmask=’ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff’, broadcast=None, ptp=None), snicaddr(family=17, address=’00:00:00:00:00:00β€², netmask=None, broadcast=None, ptp=None)], β€˜docker0β€²: [snicaddr(family=2, address=’172.17.0.1β€², netmask=’255.255.0.0β€², broadcast=’172.17.255.255β€², ptp=None), snicaddr(family=17, address=’02:42:ef:4c:3b:d9β€², netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)], β€˜eno1β€²: [snicaddr(family=17, address=’3c:52:82:09:8e:c2β€², netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)]} 1) psutil.sensors_temperatures()- This function returns hardware temperatures of the system in celsius. Each entry is a named tuple representing a certain hardware temperature sensor. Example : Python import psutil print(psutil.sensors_temperatures()) Output: {β€˜acpitz’: [shwtemp(label=”, current=27.8, high=119.0, critical=119.0), shwtemp(label=”, current=29.8, high=119.0, critical=119.0), shwtemp(label=”, current=10.0, high=None, critical=None)], β€˜coretemp’: [shwtemp(label=’Physical id 0β€², current=42.0, high=100.0, critical=100.0), shwtemp(label=’Core 0β€², current=41.0, high=100.0, critical=100.0), shwtemp(label=’Core 1β€², current=41.0, high=100.0, critical=100.0), shwtemp(label=’Physical id 0β€², current=42.0, high=100.0, critical=100.0), shwtemp(label=’Core 0β€², current=41.0, high=100.0, critical=100.0), shwtemp(label=’Core 1β€², current=41.0, high=100.0, critical=100.0)]} 2) psutil.sensors_fans() – This function gives the details of hardware fans speed expressed in RPM (rounds per minute). If sensors are not supported by the OS an empty dict is returned. Example : Python import psutil print(psutil.sensors_fans()) Output: {'asus': [sfan(label='cpu_fan', current=3000)]} 3) psutil.sensors_battery() – This function gives battery status information as a named tuple. Parameters: percent – battery power left as a percentage. secsleft – an approximate time in seconds before battery is completely discharged. power_plugged – True if the AC power cable is connected, False if it is not connected. Example : Python import psutil print(psutil.sensors_battery()) Output: sbattery(percent=98.98572501878287, secsleft=22913, power_plugged=False) 1) psutil.boot_time() – This function returns the system boot time which is expressed in seconds since the epoch. Example : Python import psutil, datetime print(psutil.boot_time()) Output: 1582860765.0 2) psutil.users() – This function gives the list of users who are connected on the system as a named tuples. Parameters: user – It is the system name of the user. terminal – the tty of the user. host – the host name of the user. started – the creation time as a floating point number expressed in seconds since the epoch. pid – the PID of the login process. Example : Python import psutil print(psutil.users()) Output: [suser(name=’admin1β€², terminal=’tty7β€², host=’localhost’, started=1582860800.0, pid=1747)] shikharraizaday d42dhpakvdal13px45kdvrdzg619cup8jrm16xvu python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Sep, 2021" }, { "code": null, "e": 462, "s": 28, "text": "Psutil is a Python cross-platform library used to access system details and process utilities. It is used to keep track of various resources utilization in the system. Usage of resources like CPU, memory, disks, network, sensors can be monitored. Hence, this library is used for system monitoring, profiling, limiting process resources, and the management of running processes. It is supported in Python versions 2.6, 2.7, and 3.4+. " }, { "code": null, "e": 486, "s": 462, "text": "sudo pip install psutil" }, { "code": null, "e": 565, "s": 486, "text": "1) psutil.cpu_times() – This function gives system CPU times as a named tuple." }, { "code": null, "e": 579, "s": 565, "text": "Parameters: " }, { "code": null, "e": 640, "s": 579, "text": "user – time spent by normal processes executing in user mode" }, { "code": null, "e": 698, "s": 640, "text": "system – time spent by processes executing in kernel mode" }, { "code": null, "e": 731, "s": 698, "text": "idle – time when system was idle" }, { "code": null, "e": 794, "s": 731, "text": "nice – time spent by priority processes executing in user mode" }, { "code": null, "e": 887, "s": 794, "text": "iowait – time spent waiting for I/O to complete. This is not accounted in idle time counter." }, { "code": null, "e": 938, "s": 887, "text": "irq – time spent for servicing hardware interrupts" }, { "code": null, "e": 993, "s": 938, "text": "softirq – time spent for servicing software interrupts" }, { "code": null, "e": 1076, "s": 993, "text": "steal – time spent by other operating systems running in a virtualized environment" }, { "code": null, "e": 1183, "s": 1076, "text": "guest – time spent running a virtual CPU for guest operating systems under the control of the Linux kernel" }, { "code": null, "e": 1194, "s": 1183, "text": "Example : " }, { "code": null, "e": 1201, "s": 1194, "text": "Python" }, { "code": "import psutil print(psutil.cpu_times())", "e": 1242, "s": 1201, "text": null }, { "code": null, "e": 1249, "s": 1242, "text": "Output" }, { "code": null, "e": 1393, "s": 1249, "text": "scputimes(user=5461.14, nice=2.44, system=1326.65, idle=45502.33, iowait=506.24, irq=0.0, softirq=5.46, steal=0.0, guest=0.0, guest_nice=0.0) " }, { "code": null, "e": 1723, "s": 1393, "text": "2) psutil.cpu_percent(interval) – This function calculates the current system-wide CPU utilization as a percentage.It is recommended to provide time interval (seconds) as parameter to the function over which the average CPU usage will be calculated, ignoring the interval parameter could result in high variation in usage values." }, { "code": null, "e": 1735, "s": 1723, "text": "Example : " }, { "code": null, "e": 1742, "s": 1735, "text": "Python" }, { "code": "import psutil print(psutil.cpu_percent(1))", "e": 1785, "s": 1742, "text": null }, { "code": null, "e": 1793, "s": 1785, "text": "Output " }, { "code": null, "e": 1797, "s": 1793, "text": "5.0" }, { "code": null, "e": 2094, "s": 1797, "text": "3) psutil.cpu_count(logical=True) – This function shows a number of logical CPUs in the system. The logical core is calculated as the number of physical cores multiplied by the number of threads that can run on each core. In the absence of logical core, it only counts a number of physical cores." }, { "code": null, "e": 2106, "s": 2094, "text": "Example : " }, { "code": null, "e": 2113, "s": 2106, "text": "Python" }, { "code": "import psutil print(\"Number of cores in system\", psutil.cpu_count())print(\"\\nNumber of physical cores in system\",)", "e": 2229, "s": 2113, "text": null }, { "code": null, "e": 2238, "s": 2229, "text": "Output: " }, { "code": null, "e": 2303, "s": 2238, "text": "Number of cores in system 4\nNumber of physical cores in system 2" }, { "code": null, "e": 2407, "s": 2303, "text": "4) psutil.cpu_stats() – This function gives CPU statistics as a named tuple. The statistics includes : " }, { "code": null, "e": 2461, "s": 2407, "text": "ctx_switches – number of context switches since boot." }, { "code": null, "e": 2507, "s": 2461, "text": "interrupts – number of interrupts since boot." }, { "code": null, "e": 2567, "s": 2507, "text": "soft_interrupts – number of software interrupts since boot." }, { "code": null, "e": 2640, "s": 2567, "text": "syscalls – number of system calls since boot. Always set to 0 in Ubuntu." }, { "code": null, "e": 2651, "s": 2640, "text": "Example : " }, { "code": null, "e": 2658, "s": 2651, "text": "Python" }, { "code": "import psutil print(\"CPU Statistics\", psutil.cpu_stats())", "e": 2717, "s": 2658, "text": null }, { "code": null, "e": 2810, "s": 2717, "text": "scpustats(ctx_switches=37382771, interrupts=13744347, soft_interrupts=6769413, syscalls=0) " }, { "code": null, "e": 3073, "s": 2810, "text": "5) psutil.cpu_freq() – This function gives CPU frequency as a tuple that includes current, min and max frequencies expressed in Mhz. On Ubuntu current frequency reports the real-time value. Whereas on all other platforms it represents the nominal β€œfixed” value. " }, { "code": null, "e": 3084, "s": 3073, "text": "Example : " }, { "code": null, "e": 3091, "s": 3084, "text": "Python" }, { "code": "import psutil print(psutil.cpu_freq())", "e": 3131, "s": 3091, "text": null }, { "code": null, "e": 3139, "s": 3131, "text": "Output:" }, { "code": null, "e": 3192, "s": 3139, "text": "scpufreq(current=931.42925, min=400.0, max=2000.0) " }, { "code": null, "e": 3444, "s": 3192, "text": "6) psutil.getloadavg() – This function gives the average system load in last 1, 5, and 15 minutes as a tuple. The load represents the processes which are in a runnable state, either using the CPU or waiting to use the CPU (e.g. waiting for disk I/O). " }, { "code": null, "e": 3456, "s": 3444, "text": "Example : " }, { "code": null, "e": 3463, "s": 3456, "text": "Python" }, { "code": "import psutil print(psutil.getloadavg())", "e": 3505, "s": 3463, "text": null }, { "code": null, "e": 3514, "s": 3505, "text": "Output: " }, { "code": null, "e": 3533, "s": 3514, "text": "(0.22, 0.33, 0.35)" }, { "code": null, "e": 3747, "s": 3533, "text": "1) psutil.virtual_memory() – This function gives system memory usage in bytes. The sum of used and available may or may not be equal to total. In order to get details of free physical memory this function is used." }, { "code": null, "e": 3760, "s": 3747, "text": "Parameters: " }, { "code": null, "e": 3806, "s": 3760, "text": "total – total physical memory excluding swap." }, { "code": null, "e": 3906, "s": 3806, "text": "available – the memory that can be given instantly to processes without the system going into swap." }, { "code": null, "e": 3926, "s": 3906, "text": "used – memory used." }, { "code": null, "e": 3977, "s": 3926, "text": "free – memory not used at and is readily available" }, { "code": null, "e": 4033, "s": 3977, "text": "active – memory currently in use or very recently used." }, { "code": null, "e": 4079, "s": 4033, "text": "inactive – memory that is marked as not used." }, { "code": null, "e": 4127, "s": 4079, "text": "buffers – cache data like file system metadata." }, { "code": null, "e": 4148, "s": 4127, "text": "cached – cached data" }, { "code": null, "e": 4208, "s": 4148, "text": "shared – memory that may be accessed by multiple processes." }, { "code": null, "e": 4219, "s": 4208, "text": "Example : " }, { "code": null, "e": 4226, "s": 4219, "text": "Python" }, { "code": "import psutil print(psutil.virtual_memory())", "e": 4272, "s": 4226, "text": null }, { "code": null, "e": 4280, "s": 4272, "text": "Output:" }, { "code": null, "e": 4486, "s": 4280, "text": "svmem(total=4028772352, available=1061466112, percent=73.7, used=2401546240, free=412352512, active=2176798720, inactive=1196470272, buffers=70774784, cached=1144098816, shared=313872384, slab=125116416) " }, { "code": null, "e": 4581, "s": 4486, "text": "2) psutil.swap_memory() – This function provides details of swap memory statistics as a tuple." }, { "code": null, "e": 4595, "s": 4581, "text": "Parameters: " }, { "code": null, "e": 4630, "s": 4595, "text": "total – total swap memory in bytes" }, { "code": null, "e": 4663, "s": 4630, "text": "used – used swap memory in bytes" }, { "code": null, "e": 4696, "s": 4663, "text": "free – free swap memory in bytes" }, { "code": null, "e": 4783, "s": 4696, "text": "percent – the percentage usage that is calculated as (total – available) / total * 100" }, { "code": null, "e": 4845, "s": 4783, "text": "sin – the number of bytes the system has swapped in from disk" }, { "code": null, "e": 4909, "s": 4845, "text": "sout – the number of bytes the system has swapped out from disk" }, { "code": null, "e": 4921, "s": 4909, "text": "Example : " }, { "code": null, "e": 4928, "s": 4921, "text": "Python" }, { "code": "import psutil print(psutil.swap_memory())", "e": 4971, "s": 4928, "text": null }, { "code": null, "e": 4979, "s": 4971, "text": "Output:" }, { "code": null, "e": 5088, "s": 4979, "text": "sswap(total=2097147904L, used=886620160L, free=1210527744L, percent=42.3, sin=1050411008, sout=1906720768) " }, { "code": null, "e": 5255, "s": 5088, "text": "1) psutil.disk_partitions() – This function provides the details of all mounted disk partitions as a list of tuples including device, mount point and filesystem type." }, { "code": null, "e": 5267, "s": 5255, "text": "Example : " }, { "code": null, "e": 5274, "s": 5267, "text": "Python" }, { "code": "import psutil print(psutil.disk_partitions())", "e": 5321, "s": 5274, "text": null }, { "code": null, "e": 5329, "s": 5321, "text": "Output:" }, { "code": null, "e": 5448, "s": 5329, "text": "[sdiskpart(device=’/dev/sda1β€², mountpoint=’/’, fstype=’ext4β€², opts=’rw, relatime, errors=remount-ro, data=ordered’)] " }, { "code": null, "e": 5631, "s": 5448, "text": "2) psutil.disk_usage(path)- This function gives disk usage statistics as a tuple for a given path. Total, used and free space are expressed in bytes, along with the percentage usage." }, { "code": null, "e": 5643, "s": 5631, "text": "Example : " }, { "code": null, "e": 5650, "s": 5643, "text": "Python" }, { "code": "import psutil print(psutil.disk_usage('/'))", "e": 5695, "s": 5650, "text": null }, { "code": null, "e": 5703, "s": 5695, "text": "Output:" }, { "code": null, "e": 5785, "s": 5703, "text": "sdiskusage(total=787310764032, used=26450710528, free=720843354112, percent=3.5) " }, { "code": null, "e": 5893, "s": 5785, "text": "1) psutil.net_io_counters()- This function gives the details of network Input output statistics as a tuple." }, { "code": null, "e": 5907, "s": 5893, "text": "Parameters: " }, { "code": null, "e": 5941, "s": 5907, "text": "bytes_sent – number of bytes sent" }, { "code": null, "e": 5979, "s": 5941, "text": "bytes_recv – number of bytes received" }, { "code": null, "e": 6017, "s": 5979, "text": "packets_sent – number of packets sent" }, { "code": null, "e": 6059, "s": 6017, "text": "packets_recv – number of packets received" }, { "code": null, "e": 6106, "s": 6059, "text": "errin – total number of errors while receiving" }, { "code": null, "e": 6152, "s": 6106, "text": "errout – total number of errors while sending" }, { "code": null, "e": 6213, "s": 6152, "text": "dropin – total number of incoming packets which were dropped" }, { "code": null, "e": 6275, "s": 6213, "text": "dropout – total number of outgoing packets which were dropped" }, { "code": null, "e": 6287, "s": 6275, "text": "Example : " }, { "code": null, "e": 6294, "s": 6287, "text": "Python" }, { "code": "import psutil print(psutil.net_io_counters())", "e": 6341, "s": 6294, "text": null }, { "code": null, "e": 6349, "s": 6341, "text": "Output:" }, { "code": null, "e": 6480, "s": 6349, "text": "snetio(bytes_sent=14508483, bytes_recv=62749361, packets_sent=84311, packets_recv=94888, errin=0, errout=0, dropin=0, dropout=0) " }, { "code": null, "e": 6592, "s": 6480, "text": "2) psutil.net_connections() – This function gives the list of socket connections of a system as a named tuples." }, { "code": null, "e": 6606, "s": 6592, "text": "Parameters: " }, { "code": null, "e": 6639, "s": 6606, "text": "fd – the socket file descriptor." }, { "code": null, "e": 6704, "s": 6639, "text": "family – the socket family, either AF_INET, AF_INET6 or AF_UNIX." }, { "code": null, "e": 6778, "s": 6704, "text": "type – the socket type, either SOCK_STREAM, SOCK_DGRAM or SOCK_SEQPACKET." }, { "code": null, "e": 6832, "s": 6778, "text": "laddr – the local address as a (ip, port) named tuple" }, { "code": null, "e": 6887, "s": 6832, "text": "raddr – the remote address as a (ip, port) named tuple" }, { "code": null, "e": 6939, "s": 6887, "text": "status – represents the status of a TCP connection." }, { "code": null, "e": 7020, "s": 6939, "text": "pid – the PID of the process which opened the socket, if retrievable, else None." }, { "code": null, "e": 7032, "s": 7020, "text": "Example : " }, { "code": null, "e": 7039, "s": 7032, "text": "Python" }, { "code": "import psutil print(psutil.net_connections())", "e": 7086, "s": 7039, "text": null }, { "code": null, "e": 7094, "s": 7086, "text": "Output:" }, { "code": null, "e": 7719, "s": 7094, "text": "[sconn(fd=118, family=2, type=1, laddr=addr(ip=’192.168.12.184β€², port=59666), raddr=addr(ip=’172.217.166.42β€², port=443), status=’ESTABLISHED’, pid=2428), sconn(fd=-1, family=2, type=2, laddr=addr(ip=’0.0.0.0β€², port=631), raddr=(), status=’NONE’, pid=None), sconn(fd=-1, family=2, type=1, laddr=addr(ip=’127.0.0.1β€², port=3306), raddr=(), status=’LISTEN’, pid=None), sconn(fd=145, family=2, type=1, laddr=addr(ip=’192.168.12.184β€², port=56568), raddr=addr(ip=’172.217.166.35β€², port=443), status=’ESTABLISHED’, pid=2428), sconn(fd=-1, family=2, type=2, laddr=addr(ip=’0.0.0.0β€², port=52253), raddr=(), status=’NONE’, pid=None)] " }, { "code": null, "e": 8004, "s": 7719, "text": "3) psutil.net_if_addrs() – This function is used to get the addresses of each network interface card installed on the system. It is a dictionary whose keys are the Network Interface Card names and value is a list of named tuples for each address assigned to it. Each tuple includes: " }, { "code": null, "e": 8059, "s": 8004, "text": "family – the socket family, either AF_INET or AF_INET6" }, { "code": null, "e": 8093, "s": 8059, "text": "address – the primary NIC address" }, { "code": null, "e": 8123, "s": 8093, "text": "netmask – the netmask address" }, { "code": null, "e": 8158, "s": 8123, "text": "broadcast – the broadcast address." }, { "code": null, "e": 8242, "s": 8158, "text": "ptp – β€œpoint to point” it is the destination address on a point to point interface." }, { "code": null, "e": 8253, "s": 8242, "text": "Example : " }, { "code": null, "e": 8260, "s": 8253, "text": "Python" }, { "code": "import psutil print(psutil.net_if_addrs())", "e": 8304, "s": 8260, "text": null }, { "code": null, "e": 8312, "s": 8304, "text": "Output:" }, { "code": null, "e": 9295, "s": 8312, "text": "{β€˜wlo1β€²: [snicaddr(family=2, address=’192.168.12.184β€², netmask=’255.255.255.0β€², broadcast=’192.168.12.255β€², ptp=None), snicaddr(family=10, address=’fe80::664f:767c:91f0:71c0%wlo1β€², netmask=’ffff:ffff:ffff:ffff::’, broadcast=None, ptp=None), snicaddr(family=17, address=’3c:f8:62:32:b7:70β€², netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)], β€˜lo’: [snicaddr(family=2, address=’127.0.0.1β€², netmask=’255.0.0.0β€², broadcast=None, ptp=None), snicaddr(family=10, address=’::1β€², netmask=’ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff’, broadcast=None, ptp=None), snicaddr(family=17, address=’00:00:00:00:00:00β€², netmask=None, broadcast=None, ptp=None)], β€˜docker0β€²: [snicaddr(family=2, address=’172.17.0.1β€², netmask=’255.255.0.0β€², broadcast=’172.17.255.255β€², ptp=None), snicaddr(family=17, address=’02:42:ef:4c:3b:d9β€², netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)], β€˜eno1β€²: [snicaddr(family=17, address=’3c:52:82:09:8e:c2β€², netmask=None, broadcast=’ff:ff:ff:ff:ff:ff’, ptp=None)]} " }, { "code": null, "e": 9480, "s": 9295, "text": "1) psutil.sensors_temperatures()- This function returns hardware temperatures of the system in celsius. Each entry is a named tuple representing a certain hardware temperature sensor. " }, { "code": null, "e": 9492, "s": 9480, "text": "Example : " }, { "code": null, "e": 9499, "s": 9492, "text": "Python" }, { "code": "import psutil print(psutil.sensors_temperatures())", "e": 9551, "s": 9499, "text": null }, { "code": null, "e": 9559, "s": 9551, "text": "Output:" }, { "code": null, "e": 10182, "s": 9559, "text": "{β€˜acpitz’: [shwtemp(label=”, current=27.8, high=119.0, critical=119.0), shwtemp(label=”, current=29.8, high=119.0, critical=119.0), shwtemp(label=”, current=10.0, high=None, critical=None)], β€˜coretemp’: [shwtemp(label=’Physical id 0β€², current=42.0, high=100.0, critical=100.0), shwtemp(label=’Core 0β€², current=41.0, high=100.0, critical=100.0), shwtemp(label=’Core 1β€², current=41.0, high=100.0, critical=100.0), shwtemp(label=’Physical id 0β€², current=42.0, high=100.0, critical=100.0), shwtemp(label=’Core 0β€², current=41.0, high=100.0, critical=100.0), shwtemp(label=’Core 1β€², current=41.0, high=100.0, critical=100.0)]} " }, { "code": null, "e": 10369, "s": 10182, "text": "2) psutil.sensors_fans() – This function gives the details of hardware fans speed expressed in RPM (rounds per minute). If sensors are not supported by the OS an empty dict is returned. " }, { "code": null, "e": 10381, "s": 10369, "text": "Example : " }, { "code": null, "e": 10388, "s": 10381, "text": "Python" }, { "code": "import psutil print(psutil.sensors_fans())", "e": 10431, "s": 10388, "text": null }, { "code": null, "e": 10439, "s": 10431, "text": "Output:" }, { "code": null, "e": 10487, "s": 10439, "text": "{'asus': [sfan(label='cpu_fan', current=3000)]}" }, { "code": null, "e": 10582, "s": 10487, "text": "3) psutil.sensors_battery() – This function gives battery status information as a named tuple." }, { "code": null, "e": 10596, "s": 10582, "text": "Parameters: " }, { "code": null, "e": 10642, "s": 10596, "text": "percent – battery power left as a percentage." }, { "code": null, "e": 10725, "s": 10642, "text": "secsleft – an approximate time in seconds before battery is completely discharged." }, { "code": null, "e": 10812, "s": 10725, "text": "power_plugged – True if the AC power cable is connected, False if it is not connected." }, { "code": null, "e": 10824, "s": 10812, "text": "Example : " }, { "code": null, "e": 10831, "s": 10824, "text": "Python" }, { "code": "import psutil print(psutil.sensors_battery())", "e": 10878, "s": 10831, "text": null }, { "code": null, "e": 10886, "s": 10878, "text": "Output:" }, { "code": null, "e": 10960, "s": 10886, "text": "sbattery(percent=98.98572501878287, secsleft=22913, power_plugged=False) " }, { "code": null, "e": 11075, "s": 10960, "text": "1) psutil.boot_time() – This function returns the system boot time which is expressed in seconds since the epoch. " }, { "code": null, "e": 11087, "s": 11075, "text": "Example : " }, { "code": null, "e": 11094, "s": 11087, "text": "Python" }, { "code": "import psutil, datetime print(psutil.boot_time())", "e": 11145, "s": 11094, "text": null }, { "code": null, "e": 11154, "s": 11145, "text": "Output: " }, { "code": null, "e": 11167, "s": 11154, "text": "1582860765.0" }, { "code": null, "e": 11277, "s": 11167, "text": "2) psutil.users() – This function gives the list of users who are connected on the system as a named tuples. " }, { "code": null, "e": 11290, "s": 11277, "text": "Parameters: " }, { "code": null, "e": 11332, "s": 11290, "text": "user – It is the system name of the user." }, { "code": null, "e": 11364, "s": 11332, "text": "terminal – the tty of the user." }, { "code": null, "e": 11398, "s": 11364, "text": "host – the host name of the user." }, { "code": null, "e": 11491, "s": 11398, "text": "started – the creation time as a floating point number expressed in seconds since the epoch." }, { "code": null, "e": 11527, "s": 11491, "text": "pid – the PID of the login process." }, { "code": null, "e": 11539, "s": 11527, "text": "Example : " }, { "code": null, "e": 11546, "s": 11539, "text": "Python" }, { "code": "import psutil print(psutil.users())", "e": 11583, "s": 11546, "text": null }, { "code": null, "e": 11591, "s": 11583, "text": "Output:" }, { "code": null, "e": 11683, "s": 11591, "text": "[suser(name=’admin1β€², terminal=’tty7β€², host=’localhost’, started=1582860800.0, pid=1747)] " }, { "code": null, "e": 11701, "s": 11685, "text": "shikharraizaday" }, { "code": null, "e": 11742, "s": 11701, "text": "d42dhpakvdal13px45kdvrdzg619cup8jrm16xvu" }, { "code": null, "e": 11757, "s": 11742, "text": "python-modules" }, { "code": null, "e": 11764, "s": 11757, "text": "Python" }, { "code": null, "e": 11862, "s": 11764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11880, "s": 11862, "text": "Python Dictionary" }, { "code": null, "e": 11922, "s": 11880, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 11944, "s": 11922, "text": "Enumerate() in Python" }, { "code": null, "e": 11979, "s": 11944, "text": "Read a file line by line in Python" }, { "code": null, "e": 12005, "s": 11979, "text": "Python String | replace()" }, { "code": null, "e": 12037, "s": 12005, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 12066, "s": 12037, "text": "*args and **kwargs in Python" }, { "code": null, "e": 12093, "s": 12066, "text": "Python Classes and Objects" }, { "code": null, "e": 12123, "s": 12093, "text": "Iterate over a list in Python" } ]
How to Push a Container Image to a Docker Repository?
30 Sep, 2021 In this article we will look into how you can push a container image to a Docker Repo. We’re going to use Docker Hub as a container registry, that we’re going to push our Docker image to. Follow the below steps to push container Image to Docker repository: Step 1: The first thing you need to do is make sure that you’ve signed up for Docker account. You can easily come to hub.docker.com, enter a Docker ID, your email address and a password. That’s all you need to do. This Docker account is completely free and you don’t have to pay a single dime for it. You want to make sure that you sign in. This will take you to your dashboard. As you can see here, we haven’t pushed any containers to my register yet: Step 2: Now, let’s go ahead and take care of that right now. First, we’ll start off with typing the below command. Now, here our credentials are already authenticated, but if yours aren’t, this will ask you to enter your Docker ID and password that you would’ve created when you signed up for Docker Hub account. docker login Step 3: The next thing we are going to need to do is, select an image that we want to push. So, we are going to type the below command: docker images We would use a awesomeapp image that we created earlier for this article. Step 4: So we will use the below command with the tag of the current image docker push awesomeapp/firstimage Now, what it’s doing is, taking that image that’s on our local machine and pushing it out into the Docker Hub. If we head back over to our Docker Hub, when we refresh the page, we can now see that image that we just pushed available here in our registry. At this point we have successfully pushed our docker image to docker repo. simranarora5sos Cloud-Computing docker Docker Container Advanced Computer Subject Microsoft Azure Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2021" }, { "code": null, "e": 217, "s": 28, "text": "In this article we will look into how you can push a container image to a Docker Repo. We’re going to use Docker Hub as a container registry, that we’re going to push our Docker image to. " }, { "code": null, "e": 286, "s": 217, "text": "Follow the below steps to push container Image to Docker repository:" }, { "code": null, "e": 739, "s": 286, "text": "Step 1: The first thing you need to do is make sure that you’ve signed up for Docker account. You can easily come to hub.docker.com, enter a Docker ID, your email address and a password. That’s all you need to do. This Docker account is completely free and you don’t have to pay a single dime for it. You want to make sure that you sign in. This will take you to your dashboard. As you can see here, we haven’t pushed any containers to my register yet:" }, { "code": null, "e": 1053, "s": 739, "text": "Step 2: Now, let’s go ahead and take care of that right now. First, we’ll start off with typing the below command. Now, here our credentials are already authenticated, but if yours aren’t, this will ask you to enter your Docker ID and password that you would’ve created when you signed up for Docker Hub account. " }, { "code": null, "e": 1066, "s": 1053, "text": "docker login" }, { "code": null, "e": 1202, "s": 1066, "text": "Step 3: The next thing we are going to need to do is, select an image that we want to push. So, we are going to type the below command:" }, { "code": null, "e": 1216, "s": 1202, "text": "docker images" }, { "code": null, "e": 1291, "s": 1216, "text": "We would use a awesomeapp image that we created earlier for this article. " }, { "code": null, "e": 1366, "s": 1291, "text": "Step 4: So we will use the below command with the tag of the current image" }, { "code": null, "e": 1400, "s": 1366, "text": "docker push awesomeapp/firstimage" }, { "code": null, "e": 1656, "s": 1400, "text": "Now, what it’s doing is, taking that image that’s on our local machine and pushing it out into the Docker Hub. If we head back over to our Docker Hub, when we refresh the page, we can now see that image that we just pushed available here in our registry. " }, { "code": null, "e": 1731, "s": 1656, "text": "At this point we have successfully pushed our docker image to docker repo." }, { "code": null, "e": 1747, "s": 1731, "text": "simranarora5sos" }, { "code": null, "e": 1763, "s": 1747, "text": "Cloud-Computing" }, { "code": null, "e": 1770, "s": 1763, "text": "docker" }, { "code": null, "e": 1787, "s": 1770, "text": "Docker Container" }, { "code": null, "e": 1813, "s": 1787, "text": "Advanced Computer Subject" }, { "code": null, "e": 1829, "s": 1813, "text": "Microsoft Azure" } ]
Compilation and Execution of a Java Program
01 Oct, 2021 Java, being a platform-independent programming language, doesn’t work on the one-step compilation. Instead, it involves a two-step execution, first through an OS-independent compiler; and second, in a virtual machine (JVM) which is custom-built for every operating system. The two principal stages are explained below: First, the source β€˜.java’ file is passed through the compiler, which then encodes the source code into a machine-independent encoding, known as Bytecode. The content of each class contained in the source file is stored in a separate β€˜.class’ file. While converting the source code into the bytecode, the compiler follows the following steps: Step 1: Parse: Reads a set of *.java source files and maps the resulting token sequence into AST (Abstract Syntax Tree)-Nodes. Step 2: Enter: Enters symbols for the definitions into the symbol table. Step 3: Process annotations: If Requested, processes annotations found in the specified compilation units. Step 4: Attribute: Attributes the Syntax trees. This step includes name resolution, type checking and constant folding. Step 5: Flow: Performs dataflow analysis on the trees from the previous step. This includes checks for assignments and reachability. Step 6: Desugar: Rewrites the AST and translates away some syntactic sugar. Step 7: Generate: Generates β€˜.Class’ files. https://www.youtube.com/watch?v=0f-Sx81bIWQ The class files generated by the compiler are independent of the machine or the OS, which allows them to be run on any system. To run, the main class file (the class that contains the method main) is passed to the JVM and then goes through three main stages before the final machine code is executed. These stages are:These states do include: ClassLoaderBytecode VerifierJust-In-Time Compiler ClassLoader Bytecode Verifier Just-In-Time Compiler Let us discuss all 3 stages. Stage 1: Class Loader The main class is loaded into the memory bypassing its β€˜.class’ file to the JVM, through invoking the latter. All the other classes referenced in the program are loaded through the class loader.A class loader, itself an object, creates a flat namespace of class bodies that are referenced by a string name. The method definition is provided below illustration as follows: Illustration: // loadClass function prototype Class r = loadClass(String className, boolean resolveIt); // className: name of the class to be loaded // resolveIt: flag to decide whether any referenced class should be loaded or not. There are two types of class loaders primordial non-primordial The primordial class loader is embedded into all the JVMs and is the default class loader. A non-primordial class loader is a user-defined class loader, which can be coded in order to customize the class-loading process. Non-primordial class loader, if defined, is preferred over the default one, to load classes. Stage 2: Bytecode Verifier After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier, whose job is to check that the instructions don’t perform damaging actions. The following are some of the checks carried out: Variables are initialized before they are used. Method calls match the types of object references. Rules for accessing private data and methods are not violated. Local variable accesses fall within the runtime stack. The run-time stack does not overflow. If any of the above checks fail, the verifier doesn’t allow the class to be loaded. Stage 3: Just-In-Time Compiler This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy translation process. This can lead to performance gains in the execution speed unless methods are executed less frequently. The process can be well-illustrated by the following diagram as given above as follows from which we landed up to the conclusion. Conclusion: Due to the two-step execution process described above, a java program is independent of the target operating system. However, because of the same, the execution time is way more than a similar program written in a compiled platform-dependent program. Implementation: Consider simple printing program is written somewhere on the local directory in a machine. Java // Java Program to Illustrate Compilation and Execution// Stages // Main classclass GFG { // Main driver method public static void main(String[] args) { // Print command System.out.print("Welcome to Geeks"); }} Welcome to Geeks Let us understand the real compilation and execution process. Step 1: Let us create a file writing simple printing code in a text file and saving it with β€œ.java” extension. Step 2: Open the terminal(here we are using macOS)and go to the Desktop directory using the below command as follows. cd /Users/mayanksolanki/GFG.java Step 3: Let us try to compile our program with the below command javac GFG.java Step 4: Lastly run it with the below command as follows: java GFG Note: GFG.class file is created after the third step which means that now our entire code in the java programming language is secure encrypted as it contains only binary. In step 4 we are running that file. Refer to the below media for ease of understanding. cgevorgharutyunyan ManasChhabra2 solankimayank java-basics 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 How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Oct, 2021" }, { "code": null, "e": 326, "s": 52, "text": "Java, being a platform-independent programming language, doesn’t work on the one-step compilation. Instead, it involves a two-step execution, first through an OS-independent compiler; and second, in a virtual machine (JVM) which is custom-built for every operating system. " }, { "code": null, "e": 372, "s": 326, "text": "The two principal stages are explained below:" }, { "code": null, "e": 714, "s": 372, "text": "First, the source β€˜.java’ file is passed through the compiler, which then encodes the source code into a machine-independent encoding, known as Bytecode. The content of each class contained in the source file is stored in a separate β€˜.class’ file. While converting the source code into the bytecode, the compiler follows the following steps:" }, { "code": null, "e": 841, "s": 714, "text": "Step 1: Parse: Reads a set of *.java source files and maps the resulting token sequence into AST (Abstract Syntax Tree)-Nodes." }, { "code": null, "e": 914, "s": 841, "text": "Step 2: Enter: Enters symbols for the definitions into the symbol table." }, { "code": null, "e": 1021, "s": 914, "text": "Step 3: Process annotations: If Requested, processes annotations found in the specified compilation units." }, { "code": null, "e": 1141, "s": 1021, "text": "Step 4: Attribute: Attributes the Syntax trees. This step includes name resolution, type checking and constant folding." }, { "code": null, "e": 1274, "s": 1141, "text": "Step 5: Flow: Performs dataflow analysis on the trees from the previous step. This includes checks for assignments and reachability." }, { "code": null, "e": 1350, "s": 1274, "text": "Step 6: Desugar: Rewrites the AST and translates away some syntactic sugar." }, { "code": null, "e": 1395, "s": 1350, "text": "Step 7: Generate: Generates β€˜.Class’ files. " }, { "code": null, "e": 1439, "s": 1395, "text": "https://www.youtube.com/watch?v=0f-Sx81bIWQ" }, { "code": null, "e": 1782, "s": 1439, "text": "The class files generated by the compiler are independent of the machine or the OS, which allows them to be run on any system. To run, the main class file (the class that contains the method main) is passed to the JVM and then goes through three main stages before the final machine code is executed. These stages are:These states do include:" }, { "code": null, "e": 1832, "s": 1782, "text": "ClassLoaderBytecode VerifierJust-In-Time Compiler" }, { "code": null, "e": 1844, "s": 1832, "text": "ClassLoader" }, { "code": null, "e": 1862, "s": 1844, "text": "Bytecode Verifier" }, { "code": null, "e": 1884, "s": 1862, "text": "Just-In-Time Compiler" }, { "code": null, "e": 1914, "s": 1884, "text": "Let us discuss all 3 stages. " }, { "code": null, "e": 1936, "s": 1914, "text": "Stage 1: Class Loader" }, { "code": null, "e": 2308, "s": 1936, "text": "The main class is loaded into the memory bypassing its β€˜.class’ file to the JVM, through invoking the latter. All the other classes referenced in the program are loaded through the class loader.A class loader, itself an object, creates a flat namespace of class bodies that are referenced by a string name. The method definition is provided below illustration as follows:" }, { "code": null, "e": 2322, "s": 2308, "text": "Illustration:" }, { "code": null, "e": 2542, "s": 2322, "text": "// loadClass function prototype\n\nClass r = loadClass(String className, boolean resolveIt);\n\n// className: name of the class to be loaded\n// resolveIt: flag to decide whether any referenced class should be loaded or not." }, { "code": null, "e": 2579, "s": 2542, "text": "There are two types of class loaders" }, { "code": null, "e": 2590, "s": 2579, "text": "primordial" }, { "code": null, "e": 2605, "s": 2590, "text": "non-primordial" }, { "code": null, "e": 2920, "s": 2605, "text": "The primordial class loader is embedded into all the JVMs and is the default class loader. A non-primordial class loader is a user-defined class loader, which can be coded in order to customize the class-loading process. Non-primordial class loader, if defined, is preferred over the default one, to load classes. " }, { "code": null, "e": 2947, "s": 2920, "text": "Stage 2: Bytecode Verifier" }, { "code": null, "e": 3184, "s": 2947, "text": "After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier, whose job is to check that the instructions don’t perform damaging actions. The following are some of the checks carried out: " }, { "code": null, "e": 3232, "s": 3184, "text": "Variables are initialized before they are used." }, { "code": null, "e": 3283, "s": 3232, "text": "Method calls match the types of object references." }, { "code": null, "e": 3346, "s": 3283, "text": "Rules for accessing private data and methods are not violated." }, { "code": null, "e": 3401, "s": 3346, "text": "Local variable accesses fall within the runtime stack." }, { "code": null, "e": 3439, "s": 3401, "text": "The run-time stack does not overflow." }, { "code": null, "e": 3523, "s": 3439, "text": "If any of the above checks fail, the verifier doesn’t allow the class to be loaded." }, { "code": null, "e": 3554, "s": 3523, "text": "Stage 3: Just-In-Time Compiler" }, { "code": null, "e": 3999, "s": 3554, "text": "This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a relatively lengthy translation process. This can lead to performance gains in the execution speed unless methods are executed less frequently." }, { "code": null, "e": 4129, "s": 3999, "text": "The process can be well-illustrated by the following diagram as given above as follows from which we landed up to the conclusion." }, { "code": null, "e": 4392, "s": 4129, "text": "Conclusion: Due to the two-step execution process described above, a java program is independent of the target operating system. However, because of the same, the execution time is way more than a similar program written in a compiled platform-dependent program." }, { "code": null, "e": 4408, "s": 4392, "text": "Implementation:" }, { "code": null, "e": 4499, "s": 4408, "text": "Consider simple printing program is written somewhere on the local directory in a machine." }, { "code": null, "e": 4504, "s": 4499, "text": "Java" }, { "code": "// Java Program to Illustrate Compilation and Execution// Stages // Main classclass GFG { // Main driver method public static void main(String[] args) { // Print command System.out.print(\"Welcome to Geeks\"); }}", "e": 4743, "s": 4504, "text": null }, { "code": null, "e": 4760, "s": 4743, "text": "Welcome to Geeks" }, { "code": null, "e": 4822, "s": 4760, "text": "Let us understand the real compilation and execution process." }, { "code": null, "e": 4933, "s": 4822, "text": "Step 1: Let us create a file writing simple printing code in a text file and saving it with β€œ.java” extension." }, { "code": null, "e": 5051, "s": 4933, "text": "Step 2: Open the terminal(here we are using macOS)and go to the Desktop directory using the below command as follows." }, { "code": null, "e": 5085, "s": 5051, "text": " cd /Users/mayanksolanki/GFG.java" }, { "code": null, "e": 5150, "s": 5085, "text": "Step 3: Let us try to compile our program with the below command" }, { "code": null, "e": 5165, "s": 5150, "text": "javac GFG.java" }, { "code": null, "e": 5222, "s": 5165, "text": "Step 4: Lastly run it with the below command as follows:" }, { "code": null, "e": 5232, "s": 5222, "text": "java GFG " }, { "code": null, "e": 5492, "s": 5232, "text": "Note: GFG.class file is created after the third step which means that now our entire code in the java programming language is secure encrypted as it contains only binary. In step 4 we are running that file. Refer to the below media for ease of understanding." }, { "code": null, "e": 5511, "s": 5492, "text": "cgevorgharutyunyan" }, { "code": null, "e": 5525, "s": 5511, "text": "ManasChhabra2" }, { "code": null, "e": 5539, "s": 5525, "text": "solankimayank" }, { "code": null, "e": 5551, "s": 5539, "text": "java-basics" }, { "code": null, "e": 5556, "s": 5551, "text": "Java" }, { "code": null, "e": 5561, "s": 5556, "text": "Java" }, { "code": null, "e": 5659, "s": 5561, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5710, "s": 5659, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 5741, "s": 5710, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5760, "s": 5741, "text": "Interfaces in Java" }, { "code": null, "e": 5790, "s": 5760, "text": "HashMap in Java with Examples" }, { "code": null, "e": 5805, "s": 5790, "text": "Stream In Java" }, { "code": null, "e": 5823, "s": 5805, "text": "ArrayList in Java" }, { "code": null, "e": 5843, "s": 5823, "text": "Collections in Java" }, { "code": null, "e": 5867, "s": 5843, "text": "Singleton Class in Java" }, { "code": null, "e": 5899, "s": 5867, "text": "Multidimensional Arrays in Java" } ]
Two nodes of a BST are swapped, correct the BST
20 Jun, 2022 Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST. Input Tree: 10 / \ 5 8 / \ 2 20 In the above tree, nodes 20 and 8 must be swapped to fix the tree. Following is the output tree 10 / \ 5 20 / \ 2 8 The inorder traversal of a BST produces a sorted array. So a simple method is to store inorder traversal of the input tree in an auxiliary array. Sort the auxiliary array. Finally, insert the auxiliary array elements back to the BST, keeping the structure of the BST same. The time complexity of this method is O(nLogn) and the auxiliary space needed is O(n). We can solve this in O(n) time and with a single traversal of the given BST. Since inorder traversal of BST is always a sorted array, the problem can be reduced to a problem where two elements of a sorted array are swapped. There are two cases that we need to handle:1. The swapped nodes are not adjacent in the inorder traversal of the BST. For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}. The inorder traversal of the given tree is 3 25 7 8 10 15 20 5 If we observe carefully, during inorder traversal, we find node 7 is smaller than the previous visited node 25. Here save the context of node 25 (previous node). Again, we find that node 5 is smaller than the previous node 20. This time, we save the context of node 5 (the current node ). Finally, swap the two node’s values.2. The swapped nodes are adjacent in the inorder traversal of BST. For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}. The inorder traversal of the given tree is 3 5 8 7 10 15 20 25 Unlike case #1, here only one point exists where a node value is smaller than the previous node value. e.g. node 7 is smaller than node 8. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. How to Solve? We will maintain three-pointers, first, middle, and last. When we find the first point where the current node value is smaller than the previous node value, we update the first with the previous node & the middle with the current node. When we find the second point where the current node value is smaller than the previous node value, we update the last with the current node. In the case of #2, we will never find the second point. So, the last pointer will not be updated. After processing, if the last node value is null, then two swapped nodes of BST are adjacent. Following is the implementation of the given code. C++ C Java Python3 C# Javascript // Two nodes in the BST's swapped, correct the BST.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to swap two integersvoid swap( int* a, int* b ){ int t = *a; *a = *b; *b = t;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node *)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // This function does inorder traversal to find out the two swapped nodes.// It sets three pointers, first, middle and last. If the swapped nodes are// adjacent to each other, then first and middle contain the resultant nodes// Else, first and last contain the resultant nodesvoid correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ){ if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); }} // A function to fix a given BST where two nodes are swapped. This// function uses correctBSTUtil() to find out two nodes and swaps the// nodes to fix the BSTvoid correctBST( struct node* root ){ // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the pointers to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST.} /* A utility function to print Inorder traversal */void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); cout <<" "<< node->data; printInorder(node->right);} /* Driver program to test above functions*/int main(){ /* 6 / \ 10 2 / \ / \ 1 3 7 12 10 and 2 are swapped */ struct node *root = newNode(6); root->left = newNode(10); root->right = newNode(2); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(12); root->right->left = newNode(7); cout <<"Inorder Traversal of the original tree \n"; printInorder(root); correctBST(root); cout <<"\nInorder Traversal of the fixed tree \n"; printInorder(root); return 0;} // This code is contributed by shivanisinghss2110 // Two nodes in the BST's swapped, correct the BST.#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to swap two integersvoid swap( int* a, int* b ){ int t = *a; *a = *b; *b = t;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node *)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // This function does inorder traversal to find out the two swapped nodes.// It sets three pointers, first, middle and last. If the swapped nodes are// adjacent to each other, then first and middle contain the resultant nodes// Else, first and last contain the resultant nodesvoid correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ){ if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); }} // A function to fix a given BST where two nodes are swapped. This// function uses correctBSTUtil() to find out two nodes and swaps the// nodes to fix the BSTvoid correctBST( struct node* root ){ // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the pointers to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST.} /* A utility function to print Inorder traversal */void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf("%d ", node->data); printInorder(node->right);} /* Driver program to test above functions*/int main(){ /* 6 / \ 10 2 / \ / \ 1 3 7 12 10 and 2 are swapped */ struct node *root = newNode(6); root->left = newNode(10); root->right = newNode(2); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(12); root->right->left = newNode(7); printf("Inorder Traversal of the original tree \n"); printInorder(root); correctBST(root); printf("\nInorder Traversal of the fixed tree \n"); printInorder(root); return 0;} // Java program to correct the BST// if two nodes are swappedimport java.util.*;import java.lang.*;import java.io.*; class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree{ Node first, middle, last, prev; // This function does inorder traversal // to find out the two swapped nodes. // It sets three pointers, first, middle // and last. If the swapped nodes are // adjacent to each other, then first // and middle contain the resultant nodes // Else, first and last contain the // resultant nodes void correctBSTUtil( Node root) { if( root != null ) { // Recur for the left subtree correctBSTUtil( root.left); // If this node is smaller than // the previous node, it's // violating the BST rule. if (prev != null && root.data < prev.data) { // If this is first violation, // mark these two nodes as // 'first' and 'middle' if (first == null) { first = prev; middle = root; } // If this is second violation, // mark this node as last else last = root; } // Mark this node as previous prev = root; // Recur for the right subtree correctBSTUtil( root.right); } } // A function to fix a given BST where // two nodes are swapped. This function // uses correctBSTUtil() to find out // two nodes and swaps the nodes to // fix the BST void correctBST( Node root ) { // Initialize pointers needed // for correctBSTUtil() first = middle = last = prev = null; // Set the pointers to find out // two nodes correctBSTUtil( root ); // Fix (or correct) the tree if( first != null && last != null ) { int temp = first.data; first.data = last.data; last.data = temp; } // Adjacent nodes swapped else if( first != null && middle != null ) { int temp = first.data; first.data = middle.data; middle.data = temp; } // else nodes have not been swapped, // passed tree is really BST. } /* A utility function to print Inorder traversal */ void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(" " + node.data); printInorder(node.right); } // Driver program to test above functions public static void main (String[] args) { /* 6 / \ 10 2 / \ / \ 1 3 7 12 10 and 2 are swapped */ Node root = new Node(6); root.left = new Node(10); root.right = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(12); root.right.left = new Node(7); System.out.println("Inorder Traversal"+ " of the original tree"); BinaryTree tree = new BinaryTree(); tree.printInorder(root); tree.correctBST(root); System.out.println("\nInorder Traversal"+ " of the fixed tree"); tree.printInorder(root); }}// This code is contributed by Chhavi # Python3 program to correct the BST # if two nodes are swappedclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Utility function to track the nodes# that we have to swapdef correctBstUtil(root, first, middle, last, prev): if(root): # Recur for the left sub tree correctBstUtil(root.left, first, middle, last, prev) # If this is the first violation, mark these # two nodes as 'first and 'middle' if(prev[0] and root.key < prev[0].key): if(not first[0]): first[0] = prev[0] middle[0] = root else: # If this is the second violation, # mark this node as last last[0] = root prev[0] = root # Recur for the right subtree correctBstUtil(root.right, first, middle, last, prev) # A function to fix a given BST where# two nodes are swapped. This function# uses correctBSTUtil() to find out two# nodes and swaps the nodes to fix the BSTdef correctBst(root): # Followed four lines just for forming # an array with only index 0 filled # with None and we will update it accordingly. # we made it null so that we can fill # node data in them. first = [None] middle = [None] last = [None] prev = [None] # Setting arrays (having zero index only) # for capturing the required node correctBstUtil(root, first, middle, last, prev) # Fixing the two nodes if(first[0] and last[0]): # Swapping for first and last key values first[0].key, last[0].key = (last[0].key, first[0].key) elif(first[0] and middle[0]): # Swapping for first and middle key values first[0].key, middle[0].key = (middle[0].key, first[0].key) # else tree will be fine # Function to print inorder# traversal of treedef PrintInorder(root): if(root): PrintInorder(root.left) print(root.key, end = " ") PrintInorder(root.right) else: return # Driver code # 6# / \# 10 2# / \ / \# 1 3 7 12 # Following 7 lines are for tree formationroot = Node(6)root.left = Node(10)root.right = Node(2)root.left.left = Node(1)root.left.right = Node(3)root.right.left = Node(7)root.right.right = Node(12) # Printing inorder traversal of normal treeprint("inorder traversal of normal tree")PrintInorder(root)print("") # Function call to do the taskcorrectBst(root) # Printing inorder for corrected Bst treeprint("")print("inorder for corrected BST") PrintInorder(root) # This code is contributed by rajutkarshai // C# program to correct the BST// if two nodes are swappedusing System;class Node{ public int data;public Node left, right;public Node(int d){ data = d; left = right = null;}} class BinaryTree{ Node first, middle, last, prev; // This function does inorder traversal// to find out the two swapped nodes.// It sets three pointers, first, middle// and last. If the swapped nodes are// adjacent to each other, then first// and middle contain the resultant nodes// Else, first and last contain the// resultant nodesvoid correctBSTUtil( Node root){ if( root != null ) { // Recur for the // left subtree correctBSTUtil(root.left); // If this node is smaller than // the previous node, it's // violating the BST rule. if (prev != null && root.data < prev.data) { // If this is first violation, // mark these two nodes as // 'first' and 'middle' if (first == null) { first = prev; middle = root; } // If this is second violation, // mark this node as last else last = root; } // Mark this node // as previous prev = root; // Recur for the // right subtree correctBSTUtil(root.right); }} // A function to fix a given BST where// two nodes are swapped. This function// uses correctBSTUtil() to find out// two nodes and swaps the nodes to// fix the BSTvoid correctBST( Node root ){ // Initialize pointers needed // for correctBSTUtil() first = middle = last = prev = null; // Set the pointers to // find out two nodes correctBSTUtil(root); // Fix (or correct) // the tree if(first != null && last != null) { int temp = first.data; first.data = last.data; last.data = temp; } // Adjacent nodes swapped else if(first != null && middle != null) { int temp = first.data; first.data = middle.data; middle.data = temp; } // else nodes have not been // swapped, passed tree is // really BST.} // A utility function to print// Inorder traversalvoid printInorder(Node node){ if (node == null) return; printInorder(node.left); Console.Write(" " + node.data); printInorder(node.right);} // Driver codepublic static void Main(String[] args){ /* 6 / \ 10 2 / \ / \ 1 3 7 12 10 and 2 are swapped */ Node root = new Node(6); root.left = new Node(10); root.right = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(12); root.right.left = new Node(7); Console.WriteLine("Inorder Traversal" + " of the original tree"); BinaryTree tree = new BinaryTree(); tree.printInorder(root); tree.correctBST(root); Console.WriteLine("\nInorder Traversal" + " of the fixed tree"); tree.printInorder(root);}} // This code is contributed by gauravrajput1 <script> // JavaScript program to correct the BST// if two nodes are swapped class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var first, middle, last, prev; // This function does inorder traversal // to find out the two swapped nodes. // It sets three pointers, first, middle // and last. If the swapped nodes are // adjacent to each other, then first // and middle contain the resultant nodes // Else, first and last contain the // resultant nodes function correctBSTUtil(root) { if (root != null) { // Recur for the left subtree correctBSTUtil(root.left); // If this node is smaller than // the previous node, it's // violating the BST rule. if (prev != null && root.data < prev.data) { // If this is first violation, // mark these two nodes as // 'first' and 'middle' if (first == null) { first = prev; middle = root; } // If this is second violation, // mark this node as last else last = root; } // Mark this node as previous prev = root; // Recur for the right subtree correctBSTUtil(root.right); } } // A function to fix a given BST where // two nodes are swapped. This function // uses correctBSTUtil() to find out // two nodes and swaps the nodes to // fix the BST function correctBST(root) { // Initialize pointers needed // for correctBSTUtil() first = middle = last = prev = null; // Set the pointers to find out // two nodes correctBSTUtil(root); // Fix (or correct) the tree if (first != null && last != null) { var temp = first.data; first.data = last.data; last.data = temp; } // Adjacent nodes swapped else if (first != null && middle != null) { var temp = first.data; first.data = middle.data; middle.data = temp; } // else nodes have not been swapped, // passed tree is really BST. } /* * A utility function to print Inorder traversal */ function printInorder(node) { if (node == null) return; printInorder(node.left); document.write(" " + node.data); printInorder(node.right); } // Driver program to test above functions /* * 6 / \ 10 2 / \ / \ 1 3 7 12 * * 10 and 2 are swapped */ var root = new Node(6); root.left = new Node(10); root.right = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(12); root.right.left = new Node(7); document.write("Inorder Traversal" + " of the original tree<br/>"); printInorder(root); correctBST(root); document.write("<br/>Inorder Traversal" + " of the fixed tree<br/>"); printInorder(root); // This code contributed by aashish1995 </script> Inorder Traversal of the original tree 1 10 3 6 7 2 12 Inorder Traversal of the fixed tree 1 2 3 6 7 10 12 Time Complexity: O(n) Auxiliary Space: O(n) for call stack Two nodes of a BST are swapped, correct the BST | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersTwo nodes of a BST are swapped, correct the BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:06β€’Liveβ€’<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=wYaq3U7Mqyg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> rajutkarshai GauravRajput1 aashish1995 gabaa406 sumitgumber28 shivanisinghss2110 adnanirshad158 saurabh1990aror arorakashish0911 polymatir3j hardikkoriintern Amazon BankBazaar FactSet Microsoft Binary Search Tree Amazon Microsoft FactSet BankBazaar Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Optimal Binary Search Tree | DP-24 Sorted Array to Balanced BST Inorder Successor in Binary Search Tree Convert a normal BST to Balanced BST set vs unordered_set in C++ STL Find k-th smallest element in BST (Order Statistics in BST) Check if a given array can represent Preorder Traversal of Binary Search Tree
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 139, "s": 52, "text": "Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST. " }, { "code": null, "e": 372, "s": 139, "text": "Input Tree:\n 10\n / \\\n 5 8\n / \\\n 2 20\n\nIn the above tree, nodes 20 and 8 must be swapped to fix the tree. \nFollowing is the output tree\n 10\n / \\\n 5 20\n / \\\n 2 8" }, { "code": null, "e": 732, "s": 372, "text": "The inorder traversal of a BST produces a sorted array. So a simple method is to store inorder traversal of the input tree in an auxiliary array. Sort the auxiliary array. Finally, insert the auxiliary array elements back to the BST, keeping the structure of the BST same. The time complexity of this method is O(nLogn) and the auxiliary space needed is O(n)." }, { "code": null, "e": 1075, "s": 732, "text": "We can solve this in O(n) time and with a single traversal of the given BST. Since inorder traversal of BST is always a sorted array, the problem can be reduced to a problem where two elements of a sorted array are swapped. There are two cases that we need to handle:1. The swapped nodes are not adjacent in the inorder traversal of the BST. " }, { "code": null, "e": 1208, "s": 1075, "text": " For example, Nodes 5 and 25 are swapped in {3 5 7 8 10 15 20 25}. \n The inorder traversal of the given tree is 3 25 7 8 10 15 20 5 " }, { "code": null, "e": 1600, "s": 1208, "text": "If we observe carefully, during inorder traversal, we find node 7 is smaller than the previous visited node 25. Here save the context of node 25 (previous node). Again, we find that node 5 is smaller than the previous node 20. This time, we save the context of node 5 (the current node ). Finally, swap the two node’s values.2. The swapped nodes are adjacent in the inorder traversal of BST." }, { "code": null, "e": 1734, "s": 1600, "text": " For example, Nodes 7 and 8 are swapped in {3 5 7 8 10 15 20 25}. \n The inorder traversal of the given tree is 3 5 8 7 10 15 20 25 " }, { "code": null, "e": 1874, "s": 1734, "text": "Unlike case #1, here only one point exists where a node value is smaller than the previous node value. e.g. node 7 is smaller than node 8. " }, { "code": null, "e": 1883, "s": 1874, "text": "Chapters" }, { "code": null, "e": 1910, "s": 1883, "text": "descriptions off, selected" }, { "code": null, "e": 1960, "s": 1910, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1983, "s": 1960, "text": "captions off, selected" }, { "code": null, "e": 1991, "s": 1983, "text": "English" }, { "code": null, "e": 2009, "s": 1991, "text": "default, selected" }, { "code": null, "e": 2033, "s": 2009, "text": "This is a modal window." }, { "code": null, "e": 2102, "s": 2033, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 2124, "s": 2102, "text": "End of dialog window." }, { "code": null, "e": 2709, "s": 2124, "text": "How to Solve? We will maintain three-pointers, first, middle, and last. When we find the first point where the current node value is smaller than the previous node value, we update the first with the previous node & the middle with the current node. When we find the second point where the current node value is smaller than the previous node value, we update the last with the current node. In the case of #2, we will never find the second point. So, the last pointer will not be updated. After processing, if the last node value is null, then two swapped nodes of BST are adjacent. " }, { "code": null, "e": 2761, "s": 2709, "text": "Following is the implementation of the given code. " }, { "code": null, "e": 2765, "s": 2761, "text": "C++" }, { "code": null, "e": 2767, "s": 2765, "text": "C" }, { "code": null, "e": 2772, "s": 2767, "text": "Java" }, { "code": null, "e": 2780, "s": 2772, "text": "Python3" }, { "code": null, "e": 2783, "s": 2780, "text": "C#" }, { "code": null, "e": 2794, "s": 2783, "text": "Javascript" }, { "code": "// Two nodes in the BST's swapped, correct the BST.#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to swap two integersvoid swap( int* a, int* b ){ int t = *a; *a = *b; *b = t;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node *)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // This function does inorder traversal to find out the two swapped nodes.// It sets three pointers, first, middle and last. If the swapped nodes are// adjacent to each other, then first and middle contain the resultant nodes// Else, first and last contain the resultant nodesvoid correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ){ if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); }} // A function to fix a given BST where two nodes are swapped. This// function uses correctBSTUtil() to find out two nodes and swaps the// nodes to fix the BSTvoid correctBST( struct node* root ){ // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the pointers to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST.} /* A utility function to print Inorder traversal */void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); cout <<\" \"<< node->data; printInorder(node->right);} /* Driver program to test above functions*/int main(){ /* 6 / \\ 10 2 / \\ / \\ 1 3 7 12 10 and 2 are swapped */ struct node *root = newNode(6); root->left = newNode(10); root->right = newNode(2); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(12); root->right->left = newNode(7); cout <<\"Inorder Traversal of the original tree \\n\"; printInorder(root); correctBST(root); cout <<\"\\nInorder Traversal of the fixed tree \\n\"; printInorder(root); return 0;} // This code is contributed by shivanisinghss2110", "e": 6244, "s": 2794, "text": null }, { "code": "// Two nodes in the BST's swapped, correct the BST.#include <stdio.h>#include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // A utility function to swap two integersvoid swap( int* a, int* b ){ int t = *a; *a = *b; *b = t;} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct node* newNode(int data){ struct node* node = (struct node *)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node);} // This function does inorder traversal to find out the two swapped nodes.// It sets three pointers, first, middle and last. If the swapped nodes are// adjacent to each other, then first and middle contain the resultant nodes// Else, first and last contain the resultant nodesvoid correctBSTUtil( struct node* root, struct node** first, struct node** middle, struct node** last, struct node** prev ){ if( root ) { // Recur for the left subtree correctBSTUtil( root->left, first, middle, last, prev ); // If this node is smaller than the previous node, it's violating // the BST rule. if (*prev && root->data < (*prev)->data) { // If this is first violation, mark these two nodes as // 'first' and 'middle' if ( !*first ) { *first = *prev; *middle = root; } // If this is second violation, mark this node as last else *last = root; } // Mark this node as previous *prev = root; // Recur for the right subtree correctBSTUtil( root->right, first, middle, last, prev ); }} // A function to fix a given BST where two nodes are swapped. This// function uses correctBSTUtil() to find out two nodes and swaps the// nodes to fix the BSTvoid correctBST( struct node* root ){ // Initialize pointers needed for correctBSTUtil() struct node *first, *middle, *last, *prev; first = middle = last = prev = NULL; // Set the pointers to find out two nodes correctBSTUtil( root, &first, &middle, &last, &prev ); // Fix (or correct) the tree if( first && last ) swap( &(first->data), &(last->data) ); else if( first && middle ) // Adjacent nodes swapped swap( &(first->data), &(middle->data) ); // else nodes have not been swapped, passed tree is really BST.} /* A utility function to print Inorder traversal */void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); printf(\"%d \", node->data); printInorder(node->right);} /* Driver program to test above functions*/int main(){ /* 6 / \\ 10 2 / \\ / \\ 1 3 7 12 10 and 2 are swapped */ struct node *root = newNode(6); root->left = newNode(10); root->right = newNode(2); root->left->left = newNode(1); root->left->right = newNode(3); root->right->right = newNode(12); root->right->left = newNode(7); printf(\"Inorder Traversal of the original tree \\n\"); printInorder(root); correctBST(root); printf(\"\\nInorder Traversal of the fixed tree \\n\"); printInorder(root); return 0;}", "e": 9626, "s": 6244, "text": null }, { "code": "// Java program to correct the BST// if two nodes are swappedimport java.util.*;import java.lang.*;import java.io.*; class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinaryTree{ Node first, middle, last, prev; // This function does inorder traversal // to find out the two swapped nodes. // It sets three pointers, first, middle // and last. If the swapped nodes are // adjacent to each other, then first // and middle contain the resultant nodes // Else, first and last contain the // resultant nodes void correctBSTUtil( Node root) { if( root != null ) { // Recur for the left subtree correctBSTUtil( root.left); // If this node is smaller than // the previous node, it's // violating the BST rule. if (prev != null && root.data < prev.data) { // If this is first violation, // mark these two nodes as // 'first' and 'middle' if (first == null) { first = prev; middle = root; } // If this is second violation, // mark this node as last else last = root; } // Mark this node as previous prev = root; // Recur for the right subtree correctBSTUtil( root.right); } } // A function to fix a given BST where // two nodes are swapped. This function // uses correctBSTUtil() to find out // two nodes and swaps the nodes to // fix the BST void correctBST( Node root ) { // Initialize pointers needed // for correctBSTUtil() first = middle = last = prev = null; // Set the pointers to find out // two nodes correctBSTUtil( root ); // Fix (or correct) the tree if( first != null && last != null ) { int temp = first.data; first.data = last.data; last.data = temp; } // Adjacent nodes swapped else if( first != null && middle != null ) { int temp = first.data; first.data = middle.data; middle.data = temp; } // else nodes have not been swapped, // passed tree is really BST. } /* A utility function to print Inorder traversal */ void printInorder(Node node) { if (node == null) return; printInorder(node.left); System.out.print(\" \" + node.data); printInorder(node.right); } // Driver program to test above functions public static void main (String[] args) { /* 6 / \\ 10 2 / \\ / \\ 1 3 7 12 10 and 2 are swapped */ Node root = new Node(6); root.left = new Node(10); root.right = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(12); root.right.left = new Node(7); System.out.println(\"Inorder Traversal\"+ \" of the original tree\"); BinaryTree tree = new BinaryTree(); tree.printInorder(root); tree.correctBST(root); System.out.println(\"\\nInorder Traversal\"+ \" of the fixed tree\"); tree.printInorder(root); }}// This code is contributed by Chhavi", "e": 13233, "s": 9626, "text": null }, { "code": "# Python3 program to correct the BST # if two nodes are swappedclass Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # Utility function to track the nodes# that we have to swapdef correctBstUtil(root, first, middle, last, prev): if(root): # Recur for the left sub tree correctBstUtil(root.left, first, middle, last, prev) # If this is the first violation, mark these # two nodes as 'first and 'middle' if(prev[0] and root.key < prev[0].key): if(not first[0]): first[0] = prev[0] middle[0] = root else: # If this is the second violation, # mark this node as last last[0] = root prev[0] = root # Recur for the right subtree correctBstUtil(root.right, first, middle, last, prev) # A function to fix a given BST where# two nodes are swapped. This function# uses correctBSTUtil() to find out two# nodes and swaps the nodes to fix the BSTdef correctBst(root): # Followed four lines just for forming # an array with only index 0 filled # with None and we will update it accordingly. # we made it null so that we can fill # node data in them. first = [None] middle = [None] last = [None] prev = [None] # Setting arrays (having zero index only) # for capturing the required node correctBstUtil(root, first, middle, last, prev) # Fixing the two nodes if(first[0] and last[0]): # Swapping for first and last key values first[0].key, last[0].key = (last[0].key, first[0].key) elif(first[0] and middle[0]): # Swapping for first and middle key values first[0].key, middle[0].key = (middle[0].key, first[0].key) # else tree will be fine # Function to print inorder# traversal of treedef PrintInorder(root): if(root): PrintInorder(root.left) print(root.key, end = \" \") PrintInorder(root.right) else: return # Driver code # 6# / \\# 10 2# / \\ / \\# 1 3 7 12 # Following 7 lines are for tree formationroot = Node(6)root.left = Node(10)root.right = Node(2)root.left.left = Node(1)root.left.right = Node(3)root.right.left = Node(7)root.right.right = Node(12) # Printing inorder traversal of normal treeprint(\"inorder traversal of normal tree\")PrintInorder(root)print(\"\") # Function call to do the taskcorrectBst(root) # Printing inorder for corrected Bst treeprint(\"\")print(\"inorder for corrected BST\") PrintInorder(root) # This code is contributed by rajutkarshai", "e": 16179, "s": 13233, "text": null }, { "code": "// C# program to correct the BST// if two nodes are swappedusing System;class Node{ public int data;public Node left, right;public Node(int d){ data = d; left = right = null;}} class BinaryTree{ Node first, middle, last, prev; // This function does inorder traversal// to find out the two swapped nodes.// It sets three pointers, first, middle// and last. If the swapped nodes are// adjacent to each other, then first// and middle contain the resultant nodes// Else, first and last contain the// resultant nodesvoid correctBSTUtil( Node root){ if( root != null ) { // Recur for the // left subtree correctBSTUtil(root.left); // If this node is smaller than // the previous node, it's // violating the BST rule. if (prev != null && root.data < prev.data) { // If this is first violation, // mark these two nodes as // 'first' and 'middle' if (first == null) { first = prev; middle = root; } // If this is second violation, // mark this node as last else last = root; } // Mark this node // as previous prev = root; // Recur for the // right subtree correctBSTUtil(root.right); }} // A function to fix a given BST where// two nodes are swapped. This function// uses correctBSTUtil() to find out// two nodes and swaps the nodes to// fix the BSTvoid correctBST( Node root ){ // Initialize pointers needed // for correctBSTUtil() first = middle = last = prev = null; // Set the pointers to // find out two nodes correctBSTUtil(root); // Fix (or correct) // the tree if(first != null && last != null) { int temp = first.data; first.data = last.data; last.data = temp; } // Adjacent nodes swapped else if(first != null && middle != null) { int temp = first.data; first.data = middle.data; middle.data = temp; } // else nodes have not been // swapped, passed tree is // really BST.} // A utility function to print// Inorder traversalvoid printInorder(Node node){ if (node == null) return; printInorder(node.left); Console.Write(\" \" + node.data); printInorder(node.right);} // Driver codepublic static void Main(String[] args){ /* 6 / \\ 10 2 / \\ / \\ 1 3 7 12 10 and 2 are swapped */ Node root = new Node(6); root.left = new Node(10); root.right = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(12); root.right.left = new Node(7); Console.WriteLine(\"Inorder Traversal\" + \" of the original tree\"); BinaryTree tree = new BinaryTree(); tree.printInorder(root); tree.correctBST(root); Console.WriteLine(\"\\nInorder Traversal\" + \" of the fixed tree\"); tree.printInorder(root);}} // This code is contributed by gauravrajput1", "e": 19064, "s": 16179, "text": null }, { "code": "<script> // JavaScript program to correct the BST// if two nodes are swapped class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var first, middle, last, prev; // This function does inorder traversal // to find out the two swapped nodes. // It sets three pointers, first, middle // and last. If the swapped nodes are // adjacent to each other, then first // and middle contain the resultant nodes // Else, first and last contain the // resultant nodes function correctBSTUtil(root) { if (root != null) { // Recur for the left subtree correctBSTUtil(root.left); // If this node is smaller than // the previous node, it's // violating the BST rule. if (prev != null && root.data < prev.data) { // If this is first violation, // mark these two nodes as // 'first' and 'middle' if (first == null) { first = prev; middle = root; } // If this is second violation, // mark this node as last else last = root; } // Mark this node as previous prev = root; // Recur for the right subtree correctBSTUtil(root.right); } } // A function to fix a given BST where // two nodes are swapped. This function // uses correctBSTUtil() to find out // two nodes and swaps the nodes to // fix the BST function correctBST(root) { // Initialize pointers needed // for correctBSTUtil() first = middle = last = prev = null; // Set the pointers to find out // two nodes correctBSTUtil(root); // Fix (or correct) the tree if (first != null && last != null) { var temp = first.data; first.data = last.data; last.data = temp; } // Adjacent nodes swapped else if (first != null && middle != null) { var temp = first.data; first.data = middle.data; middle.data = temp; } // else nodes have not been swapped, // passed tree is really BST. } /* * A utility function to print Inorder traversal */ function printInorder(node) { if (node == null) return; printInorder(node.left); document.write(\" \" + node.data); printInorder(node.right); } // Driver program to test above functions /* * 6 / \\ 10 2 / \\ / \\ 1 3 7 12 * * 10 and 2 are swapped */ var root = new Node(6); root.left = new Node(10); root.right = new Node(2); root.left.left = new Node(1); root.left.right = new Node(3); root.right.right = new Node(12); root.right.left = new Node(7); document.write(\"Inorder Traversal\" + \" of the original tree<br/>\"); printInorder(root); correctBST(root); document.write(\"<br/>Inorder Traversal\" + \" of the fixed tree<br/>\"); printInorder(root); // This code contributed by aashish1995 </script>", "e": 22320, "s": 19064, "text": null }, { "code": null, "e": 22445, "s": 22320, "text": "Inorder Traversal of the original tree \n 1 10 3 6 7 2 12\nInorder Traversal of the fixed tree \n 1 2 3 6 7 10 12" }, { "code": null, "e": 22504, "s": 22445, "text": "Time Complexity: O(n) Auxiliary Space: O(n) for call stack" }, { "code": null, "e": 23417, "s": 22504, "text": "Two nodes of a BST are swapped, correct the BST | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersTwo nodes of a BST are swapped, correct the BST | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 14:06β€’Liveβ€’<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=wYaq3U7Mqyg\" 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": 23430, "s": 23417, "text": "rajutkarshai" }, { "code": null, "e": 23444, "s": 23430, "text": "GauravRajput1" }, { "code": null, "e": 23456, "s": 23444, "text": "aashish1995" }, { "code": null, "e": 23465, "s": 23456, "text": "gabaa406" }, { "code": null, "e": 23479, "s": 23465, "text": "sumitgumber28" }, { "code": null, "e": 23498, "s": 23479, "text": "shivanisinghss2110" }, { "code": null, "e": 23513, "s": 23498, "text": "adnanirshad158" }, { "code": null, "e": 23529, "s": 23513, "text": "saurabh1990aror" }, { "code": null, "e": 23546, "s": 23529, "text": "arorakashish0911" }, { "code": null, "e": 23558, "s": 23546, "text": "polymatir3j" }, { "code": null, "e": 23575, "s": 23558, "text": "hardikkoriintern" }, { "code": null, "e": 23582, "s": 23575, "text": "Amazon" }, { "code": null, "e": 23593, "s": 23582, "text": "BankBazaar" }, { "code": null, "e": 23601, "s": 23593, "text": "FactSet" }, { "code": null, "e": 23611, "s": 23601, "text": "Microsoft" }, { "code": null, "e": 23630, "s": 23611, "text": "Binary Search Tree" }, { "code": null, "e": 23637, "s": 23630, "text": "Amazon" }, { "code": null, "e": 23647, "s": 23637, "text": "Microsoft" }, { "code": null, "e": 23655, "s": 23647, "text": "FactSet" }, { "code": null, "e": 23666, "s": 23655, "text": "BankBazaar" }, { "code": null, "e": 23685, "s": 23666, "text": "Binary Search Tree" }, { "code": null, "e": 23783, "s": 23685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23833, "s": 23783, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 23889, "s": 23833, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 23959, "s": 23889, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 23994, "s": 23959, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 24023, "s": 23994, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 24063, "s": 24023, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 24100, "s": 24063, "text": "Convert a normal BST to Balanced BST" }, { "code": null, "e": 24132, "s": 24100, "text": "set vs unordered_set in C++ STL" }, { "code": null, "e": 24192, "s": 24132, "text": "Find k-th smallest element in BST (Order Statistics in BST)" } ]
How to read numbers in CSV files in Python?
12 Dec, 2021 Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file, and they cannot save cells, columns, or rows. Also, we cannot save formulas in this format. To parse CSV files in Python, we make use of the csv library. The CSV library contains objects that are used to read, write and process data from and to CSV files. Let’s see how we can add numbers into our CSV files using csv library. Create a python file (example: gfg.py).Import the csv library.Create a nested-list β€˜marks’ which stores the student roll numbers and their marks in maths and python in a tabular format.Open a new csv file (or an existing csv file) in the β€˜w’ mode of the writer object and other necessary parameters (here delimiter & quoting).Write into it the list β€˜marks’ with the help of writerows method.In order to read the rows, make use of reader object and store each row(which is also a list) in a new list β€˜output’.Print the list output for verifying the code. Create a python file (example: gfg.py). Import the csv library. Create a nested-list β€˜marks’ which stores the student roll numbers and their marks in maths and python in a tabular format. Open a new csv file (or an existing csv file) in the β€˜w’ mode of the writer object and other necessary parameters (here delimiter & quoting). Write into it the list β€˜marks’ with the help of writerows method. In order to read the rows, make use of reader object and store each row(which is also a list) in a new list β€˜output’. Print the list output for verifying the code. In order to write in our CSV file β€˜my_csv’, we make use of the writerows() method of the writer object. But to read numbers as they are, we will make use of an optional parameter of the writer object, which is β€˜quoting’. The β€˜quoting’ parameter tells the writer which character is to be quoted. If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields which contain text data and convert all numeric fields to the float data type. Code: Python3 import csv # creating a nested list of roll numbers,# subjects and marks scored by each roll numbermarks = [ ["RollNo", "Maths", "Python"], [1000, 80, 85], [2000, 85, 89], [3000, 82, 90], [4000, 83, 98], [5000, 82, 90]] # using the open method with 'w' mode# for creating a new csv file 'my_csv' with .csv extensionwith open('my_csv.csv', 'w', newline = '') as file: writer = csv.writer(file, quoting = csv.QUOTE_NONNUMERIC, delimiter = ' ') writer.writerows(marks) # opening the 'my_csv' file to read its contentswith open('my_csv.csv', newline = '') as file: reader = csv.reader(file, quoting = csv.QUOTE_NONNUMERIC, delimiter = ' ') # storing all the rows in an output list output = [] for row in reader: output.append(row[:]) for rows in output: print(rows) Output: output of gfg.py And this is how it looks in the CSV file β€˜my_csv.csv’ which gets created once we run the above code: my_csv.csv If quoting is set to csv.QUOTE_ALL then .writerow() will quote all fields and the numbers will now be stored in quotes. To read the numbers from each row, we make use of the reader object from CSV library and store all the rows within a list β€˜output’, which we would also print afterward. Code: Python3 import csv # creating a nested list of roll numbers,# subjects and marks scored by each roll numbermarks = [ ["RollNo", "Maths", "Python"], [1000, 80, 85], [2000, 85, 89], [3000, 82, 90], [4000, 83, 98], [5000, 82, 90]] # using the open method with 'w' mode# for creating a new csv file 'my_csv' with .csv extensionwith open('my_csv.csv', 'w', newline = '') as file: writer = csv.writer(file, quoting = csv.QUOTE_ALL, delimiter = ' ') writer.writerows(marks) # opening the 'my_csv' file to read its contentswith open('my_csv.csv', newline = '') as file: reader = csv.reader(file, quoting = csv.QUOTE_ALL, delimiter = ' ') # storing all the rows in an output list output = [] for row in reader: output.append(row[:]) for rows in output: print(rows) Output: output of gfg.py And this how the above input gets stored within β€˜my_csv.csv’ file: my_csv.csv saurabh1990aror Picked python-csv Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Dec, 2021" }, { "code": null, "e": 96, "s": 28, "text": "Prerequisites: Reading and Writing data in CSV, Creating CSV files " }, { "code": null, "e": 473, "s": 96, "text": "CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file, and they cannot save cells, columns, or rows. Also, we cannot save formulas in this format." }, { "code": null, "e": 708, "s": 473, "text": "To parse CSV files in Python, we make use of the csv library. The CSV library contains objects that are used to read, write and process data from and to CSV files. Let’s see how we can add numbers into our CSV files using csv library." }, { "code": null, "e": 1262, "s": 708, "text": "Create a python file (example: gfg.py).Import the csv library.Create a nested-list β€˜marks’ which stores the student roll numbers and their marks in maths and python in a tabular format.Open a new csv file (or an existing csv file) in the β€˜w’ mode of the writer object and other necessary parameters (here delimiter & quoting).Write into it the list β€˜marks’ with the help of writerows method.In order to read the rows, make use of reader object and store each row(which is also a list) in a new list β€˜output’.Print the list output for verifying the code." }, { "code": null, "e": 1302, "s": 1262, "text": "Create a python file (example: gfg.py)." }, { "code": null, "e": 1326, "s": 1302, "text": "Import the csv library." }, { "code": null, "e": 1450, "s": 1326, "text": "Create a nested-list β€˜marks’ which stores the student roll numbers and their marks in maths and python in a tabular format." }, { "code": null, "e": 1592, "s": 1450, "text": "Open a new csv file (or an existing csv file) in the β€˜w’ mode of the writer object and other necessary parameters (here delimiter & quoting)." }, { "code": null, "e": 1658, "s": 1592, "text": "Write into it the list β€˜marks’ with the help of writerows method." }, { "code": null, "e": 1776, "s": 1658, "text": "In order to read the rows, make use of reader object and store each row(which is also a list) in a new list β€˜output’." }, { "code": null, "e": 1822, "s": 1776, "text": "Print the list output for verifying the code." }, { "code": null, "e": 2118, "s": 1822, "text": "In order to write in our CSV file β€˜my_csv’, we make use of the writerows() method of the writer object. But to read numbers as they are, we will make use of an optional parameter of the writer object, which is β€˜quoting’. The β€˜quoting’ parameter tells the writer which character is to be quoted." }, { "code": null, "e": 2279, "s": 2118, "text": "If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields which contain text data and convert all numeric fields to the float data type." }, { "code": null, "e": 2285, "s": 2279, "text": "Code:" }, { "code": null, "e": 2293, "s": 2285, "text": "Python3" }, { "code": "import csv # creating a nested list of roll numbers,# subjects and marks scored by each roll numbermarks = [ [\"RollNo\", \"Maths\", \"Python\"], [1000, 80, 85], [2000, 85, 89], [3000, 82, 90], [4000, 83, 98], [5000, 82, 90]] # using the open method with 'w' mode# for creating a new csv file 'my_csv' with .csv extensionwith open('my_csv.csv', 'w', newline = '') as file: writer = csv.writer(file, quoting = csv.QUOTE_NONNUMERIC, delimiter = ' ') writer.writerows(marks) # opening the 'my_csv' file to read its contentswith open('my_csv.csv', newline = '') as file: reader = csv.reader(file, quoting = csv.QUOTE_NONNUMERIC, delimiter = ' ') # storing all the rows in an output list output = [] for row in reader: output.append(row[:]) for rows in output: print(rows)", "e": 3155, "s": 2293, "text": null }, { "code": null, "e": 3163, "s": 3155, "text": "Output:" }, { "code": null, "e": 3180, "s": 3163, "text": "output of gfg.py" }, { "code": null, "e": 3281, "s": 3180, "text": "And this is how it looks in the CSV file β€˜my_csv.csv’ which gets created once we run the above code:" }, { "code": null, "e": 3292, "s": 3281, "text": "my_csv.csv" }, { "code": null, "e": 3581, "s": 3292, "text": "If quoting is set to csv.QUOTE_ALL then .writerow() will quote all fields and the numbers will now be stored in quotes. To read the numbers from each row, we make use of the reader object from CSV library and store all the rows within a list β€˜output’, which we would also print afterward." }, { "code": null, "e": 3587, "s": 3581, "text": "Code:" }, { "code": null, "e": 3595, "s": 3587, "text": "Python3" }, { "code": "import csv # creating a nested list of roll numbers,# subjects and marks scored by each roll numbermarks = [ [\"RollNo\", \"Maths\", \"Python\"], [1000, 80, 85], [2000, 85, 89], [3000, 82, 90], [4000, 83, 98], [5000, 82, 90]] # using the open method with 'w' mode# for creating a new csv file 'my_csv' with .csv extensionwith open('my_csv.csv', 'w', newline = '') as file: writer = csv.writer(file, quoting = csv.QUOTE_ALL, delimiter = ' ') writer.writerows(marks) # opening the 'my_csv' file to read its contentswith open('my_csv.csv', newline = '') as file: reader = csv.reader(file, quoting = csv.QUOTE_ALL, delimiter = ' ') # storing all the rows in an output list output = [] for row in reader: output.append(row[:]) for rows in output: print(rows)", "e": 4463, "s": 3595, "text": null }, { "code": null, "e": 4472, "s": 4463, "text": " Output:" }, { "code": null, "e": 4489, "s": 4472, "text": "output of gfg.py" }, { "code": null, "e": 4556, "s": 4489, "text": "And this how the above input gets stored within β€˜my_csv.csv’ file:" }, { "code": null, "e": 4567, "s": 4556, "text": "my_csv.csv" }, { "code": null, "e": 4583, "s": 4567, "text": "saurabh1990aror" }, { "code": null, "e": 4590, "s": 4583, "text": "Picked" }, { "code": null, "e": 4601, "s": 4590, "text": "python-csv" }, { "code": null, "e": 4625, "s": 4601, "text": "Technical Scripter 2020" }, { "code": null, "e": 4632, "s": 4625, "text": "Python" }, { "code": null, "e": 4651, "s": 4632, "text": "Technical Scripter" }, { "code": null, "e": 4749, "s": 4651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4781, "s": 4749, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4808, "s": 4781, "text": "Python Classes and Objects" }, { "code": null, "e": 4829, "s": 4808, "text": "Python OOPs Concepts" }, { "code": null, "e": 4852, "s": 4829, "text": "Introduction To PYTHON" }, { "code": null, "e": 4908, "s": 4852, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4939, "s": 4908, "text": "Python | os.path.join() method" }, { "code": null, "e": 4981, "s": 4939, "text": "Check if element exists in list in Python" }, { "code": null, "e": 5023, "s": 4981, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 5062, "s": 5023, "text": "Python | Get unique values from a list" } ]
B*-Trees implementation in C++
30 Jul, 2019 B*-tree of order m is a search tree that is either empty or that satisfies three properties: The root node has minimum two and maximum 2 floor ((2m-2)/3) +1 children Other internal nodes have the minimum floor ((2m-1)/3) and maximum m children All external nodes are on the same level. The advantage of using B* trees over B-trees is a unique feature called the β€˜two-to-three’ split. By this, the minimum number of keys in each node is not half the maximum number, but two-thirds of it, making data far more compact. However, the disadvantage of this is a complex deletion operation. The difficulties in practically implementing a B-star algorithm contribute to why it’s not as regularly used as its B and B+ counterparts.Below is a basic implementation of the B-star insertion function – just to demonstrate its contrast from B (full implementation would be far more lengthy and complex). The unique parts of the algorithm for B* Tree insertion are as follows: Two-Three Split 1. If inserting into a full leaf node (which is not the root) and which has a full right sibling (and whose parent has at least one free key): Take an array (β€˜marray’) consisting of β€˜m-1’ keys of the full leaf-node, the parent key of this node, the new key to be inserted, and the β€˜m-1’ keys of its right sibling (Totally m-1 + 1 + 1 + m-1 = 2m keys) Sort these keys Create three new nodes:p – whose keys are the first (2m – 2)/3 elements of β€˜marray’The element at index (2m – 2)/3 is stored as β€˜parent1’q – whose keys are the next (2m – 1)/3 elements of β€˜marray’ after parent1The element at index (4m)/3 is stored as β€˜parent2’r – whose keys are the last (2m)/3 elements of β€˜marray’ after parent2 p – whose keys are the first (2m – 2)/3 elements of β€˜marray’The element at index (2m – 2)/3 is stored as β€˜parent1’ q – whose keys are the next (2m – 1)/3 elements of β€˜marray’ after parent1The element at index (4m)/3 is stored as β€˜parent2’ r – whose keys are the last (2m)/3 elements of β€˜marray’ after parent2 The key in the leaf’s parent which points to this leaf should have its value replaced as β€˜parent1’ If the parent key in iv) has any adjacent keys, they should be shifted to the right. In the space that remains, place β€˜parent2’. p, q and r must be made child keys of parent1 and parent2 (if β€˜parent1’ and β€˜parent2’ are the first two keys in the parent node), else p, q, r must be made the child keys of the key before parent 1, parent 1, and parent 2 respectively. Before Insertion : After insertion: 2. If inserting into a full leaf node (which is not the root) with empty/non-full right sibling. Simply shift the last element of the current node to the position of the parent, shift all the keys in the right sibling to the right, and insert the previous parent. Now, use the gap in your own node to rearrange and fit in the new key. 3. The other cases are the same as for B-Trees. Examples: Input: Add 4 to 1 2 3 L 5 R 7 8 9Output: 1 2 L 3 7 R 4 5 R 8 93 and 7 become the parent keys by the two-three split Input : Add 5 to 2 3 4 L 6 R 8 9 11Output : 2 3 L 4 8 R 5 6 R 9 113 and 6 become the parent keys by the two-three split Below is the implementation of the above approach : // CPP program to implement B* tree#include <bits/stdc++.h>using namespace std; // This can be changed to any value - // it is the order of the B* Tree#define N 4 struct node { // key of N-1 nodes int key[N - 1]; // Child array of 'N' length struct node* child[N]; // To state whether a leaf or not; if node // is a leaf, isleaf=1 else isleaf=0 int isleaf; // Counts the number of filled keys in a node int n; // Keeps track of the parent node struct node* parent;}; // This function searches for the leaf // into which to insert element 'k'struct node* searchforleaf(struct node* root, int k, struct node* parent, int chindex){ if (root) { // If the passed root is a leaf node, then // k can be inserted in this node itself if (root->isleaf == 1) return root; // If the passed root is not a leaf node, // implying there are one or more children else { int i; /*If passed root's initial key is itself g reater than the element to be inserted, we need to insert to a new leaf left of the root*/ if (k < root->key[0]) root = searchforleaf(root->child[0], k, root, 0); else { // Find the first key whose value is greater // than the insertion value // and insert into child of that key for (i = 0; i < root->n; i++) if (root->key[i] > k) root = searchforleaf(root->child[i], k, root, i); // If all the keys are less than the insertion // key value, insert to the right of last key if (root->key[i - 1] < k) root = searchforleaf(root->child[i], k, root, i); } } } else { // If the passed root is NULL (there is no such // child node to search), then create a new leaf // node in that location struct node* newleaf = new struct node; newleaf->isleaf = 1; newleaf->n = 0; parent->child[chindex] = newleaf; newleaf->parent = parent; return newleaf; }} struct node* insert(struct node* root, int k){ if (root) { struct node* p = searchforleaf(root, k, NULL, 0); struct node* q = NULL; int e = k; // If the leaf node is empty, simply // add the element and return for (int e = k; p; p = p->parent) { if (p->n == 0) { p->key[0] = e; p->n = 1; return root; } // If number of filled keys is less than maximum if (p->n < N - 1) { int i; for (i = 0; i < p->n; i++) { if (p->key[i] > e) { for (int j = p->n - 1; j >= i; j--) p->key[j + 1] = p->key[j]; break; } } p->key[i] = e; p->n = p->n + 1; return root; } // If number of filled keys is equal to maximum // and it's not root and there is space in the parent if (p->n == N - 1 && p->parent && p->parent->n < N) { int m; for (int i = 0; i < p->parent->n; i++) if (p->parent->child[i] == p) { m = i; break; } // If right sibling is possible if (m + 1 <= N - 1) { // q is the right sibling q = p->parent->child[m + 1]; if (q) { // If right sibling is full if (q->n == N - 1) { struct node* r = new struct node; int* z = new int[((2 * N) / 3)]; int parent1, parent2; int* marray = new int[2 * N]; int i; for (i = 0; i < p->n; i++) marray[i] = p->key[i]; int fege = i; marray[i] = e; marray[i + 1] = p->parent->key[m]; for (int j = i + 2; j < ((i + 2) + (q->n)); j++) marray[j] = q->key[j - (i + 2)]; // marray=bubblesort(marray, 2*N) // a more rigorous implementation will // sort these elements // Put first (2*N-2)/3 elements into keys of p for (int i = 0; i < (2 * N - 2) / 3; i++) p->key[i] = marray[i]; parent1 = marray[(2 * N - 2) / 3]; // Put next (2*N-1)/3 elements into keys of q for (int j = ((2 * N - 2) / 3) + 1; j < (4 * N) / 3; j++) q->key[j - ((2 * N - 2) / 3 + 1)] = marray[j]; parent2 = marray[(4 * N) / 3]; // Put last (2*N)/3 elements into keys of r for (int f = ((4 * N) / 3 + 1); f < 2 * N; f++) r->key[f - ((4 * N) / 3 + 1)] = marray[f]; // Because m=0 and m=1 are children of the same key, // a special case is made for them if (m == 0 || m == 1) { p->parent->key[0] = parent1; p->parent->key[1] = parent2; p->parent->child[0] = p; p->parent->child[1] = q; p->parent->child[2] = r; return root; } else { p->parent->key[m - 1] = parent1; p->parent->key[m] = parent2; p->parent->child[m - 1] = p; p->parent->child[m] = q; p->parent->child[m + 1] = r; return root; } } } else // If right sibling is not full { int put; if (m == 0 || m == 1) put = p->parent->key[0]; else put = p->parent->key[m - 1]; for (int j = (q->n) - 1; j >= 1; j--) q->key[j + 1] = q->key[j]; q->key[0] = put; p->parent->key[m == 0 ? m : m - 1] = p->key[p->n - 1]; } } } } /*Cases of root splitting, etc. are omitted as this implementation is just to demonstrate the two-three split operation*/ } else { // Create new node if root is NULL struct node* root = new struct node; root->key[0] = k; root->isleaf = 1; root->n = 1; root->parent = NULL; }} // Driver codeint main(){ /* Consider the following tree that has been obtained from some root split: 6 / \ 1 2 4 7 8 9 We wish to add 5. This makes the B*-tree: 4 7 / \ \ 1 2 5 6 8 9 Contrast this with the equivalent B-tree, in which some nodes are less than half full 4 6 / \ \ 1 2 5 7 8 9 */ // Start with an empty root struct node* root = NULL; // Insert 6 root = insert(root, 6); // Insert 1, 2, 4 to the left of 6 root->child[0] = insert(root->child[0], 1); root->child[0] = insert(root->child[0], 2); root->child[0] = insert(root->child[0], 4); root->child[0]->parent = root; // Insert 7, 8, 9 to the right of 6 root->child[1] = insert(root->child[1], 7); root->child[1] = insert(root->child[1], 8); root->child[1] = insert(root->child[1], 9); root->child[1]->parent = root; cout << "Original tree: " << endl; for (int i = 0; i < root->n; i++) cout << root->key[i] << " "; cout << endl; for (int i = 0; i < 2; i++) { cout << root->child[i]->key[0] << " "; cout << root->child[i]->key[1] << " "; cout << root->child[i]->key[2] << " "; } cout << endl; cout << "After adding 5: " << endl; // Inserting element '5': root->child[0] = insert(root->child[0], 5); // Printing nodes for (int i = 0; i <= root->n; i++) cout << root->key[i] << " "; cout << endl; for (int i = 0; i < N - 1; i++) { cout << root->child[i]->key[0] << " "; cout << root->child[i]->key[1] << " "; } return 0;} Output: Original Tree: 6 1 2 4 7 8 9 After adding 5: 4 7 1 2 5 6 8 9 Advanced Data Structure DBMS Tree Tree DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of strings whose prefix match with the given string to a given length k Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree) Segment Tree | Set 2 (Range Minimum Query) 2-3 Trees | (Search, Insert and Deletion) Extendible Hashing (Dynamic approach to DBMS) SQL | Join (Inner, Left, Right and Full Joins) ACID Properties in DBMS SQL | WITH clause SQL query to find second highest salary? Normal Forms in DBMS
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Jul, 2019" }, { "code": null, "e": 147, "s": 54, "text": "B*-tree of order m is a search tree that is either empty or that satisfies three properties:" }, { "code": null, "e": 220, "s": 147, "text": "The root node has minimum two and maximum 2 floor ((2m-2)/3) +1 children" }, { "code": null, "e": 298, "s": 220, "text": "Other internal nodes have the minimum floor ((2m-1)/3) and maximum m children" }, { "code": null, "e": 340, "s": 298, "text": "All external nodes are on the same level." }, { "code": null, "e": 638, "s": 340, "text": "The advantage of using B* trees over B-trees is a unique feature called the β€˜two-to-three’ split. By this, the minimum number of keys in each node is not half the maximum number, but two-thirds of it, making data far more compact. However, the disadvantage of this is a complex deletion operation." }, { "code": null, "e": 944, "s": 638, "text": "The difficulties in practically implementing a B-star algorithm contribute to why it’s not as regularly used as its B and B+ counterparts.Below is a basic implementation of the B-star insertion function – just to demonstrate its contrast from B (full implementation would be far more lengthy and complex)." }, { "code": null, "e": 1016, "s": 944, "text": "The unique parts of the algorithm for B* Tree insertion are as follows:" }, { "code": null, "e": 1032, "s": 1016, "text": "Two-Three Split" }, { "code": null, "e": 1175, "s": 1032, "text": "1. If inserting into a full leaf node (which is not the root) and which has a full right sibling (and whose parent has at least one free key):" }, { "code": null, "e": 1383, "s": 1175, "text": "Take an array (β€˜marray’) consisting of β€˜m-1’ keys of the full leaf-node, the parent key of this node, the new key to be inserted, and the β€˜m-1’ keys of its right sibling (Totally m-1 + 1 + 1 + m-1 = 2m keys)" }, { "code": null, "e": 1399, "s": 1383, "text": "Sort these keys" }, { "code": null, "e": 1729, "s": 1399, "text": "Create three new nodes:p – whose keys are the first (2m – 2)/3 elements of β€˜marray’The element at index (2m – 2)/3 is stored as β€˜parent1’q – whose keys are the next (2m – 1)/3 elements of β€˜marray’ after parent1The element at index (4m)/3 is stored as β€˜parent2’r – whose keys are the last (2m)/3 elements of β€˜marray’ after parent2" }, { "code": null, "e": 1844, "s": 1729, "text": "p – whose keys are the first (2m – 2)/3 elements of β€˜marray’The element at index (2m – 2)/3 is stored as β€˜parent1’" }, { "code": null, "e": 1968, "s": 1844, "text": "q – whose keys are the next (2m – 1)/3 elements of β€˜marray’ after parent1The element at index (4m)/3 is stored as β€˜parent2’" }, { "code": null, "e": 2038, "s": 1968, "text": "r – whose keys are the last (2m)/3 elements of β€˜marray’ after parent2" }, { "code": null, "e": 2137, "s": 2038, "text": "The key in the leaf’s parent which points to this leaf should have its value replaced as β€˜parent1’" }, { "code": null, "e": 2266, "s": 2137, "text": "If the parent key in iv) has any adjacent keys, they should be shifted to the right. In the space that remains, place β€˜parent2’." }, { "code": null, "e": 2502, "s": 2266, "text": "p, q and r must be made child keys of parent1 and parent2 (if β€˜parent1’ and β€˜parent2’ are the first two keys in the parent node), else p, q, r must be made the child keys of the key before parent 1, parent 1, and parent 2 respectively." }, { "code": null, "e": 2521, "s": 2502, "text": "Before Insertion :" }, { "code": null, "e": 2538, "s": 2521, "text": "After insertion:" }, { "code": null, "e": 2635, "s": 2538, "text": "2. If inserting into a full leaf node (which is not the root) with empty/non-full right sibling." }, { "code": null, "e": 2873, "s": 2635, "text": "Simply shift the last element of the current node to the position of the parent, shift all the keys in the right sibling to the right, and insert the previous parent. Now, use the gap in your own node to rearrange and fit in the new key." }, { "code": null, "e": 2921, "s": 2873, "text": "3. The other cases are the same as for B-Trees." }, { "code": null, "e": 2931, "s": 2921, "text": "Examples:" }, { "code": null, "e": 3047, "s": 2931, "text": "Input: Add 4 to 1 2 3 L 5 R 7 8 9Output: 1 2 L 3 7 R 4 5 R 8 93 and 7 become the parent keys by the two-three split" }, { "code": null, "e": 3167, "s": 3047, "text": "Input : Add 5 to 2 3 4 L 6 R 8 9 11Output : 2 3 L 4 8 R 5 6 R 9 113 and 6 become the parent keys by the two-three split" }, { "code": null, "e": 3219, "s": 3167, "text": "Below is the implementation of the above approach :" }, { "code": "// CPP program to implement B* tree#include <bits/stdc++.h>using namespace std; // This can be changed to any value - // it is the order of the B* Tree#define N 4 struct node { // key of N-1 nodes int key[N - 1]; // Child array of 'N' length struct node* child[N]; // To state whether a leaf or not; if node // is a leaf, isleaf=1 else isleaf=0 int isleaf; // Counts the number of filled keys in a node int n; // Keeps track of the parent node struct node* parent;}; // This function searches for the leaf // into which to insert element 'k'struct node* searchforleaf(struct node* root, int k, struct node* parent, int chindex){ if (root) { // If the passed root is a leaf node, then // k can be inserted in this node itself if (root->isleaf == 1) return root; // If the passed root is not a leaf node, // implying there are one or more children else { int i; /*If passed root's initial key is itself g reater than the element to be inserted, we need to insert to a new leaf left of the root*/ if (k < root->key[0]) root = searchforleaf(root->child[0], k, root, 0); else { // Find the first key whose value is greater // than the insertion value // and insert into child of that key for (i = 0; i < root->n; i++) if (root->key[i] > k) root = searchforleaf(root->child[i], k, root, i); // If all the keys are less than the insertion // key value, insert to the right of last key if (root->key[i - 1] < k) root = searchforleaf(root->child[i], k, root, i); } } } else { // If the passed root is NULL (there is no such // child node to search), then create a new leaf // node in that location struct node* newleaf = new struct node; newleaf->isleaf = 1; newleaf->n = 0; parent->child[chindex] = newleaf; newleaf->parent = parent; return newleaf; }} struct node* insert(struct node* root, int k){ if (root) { struct node* p = searchforleaf(root, k, NULL, 0); struct node* q = NULL; int e = k; // If the leaf node is empty, simply // add the element and return for (int e = k; p; p = p->parent) { if (p->n == 0) { p->key[0] = e; p->n = 1; return root; } // If number of filled keys is less than maximum if (p->n < N - 1) { int i; for (i = 0; i < p->n; i++) { if (p->key[i] > e) { for (int j = p->n - 1; j >= i; j--) p->key[j + 1] = p->key[j]; break; } } p->key[i] = e; p->n = p->n + 1; return root; } // If number of filled keys is equal to maximum // and it's not root and there is space in the parent if (p->n == N - 1 && p->parent && p->parent->n < N) { int m; for (int i = 0; i < p->parent->n; i++) if (p->parent->child[i] == p) { m = i; break; } // If right sibling is possible if (m + 1 <= N - 1) { // q is the right sibling q = p->parent->child[m + 1]; if (q) { // If right sibling is full if (q->n == N - 1) { struct node* r = new struct node; int* z = new int[((2 * N) / 3)]; int parent1, parent2; int* marray = new int[2 * N]; int i; for (i = 0; i < p->n; i++) marray[i] = p->key[i]; int fege = i; marray[i] = e; marray[i + 1] = p->parent->key[m]; for (int j = i + 2; j < ((i + 2) + (q->n)); j++) marray[j] = q->key[j - (i + 2)]; // marray=bubblesort(marray, 2*N) // a more rigorous implementation will // sort these elements // Put first (2*N-2)/3 elements into keys of p for (int i = 0; i < (2 * N - 2) / 3; i++) p->key[i] = marray[i]; parent1 = marray[(2 * N - 2) / 3]; // Put next (2*N-1)/3 elements into keys of q for (int j = ((2 * N - 2) / 3) + 1; j < (4 * N) / 3; j++) q->key[j - ((2 * N - 2) / 3 + 1)] = marray[j]; parent2 = marray[(4 * N) / 3]; // Put last (2*N)/3 elements into keys of r for (int f = ((4 * N) / 3 + 1); f < 2 * N; f++) r->key[f - ((4 * N) / 3 + 1)] = marray[f]; // Because m=0 and m=1 are children of the same key, // a special case is made for them if (m == 0 || m == 1) { p->parent->key[0] = parent1; p->parent->key[1] = parent2; p->parent->child[0] = p; p->parent->child[1] = q; p->parent->child[2] = r; return root; } else { p->parent->key[m - 1] = parent1; p->parent->key[m] = parent2; p->parent->child[m - 1] = p; p->parent->child[m] = q; p->parent->child[m + 1] = r; return root; } } } else // If right sibling is not full { int put; if (m == 0 || m == 1) put = p->parent->key[0]; else put = p->parent->key[m - 1]; for (int j = (q->n) - 1; j >= 1; j--) q->key[j + 1] = q->key[j]; q->key[0] = put; p->parent->key[m == 0 ? m : m - 1] = p->key[p->n - 1]; } } } } /*Cases of root splitting, etc. are omitted as this implementation is just to demonstrate the two-three split operation*/ } else { // Create new node if root is NULL struct node* root = new struct node; root->key[0] = k; root->isleaf = 1; root->n = 1; root->parent = NULL; }} // Driver codeint main(){ /* Consider the following tree that has been obtained from some root split: 6 / \\ 1 2 4 7 8 9 We wish to add 5. This makes the B*-tree: 4 7 / \\ \\ 1 2 5 6 8 9 Contrast this with the equivalent B-tree, in which some nodes are less than half full 4 6 / \\ \\ 1 2 5 7 8 9 */ // Start with an empty root struct node* root = NULL; // Insert 6 root = insert(root, 6); // Insert 1, 2, 4 to the left of 6 root->child[0] = insert(root->child[0], 1); root->child[0] = insert(root->child[0], 2); root->child[0] = insert(root->child[0], 4); root->child[0]->parent = root; // Insert 7, 8, 9 to the right of 6 root->child[1] = insert(root->child[1], 7); root->child[1] = insert(root->child[1], 8); root->child[1] = insert(root->child[1], 9); root->child[1]->parent = root; cout << \"Original tree: \" << endl; for (int i = 0; i < root->n; i++) cout << root->key[i] << \" \"; cout << endl; for (int i = 0; i < 2; i++) { cout << root->child[i]->key[0] << \" \"; cout << root->child[i]->key[1] << \" \"; cout << root->child[i]->key[2] << \" \"; } cout << endl; cout << \"After adding 5: \" << endl; // Inserting element '5': root->child[0] = insert(root->child[0], 5); // Printing nodes for (int i = 0; i <= root->n; i++) cout << root->key[i] << \" \"; cout << endl; for (int i = 0; i < N - 1; i++) { cout << root->child[i]->key[0] << \" \"; cout << root->child[i]->key[1] << \" \"; } return 0;}", "e": 12695, "s": 3219, "text": null }, { "code": null, "e": 12703, "s": 12695, "text": "Output:" }, { "code": null, "e": 12765, "s": 12703, "text": "Original Tree:\n6\n1 2 4 7 8 9\nAfter adding 5:\n4 7\n1 2 5 6 8 9\n" }, { "code": null, "e": 12789, "s": 12765, "text": "Advanced Data Structure" }, { "code": null, "e": 12794, "s": 12789, "text": "DBMS" }, { "code": null, "e": 12799, "s": 12794, "text": "Tree" }, { "code": null, "e": 12804, "s": 12799, "text": "Tree" }, { "code": null, "e": 12809, "s": 12804, "text": "DBMS" }, { "code": null, "e": 12907, "s": 12809, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12985, "s": 12907, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 13065, "s": 12985, "text": "Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)" }, { "code": null, "e": 13108, "s": 13065, "text": "Segment Tree | Set 2 (Range Minimum Query)" }, { "code": null, "e": 13150, "s": 13108, "text": "2-3 Trees | (Search, Insert and Deletion)" }, { "code": null, "e": 13196, "s": 13150, "text": "Extendible Hashing (Dynamic approach to DBMS)" }, { "code": null, "e": 13243, "s": 13196, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 13267, "s": 13243, "text": "ACID Properties in DBMS" }, { "code": null, "e": 13285, "s": 13267, "text": "SQL | WITH clause" }, { "code": null, "e": 13326, "s": 13285, "text": "SQL query to find second highest salary?" } ]
Write a program that produces different results in C and C++
29 May, 2017 Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers. There can be many such programs, following are some of them. 1) Character literals are treated differently in C and C++. In C character literals like β€˜a’, β€˜b’, ..etc are treated as integers, while as characters in C++. (See this for details) For example, the following program produces sizeof(int) as output in C, but sizeof(char) in C++. #include<stdio.h>int main(){ printf("%d", sizeof('a')); return 0;} 2) In C, we need to use struct tag whenever we declare a struct variable. In C++, the struct tag is not necessary. For example, let there be a structure for Student. In C, we must use β€˜struct Studentβ€˜ for Student variables. In C++, we can omit struct and use β€˜Studentβ€˜ only.Following is a program that is based on the fact and produces different outputs in C and C++. It prints sizeof(int) in C and sizeof(struct T) in C++. #include <stdio.h>int T; int main(){ struct T { double x; }; // In C++, this T hides the global variable T, // but not in C printf("%d", sizeof(T)); return 0;} 3) Types of boolean results are different in C and C++. Thanks to Gaurav Jain for suggesting this point. // output = 4 in C (which is size of int)printf("%d", sizeof(1==1)); // output = 1 in c++ (which is the size of boolean datatype)cout << sizeof(1==1); This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above cpp-puzzle C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ Vector in C++ STL Initialize a vector in C++ (7 different ways) Templates in C++ with Examples Operator Overloading in C++ Set in C++ Standard Template Library (STL)
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2017" }, { "code": null, "e": 181, "s": 54, "text": "Write a program that compiles and runs both in C and C++, but produces different results when compiled by C and C++ compilers." }, { "code": null, "e": 242, "s": 181, "text": "There can be many such programs, following are some of them." }, { "code": null, "e": 423, "s": 242, "text": "1) Character literals are treated differently in C and C++. In C character literals like β€˜a’, β€˜b’, ..etc are treated as integers, while as characters in C++. (See this for details)" }, { "code": null, "e": 520, "s": 423, "text": "For example, the following program produces sizeof(int) as output in C, but sizeof(char) in C++." }, { "code": "#include<stdio.h>int main(){ printf(\"%d\", sizeof('a')); return 0;}", "e": 589, "s": 520, "text": null }, { "code": null, "e": 1013, "s": 589, "text": "2) In C, we need to use struct tag whenever we declare a struct variable. In C++, the struct tag is not necessary. For example, let there be a structure for Student. In C, we must use β€˜struct Studentβ€˜ for Student variables. In C++, we can omit struct and use β€˜Studentβ€˜ only.Following is a program that is based on the fact and produces different outputs in C and C++. It prints sizeof(int) in C and sizeof(struct T) in C++." }, { "code": "#include <stdio.h>int T; int main(){ struct T { double x; }; // In C++, this T hides the global variable T, // but not in C printf(\"%d\", sizeof(T)); return 0;}", "e": 1213, "s": 1013, "text": null }, { "code": null, "e": 1318, "s": 1213, "text": "3) Types of boolean results are different in C and C++. Thanks to Gaurav Jain for suggesting this point." }, { "code": " // output = 4 in C (which is size of int)printf(\"%d\", sizeof(1==1)); // output = 1 in c++ (which is the size of boolean datatype)cout << sizeof(1==1); ", "e": 1475, "s": 1318, "text": null }, { "code": null, "e": 1643, "s": 1475, "text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 1654, "s": 1643, "text": "cpp-puzzle" }, { "code": null, "e": 1665, "s": 1654, "text": "C Language" }, { "code": null, "e": 1669, "s": 1665, "text": "C++" }, { "code": null, "e": 1673, "s": 1669, "text": "CPP" }, { "code": null, "e": 1771, "s": 1673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1788, "s": 1771, "text": "Substring in C++" }, { "code": null, "e": 1823, "s": 1788, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 1845, "s": 1823, "text": "Function Pointer in C" }, { "code": null, "e": 1891, "s": 1845, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 1936, "s": 1891, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 1954, "s": 1936, "text": "Vector in C++ STL" }, { "code": null, "e": 2000, "s": 1954, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 2031, "s": 2000, "text": "Templates in C++ with Examples" }, { "code": null, "e": 2059, "s": 2031, "text": "Operator Overloading in C++" } ]
Smallest number greater than or equal to N having sum of digits not exceeding S
13 Apr, 2021 Given integer N and integer S, the task is to find the smallest number greater than or equal to N such that the sum of its digits does not exceed S. Examples: Input: N = 3, S = 2Output: 10Explanation: Sum of digits of 10 is 1, which is less than 2. Input: N = 19, S = 3Output: 20Explanation: Sum of digits of 20 is 2, which is less than 3. Approach: The problem can be solved using a greedy approach. Follow the below steps to solve the problem. Check if the sum of digits of N does not exceed S, return N.Initialize a variable, say ans equal to the given integer N and k with 1 to store the powers of 10.There can be at most 10 digits in the integer range.Iterate from i = 0 to 8. At each iteration, calculate the last digit as (ans / k)%10.The sum to make the last digit 0 is k*((10-last_digit)%10). Add it to ans.Check the sum of digits of ans. If it does not exceed S, print ans and break. Otherwise, update k as k = k*10 and repeat the above steps. Check if the sum of digits of N does not exceed S, return N. Initialize a variable, say ans equal to the given integer N and k with 1 to store the powers of 10. There can be at most 10 digits in the integer range. Iterate from i = 0 to 8. At each iteration, calculate the last digit as (ans / k)%10. The sum to make the last digit 0 is k*((10-last_digit)%10). Add it to ans. Check the sum of digits of ans. If it does not exceed S, print ans and break. Otherwise, update k as k = k*10 and repeat the above steps. 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 calculate sum// digits of nint sum(int n){ int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionint smallestNumber(int n, int s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables int ans = n, k = 1; for (int i = 0; i < 9; ++i) { // Finding last kth digit int digit = (ans / k) % 10; // Add remaining to make digit 0 int add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Codeint main(){ // Given N and S int N = 3, S = 2; // Function call cout << smallestNumber(N, S) << endl; return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to calculate sum// digits of nstatic int sum(int n){ int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionstatic int smallestNumber(int n, int s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables int ans = n, k = 1; for(int i = 0; i < 9; ++i) { // Finding last kth digit int digit = (ans / k) % 10; // Add remaining to make digit 0 int add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Codepublic static void main(String[] args){ // Given N and S int N = 3, S = 2; // Function call System.out.println(smallestNumber(N, S));}} // This code is contributed by akhilsaini # Python program for the above approach # Function to calculate# sum of digits of ndef sum(n): sm = 0 while(n > 0): sm += n % 10 n //= 10 return sm # Function to find the smallest# possible integer satisfying the# given conditiondef smallestNumber(n, s): # If sum of digits is# already smaller than s if(sum(n) <= s): return n # Initialize variables ans, k = n, 1 for i in range(9): # Find the k-th digit digit = (ans // k) % 10 # Add remaining add = k * ((10 - digit) % 10) ans += add # If sum of digits# does not exceed s if(sum(ans) <= s): break # Update K k *= 10 # Return answer return ans # Driver Code # Given N and Sn, s = 3, 2 # Function callprint(smallestNumber(n, s)) // C# program for the above approachusing System; class GFG{ // Function to calculate sum// digits of nstatic int sum(int n){ int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionstatic int smallestNumber(int n, int s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables int ans = n, k = 1; for(int i = 0; i < 9; ++i) { // Finding last kth digit int digit = (ans / k) % 10; // Add remaining to make digit 0 int add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Codepublic static void Main(){ // Given N and S int N = 3, S = 2; // Function call Console.WriteLine(smallestNumber(N, S));}} // This code is contributed by akhilsaini <script>// javascript program for the above approach // Function to calculate sum// digits of nfunction sum(n){ var res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionfunction smallestNumber(n , s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables var ans = n, k = 1; for(i = 0; i < 9; ++i) { // Finding last kth digit var digit = (ans / k) % 10; // Add remaining to make digit 0 var add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Code // Given N and Svar N = 3, S = 2; // Function calldocument.write(smallestNumber(N, S)); // This code is contributed by shikhasingrajput.</script> 10 Time Complexity: O(log210(N)) where N is the given integer.Space Complexity: O(1) akhilsaini shikhasingrajput Discrete Mathematics number-digits number-theory Numbers python Greedy Mathematical number-theory Greedy Mathematical Numbers python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree Greedy Algorithm for Egyptian Fraction Huffman Decoding Bin Packing Problem (Minimize number of used Bins) Boruvka's algorithm | Greedy Algo-9 Program for Fibonacci numbers C++ Data Types Set in C++ Standard Template Library (STL) Operators in C / C++ Merge two sorted arrays
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Apr, 2021" }, { "code": null, "e": 177, "s": 28, "text": "Given integer N and integer S, the task is to find the smallest number greater than or equal to N such that the sum of its digits does not exceed S." }, { "code": null, "e": 187, "s": 177, "text": "Examples:" }, { "code": null, "e": 277, "s": 187, "text": "Input: N = 3, S = 2Output: 10Explanation: Sum of digits of 10 is 1, which is less than 2." }, { "code": null, "e": 368, "s": 277, "text": "Input: N = 19, S = 3Output: 20Explanation: Sum of digits of 20 is 2, which is less than 3." }, { "code": null, "e": 474, "s": 368, "text": "Approach: The problem can be solved using a greedy approach. Follow the below steps to solve the problem." }, { "code": null, "e": 982, "s": 474, "text": "Check if the sum of digits of N does not exceed S, return N.Initialize a variable, say ans equal to the given integer N and k with 1 to store the powers of 10.There can be at most 10 digits in the integer range.Iterate from i = 0 to 8. At each iteration, calculate the last digit as (ans / k)%10.The sum to make the last digit 0 is k*((10-last_digit)%10). Add it to ans.Check the sum of digits of ans. If it does not exceed S, print ans and break. Otherwise, update k as k = k*10 and repeat the above steps." }, { "code": null, "e": 1043, "s": 982, "text": "Check if the sum of digits of N does not exceed S, return N." }, { "code": null, "e": 1143, "s": 1043, "text": "Initialize a variable, say ans equal to the given integer N and k with 1 to store the powers of 10." }, { "code": null, "e": 1196, "s": 1143, "text": "There can be at most 10 digits in the integer range." }, { "code": null, "e": 1282, "s": 1196, "text": "Iterate from i = 0 to 8. At each iteration, calculate the last digit as (ans / k)%10." }, { "code": null, "e": 1357, "s": 1282, "text": "The sum to make the last digit 0 is k*((10-last_digit)%10). Add it to ans." }, { "code": null, "e": 1495, "s": 1357, "text": "Check the sum of digits of ans. If it does not exceed S, print ans and break. Otherwise, update k as k = k*10 and repeat the above steps." }, { "code": null, "e": 1546, "s": 1495, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1550, "s": 1546, "text": "C++" }, { "code": null, "e": 1555, "s": 1550, "text": "Java" }, { "code": null, "e": 1563, "s": 1555, "text": "Python3" }, { "code": null, "e": 1566, "s": 1563, "text": "C#" }, { "code": null, "e": 1577, "s": 1566, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate sum// digits of nint sum(int n){ int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionint smallestNumber(int n, int s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables int ans = n, k = 1; for (int i = 0; i < 9; ++i) { // Finding last kth digit int digit = (ans / k) % 10; // Add remaining to make digit 0 int add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Codeint main(){ // Given N and S int N = 3, S = 2; // Function call cout << smallestNumber(N, S) << endl; return 0;}", "e": 2602, "s": 1577, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to calculate sum// digits of nstatic int sum(int n){ int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionstatic int smallestNumber(int n, int s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables int ans = n, k = 1; for(int i = 0; i < 9; ++i) { // Finding last kth digit int digit = (ans / k) % 10; // Add remaining to make digit 0 int add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Codepublic static void main(String[] args){ // Given N and S int N = 3, S = 2; // Function call System.out.println(smallestNumber(N, S));}} // This code is contributed by akhilsaini", "e": 3719, "s": 2602, "text": null }, { "code": "# Python program for the above approach # Function to calculate# sum of digits of ndef sum(n): sm = 0 while(n > 0): sm += n % 10 n //= 10 return sm # Function to find the smallest# possible integer satisfying the# given conditiondef smallestNumber(n, s): # If sum of digits is# already smaller than s if(sum(n) <= s): return n # Initialize variables ans, k = n, 1 for i in range(9): # Find the k-th digit digit = (ans // k) % 10 # Add remaining add = k * ((10 - digit) % 10) ans += add # If sum of digits# does not exceed s if(sum(ans) <= s): break # Update K k *= 10 # Return answer return ans # Driver Code # Given N and Sn, s = 3, 2 # Function callprint(smallestNumber(n, s))", "e": 4488, "s": 3719, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to calculate sum// digits of nstatic int sum(int n){ int res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionstatic int smallestNumber(int n, int s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables int ans = n, k = 1; for(int i = 0; i < 9; ++i) { // Finding last kth digit int digit = (ans / k) % 10; // Add remaining to make digit 0 int add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Codepublic static void Main(){ // Given N and S int N = 3, S = 2; // Function call Console.WriteLine(smallestNumber(N, S));}} // This code is contributed by akhilsaini", "e": 5593, "s": 4488, "text": null }, { "code": "<script>// javascript program for the above approach // Function to calculate sum// digits of nfunction sum(n){ var res = 0; while (n > 0) { res += n % 10; n /= 10; } return res;} // Function to find the smallest// possible integer satisfying the// given conditionfunction smallestNumber(n , s){ // If the sum of digits // is already smaller than S if (sum(n) <= s) { return n; } // Initialize variables var ans = n, k = 1; for(i = 0; i < 9; ++i) { // Finding last kth digit var digit = (ans / k) % 10; // Add remaining to make digit 0 var add = k * ((10 - digit) % 10); ans += add; // If sum of digits // does not exceed S if (sum(ans) <= s) { break; } // Update k k *= 10; } return ans;} // Driver Code // Given N and Svar N = 3, S = 2; // Function calldocument.write(smallestNumber(N, S)); // This code is contributed by shikhasingrajput.</script>", "e": 6628, "s": 5593, "text": null }, { "code": null, "e": 6631, "s": 6628, "text": "10" }, { "code": null, "e": 6715, "s": 6633, "text": "Time Complexity: O(log210(N)) where N is the given integer.Space Complexity: O(1)" }, { "code": null, "e": 6726, "s": 6715, "text": "akhilsaini" }, { "code": null, "e": 6743, "s": 6726, "text": "shikhasingrajput" }, { "code": null, "e": 6764, "s": 6743, "text": "Discrete Mathematics" }, { "code": null, "e": 6778, "s": 6764, "text": "number-digits" }, { "code": null, "e": 6792, "s": 6778, "text": "number-theory" }, { "code": null, "e": 6800, "s": 6792, "text": "Numbers" }, { "code": null, "e": 6807, "s": 6800, "text": "python" }, { "code": null, "e": 6814, "s": 6807, "text": "Greedy" }, { "code": null, "e": 6827, "s": 6814, "text": "Mathematical" }, { "code": null, "e": 6841, "s": 6827, "text": "number-theory" }, { "code": null, "e": 6848, "s": 6841, "text": "Greedy" }, { "code": null, "e": 6861, "s": 6848, "text": "Mathematical" }, { "code": null, "e": 6869, "s": 6861, "text": "Numbers" }, { "code": null, "e": 6876, "s": 6869, "text": "python" }, { "code": null, "e": 6974, "s": 6876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7061, "s": 6974, "text": "Shortest Job First (or SJF) CPU Scheduling Non-preemptive algorithm using Segment Tree" }, { "code": null, "e": 7100, "s": 7061, "text": "Greedy Algorithm for Egyptian Fraction" }, { "code": null, "e": 7117, "s": 7100, "text": "Huffman Decoding" }, { "code": null, "e": 7168, "s": 7117, "text": "Bin Packing Problem (Minimize number of used Bins)" }, { "code": null, "e": 7204, "s": 7168, "text": "Boruvka's algorithm | Greedy Algo-9" }, { "code": null, "e": 7234, "s": 7204, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7249, "s": 7234, "text": "C++ Data Types" }, { "code": null, "e": 7292, "s": 7249, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7313, "s": 7292, "text": "Operators in C / C++" } ]
Python – Get particular Nested level Items from Dictionary
24 Oct, 2020 Given a dictionary, extract items from particular level. Examples: Input : {β€œGfg” : { β€œn1”: 3, β€œnd2”: { β€œn2” : 6 }}, β€œis” : { β€œne1”: 5, β€œndi2”: { β€œne2” : 8, β€œne22” : 10 } }}, K = 2 Output : {β€˜n2’: 6, β€˜ne2’: 8, β€˜ne22’: 10} Explanation : 2nd nesting items are extracted. Input : {β€œGfg” : { β€œn1”: 3, β€œnd2”: { β€œn2” : 6 }}, β€œis” : { β€œne1”: 5, β€œndi2”: { β€œne2” : 8, β€œne22” : 10 } }}, K = 1 Output : {β€œn1”: 3, β€œne1”: 5} Explanation : Elements of 1st nesting extracted. Method : Using isinstance() + recursion This is one of the ways in which this task can be performed. In this, we perform required recursion for inner nestings, and isinstance is used to differentiate between dict instance and other data types to test for nesting. Python3 # Python3 code to demonstrate working of# Get particular Nested level Items from Dictionary# Using isinstance() + recursion # helper function def get_items(test_dict, lvl): # querying for lowest level if lvl == 0: yield from ((key, val) for key, val in test_dict.items() if not isinstance(val, dict)) else: # recur for inner dictionaries yield from ((key1, val1) for val in test_dict.values() if isinstance(val, dict) for key1, val1 in get_items(val, lvl - 1)) # initializing dictionarytest_dict = {"Gfg": { "n1": 3, "nd2": { "n2": 6 }}, "is": { "ne1": 5, "ndi2": { "ne2": 8, "ne22": 10 } }} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing KK = 2 # calling functionres = get_items(test_dict, K) # printing resultprint("Required items : " + str(dict(res))) The original dictionary is : {β€˜Gfg’: {β€˜n1’: 3, β€˜nd2’: {β€˜n2’: 6}}, β€˜is’: {β€˜ne1’: 5, β€˜ndi2’: {β€˜ne2’: 8, β€˜ne22’: 10}}}Required items : {β€˜n2’: 6, β€˜ne2’: 8, β€˜ne22’: 10} Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2020" }, { "code": null, "e": 85, "s": 28, "text": "Given a dictionary, extract items from particular level." }, { "code": null, "e": 95, "s": 85, "text": "Examples:" }, { "code": null, "e": 298, "s": 95, "text": "Input : {β€œGfg” : { β€œn1”: 3, β€œnd2”: { β€œn2” : 6 }}, β€œis” : { β€œne1”: 5, β€œndi2”: { β€œne2” : 8, β€œne22” : 10 } }}, K = 2 Output : {β€˜n2’: 6, β€˜ne2’: 8, β€˜ne22’: 10} Explanation : 2nd nesting items are extracted." }, { "code": null, "e": 491, "s": 298, "text": "Input : {β€œGfg” : { β€œn1”: 3, β€œnd2”: { β€œn2” : 6 }}, β€œis” : { β€œne1”: 5, β€œndi2”: { β€œne2” : 8, β€œne22” : 10 } }}, K = 1 Output : {β€œn1”: 3, β€œne1”: 5} Explanation : Elements of 1st nesting extracted. " }, { "code": null, "e": 531, "s": 491, "text": "Method : Using isinstance() + recursion" }, { "code": null, "e": 755, "s": 531, "text": "This is one of the ways in which this task can be performed. In this, we perform required recursion for inner nestings, and isinstance is used to differentiate between dict instance and other data types to test for nesting." }, { "code": null, "e": 763, "s": 755, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get particular Nested level Items from Dictionary# Using isinstance() + recursion # helper function def get_items(test_dict, lvl): # querying for lowest level if lvl == 0: yield from ((key, val) for key, val in test_dict.items() if not isinstance(val, dict)) else: # recur for inner dictionaries yield from ((key1, val1) for val in test_dict.values() if isinstance(val, dict) for key1, val1 in get_items(val, lvl - 1)) # initializing dictionarytest_dict = {\"Gfg\": { \"n1\": 3, \"nd2\": { \"n2\": 6 }}, \"is\": { \"ne1\": 5, \"ndi2\": { \"ne2\": 8, \"ne22\": 10 } }} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing KK = 2 # calling functionres = get_items(test_dict, K) # printing resultprint(\"Required items : \" + str(dict(res)))", "e": 1668, "s": 763, "text": null }, { "code": null, "e": 1832, "s": 1668, "text": "The original dictionary is : {β€˜Gfg’: {β€˜n1’: 3, β€˜nd2’: {β€˜n2’: 6}}, β€˜is’: {β€˜ne1’: 5, β€˜ndi2’: {β€˜ne2’: 8, β€˜ne22’: 10}}}Required items : {β€˜n2’: 6, β€˜ne2’: 8, β€˜ne22’: 10}" }, { "code": null, "e": 1859, "s": 1832, "text": "Python dictionary-programs" }, { "code": null, "e": 1866, "s": 1859, "text": "Python" }, { "code": null, "e": 1882, "s": 1866, "text": "Python Programs" }, { "code": null, "e": 1980, "s": 1882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2012, "s": 1980, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2039, "s": 2012, "text": "Python Classes and Objects" }, { "code": null, "e": 2060, "s": 2039, "text": "Python OOPs Concepts" }, { "code": null, "e": 2083, "s": 2060, "text": "Introduction To PYTHON" }, { "code": null, "e": 2139, "s": 2083, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2161, "s": 2139, "text": "Defaultdict in Python" }, { "code": null, "e": 2200, "s": 2161, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2238, "s": 2200, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2275, "s": 2238, "text": "Python Program for Fibonacci numbers" } ]
C# | Convert Stack to array
01 Feb, 2019 Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.ToArray Method is used to copy a Stack<T> to a new array. Properties: The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation. Stack accepts null as a valid value and allows duplicate elements. Syntax: public T[] ToArray (); Return Type: This method returns a new array t[] which contains the copy of the elements of the Stack<T>. Below given are some examples to understand the implementation in a better way : Example 1: // C# code to Convert Stack to arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Converting the Stack into array String[] arr = myStack.ToArray(); // Displaying the elements in array foreach(string str in arr) { Console.WriteLine(str); } }} GeeksforGeeks Data Structures Noida Geeks Classes Geeks Example 2: // C# code to Convert Stack to arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // Converting the Stack into array int[] arr = myStack.ToArray(); // Displaying the elements in array foreach(int i in arr) { Console.WriteLine(i); } }} 6 5 4 3 2 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.toarray?view=netframework-4.7.2 CSharp-Generic-Namespace CSharp-Generic-Stack CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Feb, 2019" }, { "code": null, "e": 337, "s": 28, "text": "Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.ToArray Method is used to copy a Stack<T> to a new array." }, { "code": null, "e": 349, "s": 337, "text": "Properties:" }, { "code": null, "e": 527, "s": 349, "text": "The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation." }, { "code": null, "e": 749, "s": 527, "text": "If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation." }, { "code": null, "e": 816, "s": 749, "text": "Stack accepts null as a valid value and allows duplicate elements." }, { "code": null, "e": 824, "s": 816, "text": "Syntax:" }, { "code": null, "e": 848, "s": 824, "text": "public T[] ToArray ();\n" }, { "code": null, "e": 954, "s": 848, "text": "Return Type: This method returns a new array t[] which contains the copy of the elements of the Stack<T>." }, { "code": null, "e": 1035, "s": 954, "text": "Below given are some examples to understand the implementation in a better way :" }, { "code": null, "e": 1046, "s": 1035, "text": "Example 1:" }, { "code": "// C# code to Convert Stack to arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack<string> myStack = new Stack<string>(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // Converting the Stack into array String[] arr = myStack.ToArray(); // Displaying the elements in array foreach(string str in arr) { Console.WriteLine(str); } }}", "e": 1737, "s": 1046, "text": null }, { "code": null, "e": 1794, "s": 1737, "text": "GeeksforGeeks\nData Structures\nNoida\nGeeks Classes\nGeeks\n" }, { "code": null, "e": 1805, "s": 1794, "text": "Example 2:" }, { "code": "// C# code to Convert Stack to arrayusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a Stack of Integers Stack<int> myStack = new Stack<int>(); // Inserting the elements into the Stack myStack.Push(2); myStack.Push(3); myStack.Push(4); myStack.Push(5); myStack.Push(6); // Converting the Stack into array int[] arr = myStack.ToArray(); // Displaying the elements in array foreach(int i in arr) { Console.WriteLine(i); } }}", "e": 2425, "s": 1805, "text": null }, { "code": null, "e": 2436, "s": 2425, "text": "6\n5\n4\n3\n2\n" }, { "code": null, "e": 2447, "s": 2436, "text": "Reference:" }, { "code": null, "e": 2558, "s": 2447, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.toarray?view=netframework-4.7.2" }, { "code": null, "e": 2583, "s": 2558, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 2604, "s": 2583, "text": "CSharp-Generic-Stack" }, { "code": null, "e": 2618, "s": 2604, "text": "CSharp-method" }, { "code": null, "e": 2621, "s": 2618, "text": "C#" } ]
StringJoiner Class in Java
24 Jan, 2022 StringJoiner is a class in java.util package is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a given suffix. Though this can also be done with the help of the StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write. 1. StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no prefix or suffix, and a copy of the supplied delimiter. Syntax: public StringJoiner(CharSequence delimiter) Parameters: The sequence of characters to be used between each element added to the StringJoiner value Exception Thrown: NullPointerException if the delimiter is null 2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and suffix. If no characters are added to the StringJoiner and methods accessing the string value are invoked, it will return the prefix + suffix (or properties thereof) in the result unless setEmptyValue has first been called. Syntax: public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) Parameters: The sequence of characters to be used between each element added to the StringJoiner value The sequence of characters to be used at the beginning The sequence of characters to be used at the end Exception Thrown: NullPointerException if prefix, delimiter, or suffix is null. Example: Java // Java program to Demonstrate Methods// of StringJoiner class // Importing required classesimport java.util.ArrayList;import java.util.StringJoiner; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to above List al.add("Ram"); al.add("Shyam"); al.add("Alice"); al.add("Bob"); // Creating object of class inside main() StringJoiner sj1 = new StringJoiner(","); // Using setEmptyValue() method sj1.setEmptyValue("sj1 is empty"); System.out.println(sj1); // Using add() method sj1.add(al.get(0)).add(al.get(1)); System.out.println(sj1); // Using length() method System.out.println("Length of sj1 : " + sj1.length()); StringJoiner sj2 = new StringJoiner(":"); sj2.add(al.get(2)).add(al.get(3)); // Using merge() method sj1.merge(sj2); // Using toString() method System.out.println(sj1.toString()); System.out.println("Length of new sj1 : " + sj1.length()); }} sj1 is empty Ram,Shyam Length of sj1 : 9 Ram,Shyam,Alice:Bob Length of new sj1 : 19 This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. payal soni romeosaurabh nishkarshgandhi solankimayank Java - util package Java-StringJoiner 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 How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jan, 2022" }, { "code": null, "e": 439, "s": 52, "text": "StringJoiner is a class in java.util package is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a given suffix. Though this can also be done with the help of the StringBuilder class to append delimiter after each string, StringJoiner provides an easy way to do that without much code to write. " }, { "code": null, "e": 589, "s": 439, "text": "1. StringJoiner(CharSequence delimiter): It constructs a StringJoiner with no characters, no prefix or suffix, and a copy of the supplied delimiter. " }, { "code": null, "e": 598, "s": 589, "text": "Syntax: " }, { "code": null, "e": 642, "s": 598, "text": "public StringJoiner(CharSequence delimiter)" }, { "code": null, "e": 745, "s": 642, "text": "Parameters: The sequence of characters to be used between each element added to the StringJoiner value" }, { "code": null, "e": 809, "s": 745, "text": "Exception Thrown: NullPointerException if the delimiter is null" }, { "code": null, "e": 1217, "s": 809, "text": "2. StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix): It constructs a StringJoiner with no characters using copies of the supplied prefix, delimiter, and suffix. If no characters are added to the StringJoiner and methods accessing the string value are invoked, it will return the prefix + suffix (or properties thereof) in the result unless setEmptyValue has first been called. " }, { "code": null, "e": 1226, "s": 1217, "text": "Syntax: " }, { "code": null, "e": 1312, "s": 1226, "text": "public StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)" }, { "code": null, "e": 1325, "s": 1312, "text": "Parameters: " }, { "code": null, "e": 1416, "s": 1325, "text": "The sequence of characters to be used between each element added to the StringJoiner value" }, { "code": null, "e": 1471, "s": 1416, "text": "The sequence of characters to be used at the beginning" }, { "code": null, "e": 1520, "s": 1471, "text": "The sequence of characters to be used at the end" }, { "code": null, "e": 1600, "s": 1520, "text": "Exception Thrown: NullPointerException if prefix, delimiter, or suffix is null." }, { "code": null, "e": 1610, "s": 1600, "text": " Example:" }, { "code": null, "e": 1615, "s": 1610, "text": "Java" }, { "code": "// Java program to Demonstrate Methods// of StringJoiner class // Importing required classesimport java.util.ArrayList;import java.util.StringJoiner; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty ArrayList of string type ArrayList<String> al = new ArrayList<>(); // Adding elements to above List al.add(\"Ram\"); al.add(\"Shyam\"); al.add(\"Alice\"); al.add(\"Bob\"); // Creating object of class inside main() StringJoiner sj1 = new StringJoiner(\",\"); // Using setEmptyValue() method sj1.setEmptyValue(\"sj1 is empty\"); System.out.println(sj1); // Using add() method sj1.add(al.get(0)).add(al.get(1)); System.out.println(sj1); // Using length() method System.out.println(\"Length of sj1 : \" + sj1.length()); StringJoiner sj2 = new StringJoiner(\":\"); sj2.add(al.get(2)).add(al.get(3)); // Using merge() method sj1.merge(sj2); // Using toString() method System.out.println(sj1.toString()); System.out.println(\"Length of new sj1 : \" + sj1.length()); }}", "e": 2867, "s": 1615, "text": null }, { "code": null, "e": 2951, "s": 2867, "text": "sj1 is empty\nRam,Shyam\nLength of sj1 : 9\nRam,Shyam,Alice:Bob\nLength of new sj1 : 19" }, { "code": null, "e": 3375, "s": 2951, "text": " This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3386, "s": 3375, "text": "payal soni" }, { "code": null, "e": 3399, "s": 3386, "text": "romeosaurabh" }, { "code": null, "e": 3415, "s": 3399, "text": "nishkarshgandhi" }, { "code": null, "e": 3429, "s": 3415, "text": "solankimayank" }, { "code": null, "e": 3449, "s": 3429, "text": "Java - util package" }, { "code": null, "e": 3467, "s": 3449, "text": "Java-StringJoiner" }, { "code": null, "e": 3472, "s": 3467, "text": "Java" }, { "code": null, "e": 3477, "s": 3472, "text": "Java" }, { "code": null, "e": 3575, "s": 3477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3626, "s": 3575, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3657, "s": 3626, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3676, "s": 3657, "text": "Interfaces in Java" }, { "code": null, "e": 3706, "s": 3676, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3721, "s": 3706, "text": "Stream In Java" }, { "code": null, "e": 3739, "s": 3721, "text": "ArrayList in Java" }, { "code": null, "e": 3759, "s": 3739, "text": "Collections in Java" }, { "code": null, "e": 3783, "s": 3759, "text": "Singleton Class in Java" }, { "code": null, "e": 3815, "s": 3783, "text": "Multidimensional Arrays in Java" } ]
Python Bokeh – Plotting Line Segments on a Graph
10 Jul, 2020 Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot line segments on a graph. Plotting line segments on a graph can be done using the segment() method of the plotting module. Syntax : segment(parameters) Parameters : x0 : x-coordinates of the starting points of the line segment y0 : y-coordinates of the starting points of the line segment x1 : x-coordinates of the ending points of the line segment y1 : y-coordinates of the ending points of the line segment Returns : an object of class GlyphRenderer Example 1 : In this example we will be using the default values for plotting the graph. # importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Segment Graph") # the points to be plottedx0 = 0y0 = 0x1 = 10y1 = 10 # plotting the graphgraph.segment(x0, y0, x1, y1) # displaying the modelshow(graph) Output : Example 2 : In this example we will be plotting the multiple line segments with various other parameters # importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Segment Graph") # name of the x-axis graph.xaxis.axis_label = "x-axis" # name of the y-axis graph.yaxis.axis_label = "y-axis" # points to be plottedx0 = [0, 0, 5]y0 = [0, 5, 0]x1 = [10, 10, 5]y1 = [10, 5, 10] # color of the linesline_color = ["yellow", "red", "purple"] # value of line dashline_dash = "dotted" # thickness of the linesline_width = [15, 10, 20] # plotting the graph graph.segment(x0, y0, x1, y1, line_color = line_color, line_dash = line_dash, line_width = line_width) # displaying the model show(graph) Output : Data Visualization Python Bokeh-plotting-figure-class Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 269, "s": 28, "text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity." }, { "code": null, "e": 418, "s": 269, "text": "Bokeh can be used to plot line segments on a graph. Plotting line segments on a graph can be done using the segment() method of the plotting module." }, { "code": null, "e": 447, "s": 418, "text": "Syntax : segment(parameters)" }, { "code": null, "e": 460, "s": 447, "text": "Parameters :" }, { "code": null, "e": 522, "s": 460, "text": "x0 : x-coordinates of the starting points of the line segment" }, { "code": null, "e": 584, "s": 522, "text": "y0 : y-coordinates of the starting points of the line segment" }, { "code": null, "e": 644, "s": 584, "text": "x1 : x-coordinates of the ending points of the line segment" }, { "code": null, "e": 704, "s": 644, "text": "y1 : y-coordinates of the ending points of the line segment" }, { "code": null, "e": 747, "s": 704, "text": "Returns : an object of class GlyphRenderer" }, { "code": null, "e": 835, "s": 747, "text": "Example 1 : In this example we will be using the default values for plotting the graph." }, { "code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Segment Graph\") # the points to be plottedx0 = 0y0 = 0x1 = 10y1 = 10 # plotting the graphgraph.segment(x0, y0, x1, y1) # displaying the modelshow(graph)", "e": 1213, "s": 835, "text": null }, { "code": null, "e": 1222, "s": 1213, "text": "Output :" }, { "code": null, "e": 1327, "s": 1222, "text": "Example 2 : In this example we will be plotting the multiple line segments with various other parameters" }, { "code": "# importing the modules from bokeh.plotting import figure, output_file, show # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Segment Graph\") # name of the x-axis graph.xaxis.axis_label = \"x-axis\" # name of the y-axis graph.yaxis.axis_label = \"y-axis\" # points to be plottedx0 = [0, 0, 5]y0 = [0, 5, 0]x1 = [10, 10, 5]y1 = [10, 5, 10] # color of the linesline_color = [\"yellow\", \"red\", \"purple\"] # value of line dashline_dash = \"dotted\" # thickness of the linesline_width = [15, 10, 20] # plotting the graph graph.segment(x0, y0, x1, y1, line_color = line_color, line_dash = line_dash, line_width = line_width) # displaying the model show(graph)", "e": 2118, "s": 1327, "text": null }, { "code": null, "e": 2127, "s": 2118, "text": "Output :" }, { "code": null, "e": 2146, "s": 2127, "text": "Data Visualization" }, { "code": null, "e": 2181, "s": 2146, "text": "Python Bokeh-plotting-figure-class" }, { "code": null, "e": 2194, "s": 2181, "text": "Python-Bokeh" }, { "code": null, "e": 2201, "s": 2194, "text": "Python" } ]
Types of Spring Bean Scopes Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we will see the different types of Spring Bean Scopes. In Spring there is a possibility to define a scope of a bean, based on your requirement you can make use of it. We can define the scope of a bean as part of the configuration details, if your application is based on XML configuration, then you can define the scope using scope attribute in <bean> tag or if you are using annotation-based configuration then you can use @scope annotation. Basically Spring we have 5 different types of bean scopes, which are described below. 1) singleton: It returns a single bean instance per Spring IoC container. 2) prototype: It returns a new bean instance each time when requested to create a bean. 3) request: It returns a single instance for every HTTP request. 4) session: It returns a single instance for the entire HTTP session. 5) global session: global session scope is equal to session scope on portlet-based web applications. <beans xmlns="http://www.springframework.org/schema/beans" = xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="company" scope="singleton" class="com.onlinetutorialspoint.springcoreapplication.Company"> <bean id="employee" scope="prototype" class="com.onlinetutorialspoint.springcoreapplication.Employee"> <bean id="student" scope="request" class="com.onlinetutorialspoint.springcoreapplication.Student"> <bean id="customer" scope="session" class="com.onlinetutorialspoint.springcoreapplication.Customer"> <bean id="item" scope="globalsession" class="com.onlinetutorialspoint.springcoreapplication.Item"> </bean> </bean> </bean> </bean> </bean> </beans> On the above configuration, we can see all types of spring bean scopes and declarations. Note: If we don’t mention any scope explicitly, the default scope for a bean is a singleton. It is a commonly asked spring interview question. We can define a bean scope in spring using @scope annotation. @Component @Scope("prototype") public class Customer { private int id; public Customer() { System.out.println(" id is:" + id); } public String getId() { return id; } } We can define all types of bean scopes by passing the parameter to @scope annotation. Happy Learning πŸ™‚ Spring Bean Autowire By Constructor Example Spring Bean Autowire ByName Example Spring Bean Autowire ByType Example Spring JdbcTemplate CRUD Application @Qualifier annotation example in Spring Spring Java Configuration Example @Autowired,@Qualifier,@Value annotations in Spring Spring Collection Dependency List Example Spring Collection Map Dependency Example BeanFactory Example in Spring spring expression language example @Component,@Service,@Repository,@Controller in spring Spring MVC HelloWorld Spring Boot Lazy Loading Beans Example Spring MVC Login Form Example Tutorials Spring Bean Autowire By Constructor Example Spring Bean Autowire ByName Example Spring Bean Autowire ByType Example Spring JdbcTemplate CRUD Application @Qualifier annotation example in Spring Spring Java Configuration Example @Autowired,@Qualifier,@Value annotations in Spring Spring Collection Dependency List Example Spring Collection Map Dependency Example BeanFactory Example in Spring spring expression language example @Component,@Service,@Repository,@Controller in spring Spring MVC HelloWorld Spring Boot Lazy Loading Beans Example Spring MVC Login Form Example Tutorials
[ { "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": 471, "s": 398, "text": "In this tutorial, we will see the different types of Spring Bean Scopes." }, { "code": null, "e": 859, "s": 471, "text": "In Spring there is a possibility to define a scope of a bean, based on your requirement you can make use of it. We can define the scope of a bean as part of the configuration details, if your application is based on XML configuration, then you can define the scope using scope attribute in <bean> tag or if you are using annotation-based configuration then you can use @scope annotation." }, { "code": null, "e": 945, "s": 859, "text": "Basically Spring we have 5 different types of bean scopes, which are described below." }, { "code": null, "e": 1019, "s": 945, "text": "1) singleton: It returns a single bean instance per Spring IoC container." }, { "code": null, "e": 1107, "s": 1019, "text": "2) prototype: It returns a new bean instance each time when requested to create a bean." }, { "code": null, "e": 1172, "s": 1107, "text": "3) request: It returns a single instance for every HTTP request." }, { "code": null, "e": 1242, "s": 1172, "text": "4) session: It returns a single instance for the entire HTTP session." }, { "code": null, "e": 1343, "s": 1242, "text": "5) global session: global session scope is equal to session scope on portlet-based web applications." }, { "code": null, "e": 2349, "s": 1343, "text": "<beans xmlns=\"http://www.springframework.org/schema/beans\" =\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemalocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\">\n <bean id=\"company\" scope=\"singleton\"\n class=\"com.onlinetutorialspoint.springcoreapplication.Company\">\n <bean id=\"employee\" scope=\"prototype\"\n class=\"com.onlinetutorialspoint.springcoreapplication.Employee\">\n <bean id=\"student\" scope=\"request\"\n class=\"com.onlinetutorialspoint.springcoreapplication.Student\">\n <bean id=\"customer\" scope=\"session\"\n class=\"com.onlinetutorialspoint.springcoreapplication.Customer\">\n <bean id=\"item\" scope=\"globalsession\"\n class=\"com.onlinetutorialspoint.springcoreapplication.Item\">\n </bean>\n </bean>\n </bean>\n </bean>\n </bean>\n</beans>" }, { "code": null, "e": 2438, "s": 2349, "text": "On the above configuration, we can see all types of spring bean scopes and declarations." }, { "code": null, "e": 2581, "s": 2438, "text": "Note: If we don’t mention any scope explicitly, the default scope for a bean is a singleton. It is a commonly asked spring interview question." }, { "code": null, "e": 2643, "s": 2581, "text": "We can define a bean scope in spring using @scope annotation." }, { "code": null, "e": 2850, "s": 2643, "text": "@Component\n@Scope(\"prototype\")\npublic class Customer {\n\n private int id;\n\n public Customer() {\n System.out.println(\" id is:\" + id);\n }\n\n public String getId() {\n return id;\n }\n}" }, { "code": null, "e": 2936, "s": 2850, "text": "We can define all types of bean scopes by passing the parameter to @scope annotation." }, { "code": null, "e": 2953, "s": 2936, "text": "Happy Learning πŸ™‚" }, { "code": null, "e": 3536, "s": 2953, "text": "\nSpring Bean Autowire By Constructor Example\nSpring Bean Autowire ByName Example\nSpring Bean Autowire ByType Example\nSpring JdbcTemplate CRUD Application\n@Qualifier annotation example in Spring\nSpring Java Configuration Example\n@Autowired,@Qualifier,@Value annotations in Spring\nSpring Collection Dependency List Example\nSpring Collection Map Dependency Example\nBeanFactory Example in Spring\nspring expression language example\n@Component,@Service,@Repository,@Controller in spring\nSpring MVC HelloWorld\nSpring Boot Lazy Loading Beans Example\nSpring MVC Login Form Example Tutorials\n" }, { "code": null, "e": 3580, "s": 3536, "text": "Spring Bean Autowire By Constructor Example" }, { "code": null, "e": 3616, "s": 3580, "text": "Spring Bean Autowire ByName Example" }, { "code": null, "e": 3652, "s": 3616, "text": "Spring Bean Autowire ByType Example" }, { "code": null, "e": 3689, "s": 3652, "text": "Spring JdbcTemplate CRUD Application" }, { "code": null, "e": 3729, "s": 3689, "text": "@Qualifier annotation example in Spring" }, { "code": null, "e": 3763, "s": 3729, "text": "Spring Java Configuration Example" }, { "code": null, "e": 3814, "s": 3763, "text": "@Autowired,@Qualifier,@Value annotations in Spring" }, { "code": null, "e": 3856, "s": 3814, "text": "Spring Collection Dependency List Example" }, { "code": null, "e": 3897, "s": 3856, "text": "Spring Collection Map Dependency Example" }, { "code": null, "e": 3927, "s": 3897, "text": "BeanFactory Example in Spring" }, { "code": null, "e": 3962, "s": 3927, "text": "spring expression language example" }, { "code": null, "e": 4016, "s": 3962, "text": "@Component,@Service,@Repository,@Controller in spring" }, { "code": null, "e": 4038, "s": 4016, "text": "Spring MVC HelloWorld" }, { "code": null, "e": 4077, "s": 4038, "text": "Spring Boot Lazy Loading Beans Example" } ]
Generating Synthetic Classification Data using Scikit | by Faizan Ahemad | Towards Data Science
This is part 1 in a series of articles about imbalanced and noisy data. Part 2 about skewed classification metrics is out. Data generators help us create data with different distributions and profiles to experiment on. If you are testing various algorithms available to you and you want to find which one works in what cases, then these data generators can help you generate case specific data and then test the algorithm. For example you want to check whether gradient boosting trees can do well given just 100 data-points and 2 features? Now either you can search for a 100 data-points dataset, or you can use your own dataset that you are working on. But how would you know if the classifier was a good choice, given that you have so less data and doing cross validation and testing still leaves fair chance of overfitting? Or rather you could use generated data and see what usually works well for such a case, a boosting algorithm or a linear model. Few reasons why you need generated data Can your models handle noisy labels? What happens when 99% of your labels are negative and only 1% are positive? if your models can tell you which features are redundant? In case of model provided feature importances how does the model handle redundant features. Does removing redundant features improve your model’s performance? How does your model behave when Redundant features, noise and imbalance are all present at once in your dataset? If you have N datapoints and M features, what are the safe values of N,M so your model doesn’t overfit? Finding a real dataset meeting such combination of criterias with known levels will be very difficult. As a result we take into account few capabilities that a generator must have to give good approximations of real world datasets. While looking for generators we look for certain capabilities. I list the important capabilities that we look for in generators and classify them accordingly. A lot of times you will get classification data that has huge imbalance. For example fraud detection has imbalance such that most examples (99%) are non-fraud. To check how your classifier does in imbalanced cases, you need to have ability to generate multiple types of imbalanced data. Guassian Quantiles Make classification API Can your classifier perform its job even if the class labels are noisy. What if some fraud examples are marked non-fraud and some non-fraud are marked fraud? How do you know your chosen classifiers behaviour in presence of noise? And how do you select a Robust classifier? Make classification API These are Linear Combinations of your useful features. Many Models like Linear Regression give arbitrary feature coefficient for correlated features. In case of Tree Models they mess up feature importance and also use these features randomly and interchangeably for splits. Removing correlated features usually improves performance. Make classification API The Notebook Used for this is in Github. The helper functions are defined in this file. Here we will go over 3 very good data generators available in scikit and see how you can use them for various cases. 2 Class 2D from sklearn.datasets import make_gaussian_quantiles# Construct datasetX1, y1 = make_gaussian_quantiles(cov=3., n_samples=10000, n_features=2, n_classes=2, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y'])y1 = pd.Series(y1)visualize_2d(X1,y1) Multi-Class 2D from sklearn.datasets import make_gaussian_quantiles# Construct datasetX1, y1 = make_gaussian_quantiles(cov=3., n_samples=10000, n_features=2, n_classes=3, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y'])y1 = pd.Series(y1)visualize_2d(X1,y1) 2 Class 3D from sklearn.datasets import make_gaussian_quantiles# Construct datasetX1, y1 = make_gaussian_quantiles(cov=1., n_samples=10000, n_features=3, n_classes=2, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y','z'])y1 = pd.Series(y1)visualize_3d(X1,y1) A Harder Boundary by Combining 2 Gaussians We create 2 Gaussian’s with different centre locations. mean=(4,4)in 2nd gaussian creates it centered at x=4, y=4. Next we invert the 2nd gaussian and add it’s data points to first gaussian’s data points. from sklearn.datasets import make_gaussian_quantiles# Construct dataset# Gaussian 1X1, y1 = make_gaussian_quantiles(cov=3., n_samples=10000, n_features=2, n_classes=2, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y'])y1 = pd.Series(y1)# Gaussian 2X2, y2 = make_gaussian_quantiles(mean=(4, 4), cov=1, n_samples=5000, n_features=2, n_classes=2, random_state=1)X2 = pd.DataFrame(X2,columns=['x','y'])y2 = pd.Series(y2)# Combine the gaussiansX1.shapeX2.shapeX = pd.DataFrame(np.concatenate((X1, X2)))y = pd.Series(np.concatenate((y1, - y2 + 1)))X.shapevisualize_2d(X,y) In case you want a little simpler and easily separable data Blobs are the way to go. These can be separated by Linear decision Boundaries. Here I will show an example of 4 Class 3D (3-feature Blob). You can notice how the Blobs can be separated by simple planes. As such such data points are good to test Linear Algorithms Like LogisticRegression. This is the most sophisticated scikit api for data generation and it comes with all bells and whistles. It allows you to have multiple features. Also allows you to add noise and imbalance to your data. Some of the more nifty features include adding Redundant features which are basically Linear combination of existing features. Adding Non-Informative features to check if model overfits these useless features. Adding directly repeated features as well. Also to increase complexity of classification you can have multiple clusters of your classes and decrease the separation between classes to force complex non-linear boundary for classifier. I provide below various ways to use this API. 3 Class 3D simple case from sklearn.datasets import make_classificationX,y = make_classification(n_samples=10000, n_features=3, n_informative=3, n_redundant=0, n_repeated=0, n_classes=3, n_clusters_per_class=2, class_sep=1.5, flip_y=0,weights=[0.5,0.5,0.5])X = pd.DataFrame(X)y = pd.Series(y)visualize_3d(X,y) 3 Class 2D with Noise Here we will use the parameter flip_y to add additional noise. This can be used to test if our classifiers will work well after added noise or not. In case we have real world noisy data (say from IOT devices), and a classifier that doesn’t work well with noise, then our accuracy is going to suffer. from sklearn.datasets import make_classification# Generate Clean dataX,y = make_classification(n_samples=10000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2) = plt.subplots(nrows=1, ncols=2,figsize=(20,8))sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax1);ax1.set_title("No Noise");# Generate noisy DataX,y = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1,class_sep=2,flip_y=0.2,weights=[0.5,0.5], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax2);ax2.set_title("With Noise");plt.show(); 2 Class 2D with Imbalance Here we will have 9x more negative examples than positive examples. from sklearn.datasets import make_classification# Generate Balanced DataX,y = make_classification(n_samples=1000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2) = plt.subplots(nrows=1, ncols=2,figsize=(20,8))sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax1);ax1.set_title("No Imbalance");# Generate Imbalanced DataX,y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.9,0.1], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax2);ax2.set_title("Imbalance 9:1 :: Negative:Postive");plt.show(); Using Redundant features (3D) This adds redundant features which are Linear Combinations of other useful features. from sklearn.datasets import make_classification# All unique featuresX,y = make_classification(n_samples=10000, n_features=3, n_informative=3, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_3d(X,y,algorithm="pca")# 2 Useful features and 3rd feature as Linear Combination of first 2X,y = make_classification(n_samples=10000, n_features=3, n_informative=2, n_redundant=1, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_3d(X,y,algorithm="pca") Notice how in presence of redundant features, the 2nd graph, appears to be composed of data points that are in a certain 3D plane (Not full 3D space). Contrast this to first graph which has the data points as clouds spread in all 3 dimensions. For the 2nd graph I intuitively think that if I change my cordinates to the 3D plane in which the data points are, then the data will still be separable but its dimension will reduce to 2D, i.e. I will loose no information by reducing the dimensionality of the 2nd graph. But if I reduce the dimensionality of the first graph the data will not longer remain separable since all 3 features are non-redundant. Lets try this idea. X,y = make_classification(n_samples=1000, n_features=3, n_informative=3, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=0.75,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_2d(X,y,algorithm="pca")X,y = make_classification(n_samples=1000, n_features=3, n_informative=2, n_redundant=1, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=0.75,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_2d(X,y,algorithm="pca") Using Class separation Changing class separation changes the difficulty of the classification task. The data points no longer remain easily separable in case of lower class separation. from sklearn.datasets import make_classification# Low class Sep, Hard decision boundaryX,y = make_classification(n_samples=1000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=0.75,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2, ax3) = plt.subplots(nrows=1, ncols=3,figsize=(20,5))sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax1);ax1.set_title("Low class Sep, Hard decision boundary");# Avg class Sep, Normal decision boundaryX,y = make_classification(n_samples=1000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=1.5,flip_y=0,weights=[0.5,0.5], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax2);ax2.set_title("Avg class Sep, Normal decision boundary");# Large class Sep, Easy decision boundaryX,y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=3,flip_y=0,weights=[0.5,0.5], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax3);ax3.set_title("Large class Sep, Easy decision boundary");plt.show(); We will generate two sets of data and show how you can test your binary classifiers performance and check it’s performance. Our first set will be a standard 2 class data with easy separability. Our 2nd set will be 2 Class data with Non Linear boundary and minor class imbalance. The Hypothesis we want to test is Logistic Regression alone cannot learn Non Linear Boundary. Gradient Boosting is most efficient in learning Non Linear Boundaries. from sklearn.datasets import make_classification# Easy decision boundaryX1,y1 = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2) = plt.subplots(nrows=1, ncols=2,figsize=(20,8))sns.scatterplot(X1[:,0],X1[:,1],hue=y1,ax=ax1);ax1.set_title("Easy decision boundary");# Hard decision boundaryX2,y2 = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=1,flip_y=0,weights=[0.7,0.3], random_state=17)X2a,y2a = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=1.25,flip_y=0,weights=[0.8,0.2], random_state=93)X2 = np.concatenate((X2,X2a))y2 = np.concatenate((y2,y2a))sns.scatterplot(X2[:,0],X2[:,1],hue=y2,ax=ax2);ax2.set_title("Hard decision boundary");X1,y1 = pd.DataFrame(X1),pd.Series(y1)X2,y2 = pd.DataFrame(X2),pd.Series(y2) We will test 3 Algorithms with these and see how the algorithms perform Logistic Regression Logistic Regression with Polynomial Features XGBoost (Gradient Boosting Algorithm) Refer Notebook section 5 for full code. f, (ax1,ax2,ax3) = plt.subplots(nrows=1, ncols=3,figsize=(20,6))lr_results = run_logistic_plain(X1,y1,ax1)lrp_results = run_logistic_polynomial_features(X1,y1,ax2)xgb_results = run_xgb(X1,y1,ax3)plt.show() Lets plot performance and decision boundary structure. Decision Boundary Performance Notice how here XGBoost with 0.916 score emerges as the sure winner. This is because gradient boosting allows learning complex non-linear boundaries. We were able to test our hypothesis and come to conclude that it was correct. Given that it was easy to generate data, we saved time in initial data gathering process and were able to test our classifiers very fast. www.blackarbs.com scikit-learn.org github.com github.com towardsdatascience.com This is the 1st article in a Series where I plan to analyse performance of various classifiers given noise and imbalance. Next Part 2 here. Thanks for Reading!! I solve real-world problems leveraging data science, artificial intelligence, machine learning and deep learning. Feel free to reach out to me on LinkedIn.
[ { "code": null, "e": 295, "s": 172, "text": "This is part 1 in a series of articles about imbalanced and noisy data. Part 2 about skewed classification metrics is out." }, { "code": null, "e": 595, "s": 295, "text": "Data generators help us create data with different distributions and profiles to experiment on. If you are testing various algorithms available to you and you want to find which one works in what cases, then these data generators can help you generate case specific data and then test the algorithm." }, { "code": null, "e": 1127, "s": 595, "text": "For example you want to check whether gradient boosting trees can do well given just 100 data-points and 2 features? Now either you can search for a 100 data-points dataset, or you can use your own dataset that you are working on. But how would you know if the classifier was a good choice, given that you have so less data and doing cross validation and testing still leaves fair chance of overfitting? Or rather you could use generated data and see what usually works well for such a case, a boosting algorithm or a linear model." }, { "code": null, "e": 1167, "s": 1127, "text": "Few reasons why you need generated data" }, { "code": null, "e": 1204, "s": 1167, "text": "Can your models handle noisy labels?" }, { "code": null, "e": 1280, "s": 1204, "text": "What happens when 99% of your labels are negative and only 1% are positive?" }, { "code": null, "e": 1338, "s": 1280, "text": "if your models can tell you which features are redundant?" }, { "code": null, "e": 1430, "s": 1338, "text": "In case of model provided feature importances how does the model handle redundant features." }, { "code": null, "e": 1497, "s": 1430, "text": "Does removing redundant features improve your model’s performance?" }, { "code": null, "e": 1610, "s": 1497, "text": "How does your model behave when Redundant features, noise and imbalance are all present at once in your dataset?" }, { "code": null, "e": 1714, "s": 1610, "text": "If you have N datapoints and M features, what are the safe values of N,M so your model doesn’t overfit?" }, { "code": null, "e": 1946, "s": 1714, "text": "Finding a real dataset meeting such combination of criterias with known levels will be very difficult. As a result we take into account few capabilities that a generator must have to give good approximations of real world datasets." }, { "code": null, "e": 2105, "s": 1946, "text": "While looking for generators we look for certain capabilities. I list the important capabilities that we look for in generators and classify them accordingly." }, { "code": null, "e": 2392, "s": 2105, "text": "A lot of times you will get classification data that has huge imbalance. For example fraud detection has imbalance such that most examples (99%) are non-fraud. To check how your classifier does in imbalanced cases, you need to have ability to generate multiple types of imbalanced data." }, { "code": null, "e": 2411, "s": 2392, "text": "Guassian Quantiles" }, { "code": null, "e": 2435, "s": 2411, "text": "Make classification API" }, { "code": null, "e": 2708, "s": 2435, "text": "Can your classifier perform its job even if the class labels are noisy. What if some fraud examples are marked non-fraud and some non-fraud are marked fraud? How do you know your chosen classifiers behaviour in presence of noise? And how do you select a Robust classifier?" }, { "code": null, "e": 2732, "s": 2708, "text": "Make classification API" }, { "code": null, "e": 3065, "s": 2732, "text": "These are Linear Combinations of your useful features. Many Models like Linear Regression give arbitrary feature coefficient for correlated features. In case of Tree Models they mess up feature importance and also use these features randomly and interchangeably for splits. Removing correlated features usually improves performance." }, { "code": null, "e": 3089, "s": 3065, "text": "Make classification API" }, { "code": null, "e": 3177, "s": 3089, "text": "The Notebook Used for this is in Github. The helper functions are defined in this file." }, { "code": null, "e": 3294, "s": 3177, "text": "Here we will go over 3 very good data generators available in scikit and see how you can use them for various cases." }, { "code": null, "e": 3305, "s": 3294, "text": "2 Class 2D" }, { "code": null, "e": 3617, "s": 3305, "text": "from sklearn.datasets import make_gaussian_quantiles# Construct datasetX1, y1 = make_gaussian_quantiles(cov=3., n_samples=10000, n_features=2, n_classes=2, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y'])y1 = pd.Series(y1)visualize_2d(X1,y1)" }, { "code": null, "e": 3632, "s": 3617, "text": "Multi-Class 2D" }, { "code": null, "e": 3944, "s": 3632, "text": "from sklearn.datasets import make_gaussian_quantiles# Construct datasetX1, y1 = make_gaussian_quantiles(cov=3., n_samples=10000, n_features=2, n_classes=3, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y'])y1 = pd.Series(y1)visualize_2d(X1,y1)" }, { "code": null, "e": 3955, "s": 3944, "text": "2 Class 3D" }, { "code": null, "e": 4271, "s": 3955, "text": "from sklearn.datasets import make_gaussian_quantiles# Construct datasetX1, y1 = make_gaussian_quantiles(cov=1., n_samples=10000, n_features=3, n_classes=2, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y','z'])y1 = pd.Series(y1)visualize_3d(X1,y1)" }, { "code": null, "e": 4314, "s": 4271, "text": "A Harder Boundary by Combining 2 Gaussians" }, { "code": null, "e": 4519, "s": 4314, "text": "We create 2 Gaussian’s with different centre locations. mean=(4,4)in 2nd gaussian creates it centered at x=4, y=4. Next we invert the 2nd gaussian and add it’s data points to first gaussian’s data points." }, { "code": null, "e": 5218, "s": 4519, "text": "from sklearn.datasets import make_gaussian_quantiles# Construct dataset# Gaussian 1X1, y1 = make_gaussian_quantiles(cov=3., n_samples=10000, n_features=2, n_classes=2, random_state=1)X1 = pd.DataFrame(X1,columns=['x','y'])y1 = pd.Series(y1)# Gaussian 2X2, y2 = make_gaussian_quantiles(mean=(4, 4), cov=1, n_samples=5000, n_features=2, n_classes=2, random_state=1)X2 = pd.DataFrame(X2,columns=['x','y'])y2 = pd.Series(y2)# Combine the gaussiansX1.shapeX2.shapeX = pd.DataFrame(np.concatenate((X1, X2)))y = pd.Series(np.concatenate((y1, - y2 + 1)))X.shapevisualize_2d(X,y)" }, { "code": null, "e": 5417, "s": 5218, "text": "In case you want a little simpler and easily separable data Blobs are the way to go. These can be separated by Linear decision Boundaries. Here I will show an example of 4 Class 3D (3-feature Blob)." }, { "code": null, "e": 5566, "s": 5417, "text": "You can notice how the Blobs can be separated by simple planes. As such such data points are good to test Linear Algorithms Like LogisticRegression." }, { "code": null, "e": 5768, "s": 5566, "text": "This is the most sophisticated scikit api for data generation and it comes with all bells and whistles. It allows you to have multiple features. Also allows you to add noise and imbalance to your data." }, { "code": null, "e": 6021, "s": 5768, "text": "Some of the more nifty features include adding Redundant features which are basically Linear combination of existing features. Adding Non-Informative features to check if model overfits these useless features. Adding directly repeated features as well." }, { "code": null, "e": 6211, "s": 6021, "text": "Also to increase complexity of classification you can have multiple clusters of your classes and decrease the separation between classes to force complex non-linear boundary for classifier." }, { "code": null, "e": 6257, "s": 6211, "text": "I provide below various ways to use this API." }, { "code": null, "e": 6280, "s": 6257, "text": "3 Class 3D simple case" }, { "code": null, "e": 6630, "s": 6280, "text": "from sklearn.datasets import make_classificationX,y = make_classification(n_samples=10000, n_features=3, n_informative=3, n_redundant=0, n_repeated=0, n_classes=3, n_clusters_per_class=2, class_sep=1.5, flip_y=0,weights=[0.5,0.5,0.5])X = pd.DataFrame(X)y = pd.Series(y)visualize_3d(X,y)" }, { "code": null, "e": 6652, "s": 6630, "text": "3 Class 2D with Noise" }, { "code": null, "e": 6952, "s": 6652, "text": "Here we will use the parameter flip_y to add additional noise. This can be used to test if our classifiers will work well after added noise or not. In case we have real world noisy data (say from IOT devices), and a classifier that doesn’t work well with noise, then our accuracy is going to suffer." }, { "code": null, "e": 7647, "s": 6952, "text": "from sklearn.datasets import make_classification# Generate Clean dataX,y = make_classification(n_samples=10000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2) = plt.subplots(nrows=1, ncols=2,figsize=(20,8))sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax1);ax1.set_title(\"No Noise\");# Generate noisy DataX,y = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=1,class_sep=2,flip_y=0.2,weights=[0.5,0.5], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax2);ax2.set_title(\"With Noise\");plt.show();" }, { "code": null, "e": 7673, "s": 7647, "text": "2 Class 2D with Imbalance" }, { "code": null, "e": 7741, "s": 7673, "text": "Here we will have 9x more negative examples than positive examples." }, { "code": null, "e": 8467, "s": 7741, "text": "from sklearn.datasets import make_classification# Generate Balanced DataX,y = make_classification(n_samples=1000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2) = plt.subplots(nrows=1, ncols=2,figsize=(20,8))sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax1);ax1.set_title(\"No Imbalance\");# Generate Imbalanced DataX,y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.9,0.1], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax2);ax2.set_title(\"Imbalance 9:1 :: Negative:Postive\");plt.show();" }, { "code": null, "e": 8497, "s": 8467, "text": "Using Redundant features (3D)" }, { "code": null, "e": 8582, "s": 8497, "text": "This adds redundant features which are Linear Combinations of other useful features." }, { "code": null, "e": 9176, "s": 8582, "text": "from sklearn.datasets import make_classification# All unique featuresX,y = make_classification(n_samples=10000, n_features=3, n_informative=3, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_3d(X,y,algorithm=\"pca\")# 2 Useful features and 3rd feature as Linear Combination of first 2X,y = make_classification(n_samples=10000, n_features=3, n_informative=2, n_redundant=1, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_3d(X,y,algorithm=\"pca\")" }, { "code": null, "e": 9420, "s": 9176, "text": "Notice how in presence of redundant features, the 2nd graph, appears to be composed of data points that are in a certain 3D plane (Not full 3D space). Contrast this to first graph which has the data points as clouds spread in all 3 dimensions." }, { "code": null, "e": 9848, "s": 9420, "text": "For the 2nd graph I intuitively think that if I change my cordinates to the 3D plane in which the data points are, then the data will still be separable but its dimension will reduce to 2D, i.e. I will loose no information by reducing the dimensionality of the 2nd graph. But if I reduce the dimensionality of the first graph the data will not longer remain separable since all 3 features are non-redundant. Lets try this idea." }, { "code": null, "e": 10309, "s": 9848, "text": "X,y = make_classification(n_samples=1000, n_features=3, n_informative=3, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=0.75,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_2d(X,y,algorithm=\"pca\")X,y = make_classification(n_samples=1000, n_features=3, n_informative=2, n_redundant=1, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=0.75,flip_y=0,weights=[0.5,0.5], random_state=17)visualize_2d(X,y,algorithm=\"pca\")" }, { "code": null, "e": 10332, "s": 10309, "text": "Using Class separation" }, { "code": null, "e": 10494, "s": 10332, "text": "Changing class separation changes the difficulty of the classification task. The data points no longer remain easily separable in case of lower class separation." }, { "code": null, "e": 11626, "s": 10494, "text": "from sklearn.datasets import make_classification# Low class Sep, Hard decision boundaryX,y = make_classification(n_samples=1000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=0.75,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2, ax3) = plt.subplots(nrows=1, ncols=3,figsize=(20,5))sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax1);ax1.set_title(\"Low class Sep, Hard decision boundary\");# Avg class Sep, Normal decision boundaryX,y = make_classification(n_samples=1000, n_features=2, n_informative=2,n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=1.5,flip_y=0,weights=[0.5,0.5], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax2);ax2.set_title(\"Avg class Sep, Normal decision boundary\");# Large class Sep, Easy decision boundaryX,y = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=3,flip_y=0,weights=[0.5,0.5], random_state=17)sns.scatterplot(X[:,0],X[:,1],hue=y,ax=ax3);ax3.set_title(\"Large class Sep, Easy decision boundary\");plt.show();" }, { "code": null, "e": 11905, "s": 11626, "text": "We will generate two sets of data and show how you can test your binary classifiers performance and check it’s performance. Our first set will be a standard 2 class data with easy separability. Our 2nd set will be 2 Class data with Non Linear boundary and minor class imbalance." }, { "code": null, "e": 12070, "s": 11905, "text": "The Hypothesis we want to test is Logistic Regression alone cannot learn Non Linear Boundary. Gradient Boosting is most efficient in learning Non Linear Boundaries." }, { "code": null, "e": 13131, "s": 12070, "text": "from sklearn.datasets import make_classification# Easy decision boundaryX1,y1 = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=2,flip_y=0,weights=[0.5,0.5], random_state=17)f, (ax1,ax2) = plt.subplots(nrows=1, ncols=2,figsize=(20,8))sns.scatterplot(X1[:,0],X1[:,1],hue=y1,ax=ax1);ax1.set_title(\"Easy decision boundary\");# Hard decision boundaryX2,y2 = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=1,flip_y=0,weights=[0.7,0.3], random_state=17)X2a,y2a = make_classification(n_samples=10000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, n_clusters_per_class=2,class_sep=1.25,flip_y=0,weights=[0.8,0.2], random_state=93)X2 = np.concatenate((X2,X2a))y2 = np.concatenate((y2,y2a))sns.scatterplot(X2[:,0],X2[:,1],hue=y2,ax=ax2);ax2.set_title(\"Hard decision boundary\");X1,y1 = pd.DataFrame(X1),pd.Series(y1)X2,y2 = pd.DataFrame(X2),pd.Series(y2)" }, { "code": null, "e": 13203, "s": 13131, "text": "We will test 3 Algorithms with these and see how the algorithms perform" }, { "code": null, "e": 13223, "s": 13203, "text": "Logistic Regression" }, { "code": null, "e": 13268, "s": 13223, "text": "Logistic Regression with Polynomial Features" }, { "code": null, "e": 13306, "s": 13268, "text": "XGBoost (Gradient Boosting Algorithm)" }, { "code": null, "e": 13346, "s": 13306, "text": "Refer Notebook section 5 for full code." }, { "code": null, "e": 13552, "s": 13346, "text": "f, (ax1,ax2,ax3) = plt.subplots(nrows=1, ncols=3,figsize=(20,6))lr_results = run_logistic_plain(X1,y1,ax1)lrp_results = run_logistic_polynomial_features(X1,y1,ax2)xgb_results = run_xgb(X1,y1,ax3)plt.show()" }, { "code": null, "e": 13607, "s": 13552, "text": "Lets plot performance and decision boundary structure." }, { "code": null, "e": 13625, "s": 13607, "text": "Decision Boundary" }, { "code": null, "e": 13637, "s": 13625, "text": "Performance" }, { "code": null, "e": 13787, "s": 13637, "text": "Notice how here XGBoost with 0.916 score emerges as the sure winner. This is because gradient boosting allows learning complex non-linear boundaries." }, { "code": null, "e": 14003, "s": 13787, "text": "We were able to test our hypothesis and come to conclude that it was correct. Given that it was easy to generate data, we saved time in initial data gathering process and were able to test our classifiers very fast." }, { "code": null, "e": 14021, "s": 14003, "text": "www.blackarbs.com" }, { "code": null, "e": 14038, "s": 14021, "text": "scikit-learn.org" }, { "code": null, "e": 14049, "s": 14038, "text": "github.com" }, { "code": null, "e": 14060, "s": 14049, "text": "github.com" }, { "code": null, "e": 14083, "s": 14060, "text": "towardsdatascience.com" }, { "code": null, "e": 14223, "s": 14083, "text": "This is the 1st article in a Series where I plan to analyse performance of various classifiers given noise and imbalance. Next Part 2 here." }, { "code": null, "e": 14244, "s": 14223, "text": "Thanks for Reading!!" } ]
Python - Network Environment
Python 3 is available for Windows, Mac OS and most of the flavors of Linux operating system. Even though Python 2 is available for many other OSs, Python 3 support either has not been made available for them or has been dropped. Open a terminal window and type "python" to find out if it is already installed and which version is installed. Binaries of latest version of Python 3 (Python 3.5.1) are available on this download page The following different installation options are available. Windows x86-64 embeddable zip file Windows x86-64 executable installer Windows x86-64 web-based installer Windows x86 embeddable zip file Windows x86 executable installer Windows x86 web-based installer Note βˆ’ In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1. For versions 3.0 to 3.4.x Windows XP is acceptable. Different flavors of Linux use different package managers for installation of new packages. On Ubuntu Linux, Python 3 is installed using the following command from the terminal. $sudo apt-get install python3-minimal Installation from source Download Gzipped source tarball from Python's download URL βˆ’ https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz Extract the tarball tar xvfz Python-3.5.1.tgz Configure and Install: cd Python-3.5.1 ./configure --prefix = /opt/python3.5.1 make sudo make install Download Mac OS installers from this URL βˆ’ https://www.python.org/downloads/mac-osx/ Mac OS X 64-bit/32-bit installer βˆ’ python-3.5.1-macosx10.6.pkg Mac OS X 32-bit i386/PPC installer βˆ’ python-3.5.1-macosx10.5.pkg Double click this package file and follow the wizard instructions to install. The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python βˆ’ Python Official Website βˆ’ https://www.python.org/ You can download Python documentation from the following site. The documentation is available in HTML, PDF and PostScript formats. Python Documentation Website βˆ’ www.python.org/doc/ Programs and other executable files can be in many directories. Hence, the operating systems provide a search path that lists the directories that it searches for executables. The important features are βˆ’ The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path variable is named as PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not). The path variable is named as PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not). In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path. In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path. To add the Python directory to the path for a particular session in Unix βˆ’ In the csh shell βˆ’ type setenv PATH "$PATH:/usr/local/bin/python3" and press Enter. In the csh shell βˆ’ type setenv PATH "$PATH:/usr/local/bin/python3" and press Enter. In the bash shell (Linux) βˆ’ type export PYTHONPATH=/usr/local/bin/python3.4 and press Enter. In the bash shell (Linux) βˆ’ type export PYTHONPATH=/usr/local/bin/python3.4 and press Enter. In the sh or ksh shell βˆ’ type PATH="$PATH:/usr/local/bin/python3" and press Enter. In the sh or ksh shell βˆ’ type PATH="$PATH:/usr/local/bin/python3" and press Enter. Note βˆ’ /usr/local/bin/python3 is the path of the Python directory. To add the Python directory to the path for a particular session in Windows βˆ’ At the command prompt βˆ’ type path %path%;C:\Python and press Enter. At the command prompt βˆ’ type path %path%;C:\Python and press Enter. Note βˆ’ C:\Python is the path of the Python directory There are three different ways to start Python βˆ’ You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. Enter python the command line. Start coding right away in the interactive interpreter. $python # Unix/Linux or python% # Unix/Linux or C:>python # Windows/DOS You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. Unix βˆ’ IDLE is the very first Unix IDE for Python. Unix βˆ’ IDLE is the very first Unix IDE for Python. Windows βˆ’ PythonWin is the first Windows interface for Python and is an IDE with a GUI. Windows βˆ’ PythonWin is the first Windows interface for Python and is an IDE with a GUI. Macintosh βˆ’ The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. Macintosh βˆ’ The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. If you are not able to set up the environment properly, then you can take the help of your system admin. Make sure the Python environment is properly set up and working perfectly fine. Note βˆ’ All the examples given in subsequent chapters are executed with Python 3.4.1 version available on Windows 7 and Ubuntu Linux. We have already set up Python Programming environment online, so that you can execute all the available examples online while you are learning theory. Feel free to modify any example and execute it online. 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": 2555, "s": 2326, "text": "Python 3 is available for Windows, Mac OS and most of the flavors of Linux operating system. Even though Python 2 is available for many other OSs, Python 3 support either has not been made available for them or has been dropped." }, { "code": null, "e": 2667, "s": 2555, "text": "Open a terminal window and type \"python\" to find out if it is already installed and which version is installed." }, { "code": null, "e": 2757, "s": 2667, "text": "Binaries of latest version of Python 3 (Python 3.5.1) are available on this download page" }, { "code": null, "e": 2817, "s": 2757, "text": "The following different installation options are available." }, { "code": null, "e": 2852, "s": 2817, "text": "Windows x86-64 embeddable zip file" }, { "code": null, "e": 2888, "s": 2852, "text": "Windows x86-64 executable installer" }, { "code": null, "e": 2923, "s": 2888, "text": "Windows x86-64 web-based installer" }, { "code": null, "e": 2955, "s": 2923, "text": "Windows x86 embeddable zip file" }, { "code": null, "e": 2988, "s": 2955, "text": "Windows x86 executable installer" }, { "code": null, "e": 3020, "s": 2988, "text": "Windows x86 web-based installer" }, { "code": null, "e": 3161, "s": 3020, "text": "Note βˆ’ In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1. For versions 3.0 to 3.4.x Windows XP is acceptable." }, { "code": null, "e": 3253, "s": 3161, "text": "Different flavors of Linux use different package managers for installation of new packages." }, { "code": null, "e": 3339, "s": 3253, "text": "On Ubuntu Linux, Python 3 is installed using the following command from the terminal." }, { "code": null, "e": 3377, "s": 3339, "text": "$sudo apt-get install python3-minimal" }, { "code": null, "e": 3402, "s": 3377, "text": "Installation from source" }, { "code": null, "e": 3520, "s": 3402, "text": "Download Gzipped source tarball from Python's download URL βˆ’ https://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz" }, { "code": null, "e": 3670, "s": 3520, "text": "Extract the tarball\ntar xvfz Python-3.5.1.tgz\nConfigure and Install:\ncd Python-3.5.1\n./configure --prefix = /opt/python3.5.1\nmake \nsudo make install" }, { "code": null, "e": 3755, "s": 3670, "text": "Download Mac OS installers from this URL βˆ’ https://www.python.org/downloads/mac-osx/" }, { "code": null, "e": 3818, "s": 3755, "text": "Mac OS X 64-bit/32-bit installer βˆ’ python-3.5.1-macosx10.6.pkg" }, { "code": null, "e": 3883, "s": 3818, "text": "Mac OS X 32-bit i386/PPC installer βˆ’ python-3.5.1-macosx10.5.pkg" }, { "code": null, "e": 3961, "s": 3883, "text": "Double click this package file and follow the wizard instructions to install." }, { "code": null, "e": 4092, "s": 3961, "text": "The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python βˆ’" }, { "code": null, "e": 4142, "s": 4092, "text": "Python Official Website βˆ’ https://www.python.org/" }, { "code": null, "e": 4273, "s": 4142, "text": "You can download Python documentation from the following site. The documentation is available in HTML, PDF and PostScript formats." }, { "code": null, "e": 4324, "s": 4273, "text": "Python Documentation Website βˆ’ www.python.org/doc/" }, { "code": null, "e": 4500, "s": 4324, "text": "Programs and other executable files can be in many directories. Hence, the operating systems provide a search path that lists the directories that it searches for executables." }, { "code": null, "e": 4529, "s": 4500, "text": "The important features are βˆ’" }, { "code": null, "e": 4722, "s": 4529, "text": "The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs." }, { "code": null, "e": 4915, "s": 4722, "text": "The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs." }, { "code": null, "e": 5019, "s": 4915, "text": "The path variable is named as PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not)." }, { "code": null, "e": 5123, "s": 5019, "text": "The path variable is named as PATH in Unix or Path in Windows (Unix is case-sensitive; Windows is not)." }, { "code": null, "e": 5286, "s": 5123, "text": "In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path." }, { "code": null, "e": 5449, "s": 5286, "text": "In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path." }, { "code": null, "e": 5524, "s": 5449, "text": "To add the Python directory to the path for a particular session in Unix βˆ’" }, { "code": null, "e": 5608, "s": 5524, "text": "In the csh shell βˆ’ type setenv PATH \"$PATH:/usr/local/bin/python3\" and press Enter." }, { "code": null, "e": 5692, "s": 5608, "text": "In the csh shell βˆ’ type setenv PATH \"$PATH:/usr/local/bin/python3\" and press Enter." }, { "code": null, "e": 5785, "s": 5692, "text": "In the bash shell (Linux) βˆ’ type export PYTHONPATH=/usr/local/bin/python3.4 and press Enter." }, { "code": null, "e": 5878, "s": 5785, "text": "In the bash shell (Linux) βˆ’ type export PYTHONPATH=/usr/local/bin/python3.4 and press Enter." }, { "code": null, "e": 5961, "s": 5878, "text": "In the sh or ksh shell βˆ’ type PATH=\"$PATH:/usr/local/bin/python3\" and press Enter." }, { "code": null, "e": 6044, "s": 5961, "text": "In the sh or ksh shell βˆ’ type PATH=\"$PATH:/usr/local/bin/python3\" and press Enter." }, { "code": null, "e": 6112, "s": 6044, "text": "Note βˆ’ /usr/local/bin/python3 is the path of the Python directory." }, { "code": null, "e": 6190, "s": 6112, "text": "To add the Python directory to the path for a particular session in Windows βˆ’" }, { "code": null, "e": 6258, "s": 6190, "text": "At the command prompt βˆ’ type path %path%;C:\\Python and press Enter." }, { "code": null, "e": 6326, "s": 6258, "text": "At the command prompt βˆ’ type path %path%;C:\\Python and press Enter." }, { "code": null, "e": 6380, "s": 6326, "text": "Note βˆ’ C:\\Python is the path of the Python directory " }, { "code": null, "e": 6429, "s": 6380, "text": "There are three different ways to start Python βˆ’" }, { "code": null, "e": 6548, "s": 6429, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window." }, { "code": null, "e": 6579, "s": 6548, "text": "Enter python the command line." }, { "code": null, "e": 6635, "s": 6579, "text": "Start coding right away in the interactive interpreter." }, { "code": null, "e": 6747, "s": 6635, "text": "$python # Unix/Linux\n\nor \n\npython% # Unix/Linux\n\nor \n\nC:>python # Windows/DOS" }, { "code": null, "e": 6892, "s": 6747, "text": "You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python." }, { "code": null, "e": 6943, "s": 6892, "text": "Unix βˆ’ IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 6994, "s": 6943, "text": "Unix βˆ’ IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 7082, "s": 6994, "text": "Windows βˆ’ PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 7170, "s": 7082, "text": "Windows βˆ’ PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 7327, "s": 7170, "text": "Macintosh βˆ’ The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 7484, "s": 7327, "text": "Macintosh βˆ’ The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 7669, "s": 7484, "text": "If you are not able to set up the environment properly, then you can take the help of your system admin. Make sure the Python environment is properly set up and working perfectly fine." }, { "code": null, "e": 7802, "s": 7669, "text": "Note βˆ’ All the examples given in subsequent chapters are executed with Python 3.4.1 version available on Windows 7 and Ubuntu Linux." }, { "code": null, "e": 8008, "s": 7802, "text": "We have already set up Python Programming environment online, so that you can execute all the available examples online while you are learning theory. Feel free to modify any example and execute it online." }, { "code": null, "e": 8045, "s": 8008, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 8061, "s": 8045, "text": " Malhar Lathkar" }, { "code": null, "e": 8094, "s": 8061, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 8113, "s": 8094, "text": " Arnab Chakraborty" }, { "code": null, "e": 8148, "s": 8113, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 8170, "s": 8148, "text": " In28Minutes Official" }, { "code": null, "e": 8204, "s": 8170, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 8232, "s": 8204, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 8267, "s": 8232, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 8281, "s": 8267, "text": " Lets Kode It" }, { "code": null, "e": 8314, "s": 8281, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 8331, "s": 8314, "text": " Abhilash Nelson" }, { "code": null, "e": 8338, "s": 8331, "text": " Print" }, { "code": null, "e": 8349, "s": 8338, "text": " Add Notes" } ]
B+ tree Deletion in Data Structure
Here we will see, how to perform the deletion of a node from B+ Tree. Suppose we have a B+ Tree like below 7minus; Example of B+ Tree βˆ’ Deletion has two parts. At first we have to find the element. That strategy is like the querying. Now for deletion, we have to care about some rules. One node must have at-least m/2 elements. So if we delete, one element, and it has less than m-1 elements remaining, then it will adjust itself. If the entire node is deleted, then its children will be merged, and if their size is same as m, then split them into two parts, and again the median value will go up. Suppose we want to delete 78. Now there are two children. [75, 77], and [78, 85], then It will delete 78 from the leaf node first, after that take 85, and make a copy of key 85, and make it as root of the subtree. BPlusTreeDelete(x, key) βˆ’ Input βˆ’ The root of the tree, and key to delete We will assume, that the key is present into the list Start from root node, perform exact match for key as β€˜key’ till a leaf node. Let the search path be x1, x2, ... , xh. The x1 is first node so root, then xh is leaf node. Each node xi is parent of xi+1 delete the object where key is β€˜key’ from xh. if h = 1, then return, as there is only one node which is root. i := h while xi underflows, do if immediate sibling node s of xi, has at least m/2 + 1 elements, then redistribute entries evenly between s and xi. corresponding to redistribution, a key k in the parent node xi-1, will be changed. if xi is non-leaf node, then k is dragged down to xi. and a key from s is pushed up to fill the place of k else k is simply replaced by a key in s return else merge xi with the sibling node s. Delete the corresponding child pointer in xi-1. if xi is an internal node, then drag the key in xi-1. which is previously divides xi and s. into the new node xi and s, into the new node xi. else delete that key in xi-1. i := i – 1 end if done
[ { "code": null, "e": 1177, "s": 1062, "text": "Here we will see, how to perform the deletion of a node from B+ Tree. Suppose we have a B+ Tree like below 7minus;" }, { "code": null, "e": 1198, "s": 1177, "text": "Example of B+ Tree βˆ’" }, { "code": null, "e": 1661, "s": 1198, "text": "Deletion has two parts. At first we have to find the element. That strategy is like the querying. Now for deletion, we have to care about some rules. One node must have at-least m/2 elements. So if we delete, one element, and it has less than m-1 elements remaining, then it will adjust itself. If the entire node is deleted, then its children will be merged, and if their size is same as m, then split them into two parts, and again the median value will go up." }, { "code": null, "e": 1875, "s": 1661, "text": "Suppose we want to delete 78. Now there are two children. [75, 77], and [78, 85], then It will delete 78 from the leaf node first, after that take 85, and make a copy of key 85, and make it as root of the subtree." }, { "code": null, "e": 1901, "s": 1875, "text": "BPlusTreeDelete(x, key) βˆ’" }, { "code": null, "e": 1949, "s": 1901, "text": "Input βˆ’ The root of the tree, and key to delete" }, { "code": null, "e": 3089, "s": 1949, "text": "We will assume, that the key is present into the list\nStart from root node, perform exact match for key as β€˜key’ till a leaf node. Let the search path\nbe x1, x2, ... , xh. The x1 is first node so root, then xh is leaf node. Each node xi is parent of xi+1\ndelete the object where key is β€˜key’ from xh.\nif h = 1, then return, as there is only one node which is root.\ni := h\nwhile xi underflows, do\n if immediate sibling node s of xi, has at least m/2 + 1 elements, then\n redistribute entries evenly between s and xi.\n corresponding to redistribution, a key k in the parent node xi-1, will be changed.\n if xi is non-leaf node, then\n k is dragged down to xi. and a key from s is pushed up to fill the place of k\n else\n k is simply replaced by a key in s\n return\n else\n merge xi with the sibling node s. Delete the corresponding child pointer in xi-1.\n if xi is an internal node, then\n drag the key in xi-1. which is previously divides xi and s. into the new node\n xi and s, into the new node xi.\n else\n delete that key in xi-1.\n i := i – 1\n end if\ndone" } ]
Change the Return-Path in PHP mail function
The reply and return path can be placed in the headers as shown below βˆ’ $headers = 'From: sample@example.com' . "\r\n" . 'Reply-To: sample@example.com' . "\r\n" . 'Return-Path: sample@example.com' Otherwise, it can be passed as the fifth parameter to change the return path βˆ’ mail($to, $subject, $message, $headers, "-f email@wherever.com"); Here, 'email@wherever.com' has to be replaced with the user's respective email id.
[ { "code": null, "e": 1134, "s": 1062, "text": "The reply and return path can be placed in the headers as shown below βˆ’" }, { "code": null, "e": 1259, "s": 1134, "text": "$headers = 'From: sample@example.com' . \"\\r\\n\" .\n'Reply-To: sample@example.com' . \"\\r\\n\" .\n'Return-Path: sample@example.com'" }, { "code": null, "e": 1338, "s": 1259, "text": "Otherwise, it can be passed as the fifth parameter to change the return path βˆ’" }, { "code": null, "e": 1404, "s": 1338, "text": "mail($to, $subject, $message, $headers, \"-f email@wherever.com\");" }, { "code": null, "e": 1487, "s": 1404, "text": "Here, 'email@wherever.com' has to be replaced with the user's respective email id." } ]
How do you fill in or pad a column with zeros using a MySQL query?
You can use ZEROFILL for column to fill in or pad with zeros. Let us first create a tableβˆ’ mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.58 sec) Following is the query to add zerofill attribute for Number columnβˆ’ mysql> alter table DemoTable change Number Number int(10) zerofill not null; Query OK, 0 rows affected (1.13 sec) Records: 0 Duplicates: 0 Warnings: 0 Insert records in the table using insert command βˆ’ mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(12); Query OK, 1 row affected (0.53 sec) mysql> insert into DemoTable values(123); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(1234); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(12345); Query OK, 1 row affected (0.15 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable; This will produce the following outputβˆ’ +------------+ | Number | +------------+ | 0000000001 | | 0000000012 | | 0000000123 | | 0000001234 | | 0000012345 | +------------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1153, "s": 1062, "text": "You can use ZEROFILL for column to fill in or pad with zeros. Let us first create a tableβˆ’" }, { "code": null, "e": 1245, "s": 1153, "text": "mysql> create table DemoTable\n (\n Number int\n );\nQuery OK, 0 rows affected (0.58 sec)" }, { "code": null, "e": 1313, "s": 1245, "text": "Following is the query to add zerofill attribute for Number columnβˆ’" }, { "code": null, "e": 1464, "s": 1313, "text": "mysql> alter table DemoTable change Number Number int(10) zerofill not null;\nQuery OK, 0 rows affected (1.13 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 1515, "s": 1464, "text": "Insert records in the table using insert command βˆ’" }, { "code": null, "e": 1905, "s": 1515, "text": "mysql> insert into DemoTable values(1);\nQuery OK, 1 row affected (0.23 sec)\nmysql> insert into DemoTable values(12);\nQuery OK, 1 row affected (0.53 sec)\nmysql> insert into DemoTable values(123);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(1234);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values(12345);\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1965, "s": 1905, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1996, "s": 1965, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2036, "s": 1996, "text": "This will produce the following outputβˆ’" }, { "code": null, "e": 2196, "s": 2036, "text": "+------------+\n| Number |\n+------------+\n| 0000000001 |\n| 0000000012 |\n| 0000000123 |\n| 0000001234 |\n| 0000012345 |\n+------------+\n5 rows in set (0.00 sec)" } ]
How to add a Login Form to an Image using HTML and CSS ?
21 May, 2021 The login form on an Image is used on many websites. Like hotels website that contains the pictures of the hotels or some organizations that organize some special events holding that events picture and login form on that. In that case, you can design a login or registration form on that picture. This design will make the website more attractive than a regular login or registration form. To create the login form on an Image you just need HTML and CSS. The below example will illustrate the approach of the concept.Creating the Structure: In this section, we will create a basic website structure to create a login form on an Image. HTML code: HTML code is used to design the structure of the login form. html <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"></head> <body> <div class="bg-img"> <h1>GeeksforGeeks</h1> <form class="container"> <b>Username</b> <input type="text" placeholder="Username Please" name="username" required> <b>Password</b> <input type="password" placeholder="Enter Password" name="password" required> <button type="submit" class="button">Login</button> </form> </div></body> </html> Designing the Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the login form. CSS code of structure: CSS <style> body { height: 100%; font-family: Arial, sans-serif; } * { box-sizing: border-box; } h1 { text-align:center; color:green; -webkit-text-stroke: 1px black; } /* styling background image */ .bg-img { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/20191212174641/bg1.png"); min-height: 380px; background-size: cover; } /* Styling the form container */ .container { position: absolute; left: 28px; top: 50px; margin: 20px; max-width: 300px; padding: 16px; } b { color: green; font-size:26px; -webkit-text-stroke: 1px black; } /* Full-width input */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 15px 0px; border: 2px solid green; } /* Styling the submit button */ .button { background-color: green; color: white; padding: 16px 16px; border: none; cursor: pointer; width: 100%; } .button:hover { transform: scale(1.1); transition: transform 0.3s; } </style> Combining the HTML and CSS code: This is the final code after combining the above two sections. You can see that the left align login form on the image is more attractive compared to a normal login form. html <!DOCTYPE html><html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { height: 100%; font-family: Arial, sans-serif; } * { box-sizing: border-box; } h1 { text-align:center; color:green; -webkit-text-stroke: 1px black; } /* styling background image */ .bg-img { background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/20191212174641/bg1.png"); min-height: 380px; background-size: cover; } /* Styling the form container */ .container { position: absolute; left: 28px; top: 50px; margin: 20px; max-width: 300px; padding: 16px; } b { color: green; font-size:26px; -webkit-text-stroke: 1px black; } /* Full-width input */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 15px 0px; border: 2px solid green; } /* Styling the submit button */ .button { background-color: green; color: white; padding: 16px 16px; border: none; cursor: pointer; width: 100%; } .button:hover { transform: scale(1.1); transition: transform 0.3s; } </style></head> <body> <div class="bg-img"> <h1>GeeksforGeeks</h1> <form class="container"> <b>Username</b> <input type="text" placeholder="Username Please" name="username" required> <b>Password</b> <input type="password" placeholder="Enter Password" name="password" required> <button type="submit" class="button">Login</button> </form> </div></body> </html> Output: sumitgumber28 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 53, "s": 25, "text": "\n21 May, 2021" }, { "code": null, "e": 690, "s": 53, "text": "The login form on an Image is used on many websites. Like hotels website that contains the pictures of the hotels or some organizations that organize some special events holding that events picture and login form on that. In that case, you can design a login or registration form on that picture. This design will make the website more attractive than a regular login or registration form. To create the login form on an Image you just need HTML and CSS. The below example will illustrate the approach of the concept.Creating the Structure: In this section, we will create a basic website structure to create a login form on an Image. " }, { "code": null, "e": 764, "s": 690, "text": "HTML code: HTML code is used to design the structure of the login form. " }, { "code": null, "e": 769, "s": 764, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head> <body> <div class=\"bg-img\"> <h1>GeeksforGeeks</h1> <form class=\"container\"> <b>Username</b> <input type=\"text\" placeholder=\"Username Please\" name=\"username\" required> <b>Password</b> <input type=\"password\" placeholder=\"Enter Password\" name=\"password\" required> <button type=\"submit\" class=\"button\">Login</button> </form> </div></body> </html>", "e": 1360, "s": 769, "text": null }, { "code": null, "e": 1532, "s": 1362, "text": "Designing the Structure: In the previous section, we have created the structure of the basic website. In this section, we will design the structure for the login form. " }, { "code": null, "e": 1557, "s": 1532, "text": "CSS code of structure: " }, { "code": null, "e": 1561, "s": 1557, "text": "CSS" }, { "code": " <style> body { height: 100%; font-family: Arial, sans-serif; } * { box-sizing: border-box; } h1 { text-align:center; color:green; -webkit-text-stroke: 1px black; } /* styling background image */ .bg-img { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/20191212174641/bg1.png\"); min-height: 380px; background-size: cover; } /* Styling the form container */ .container { position: absolute; left: 28px; top: 50px; margin: 20px; max-width: 300px; padding: 16px; } b { color: green; font-size:26px; -webkit-text-stroke: 1px black; } /* Full-width input */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 15px 0px; border: 2px solid green; } /* Styling the submit button */ .button { background-color: green; color: white; padding: 16px 16px; border: none; cursor: pointer; width: 100%; } .button:hover { transform: scale(1.1); transition: transform 0.3s; } </style>", "e": 3039, "s": 1561, "text": null }, { "code": null, "e": 3246, "s": 3041, "text": "Combining the HTML and CSS code: This is the final code after combining the above two sections. You can see that the left align login form on the image is more attractive compared to a normal login form. " }, { "code": null, "e": 3251, "s": 3246, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <style> body { height: 100%; font-family: Arial, sans-serif; } * { box-sizing: border-box; } h1 { text-align:center; color:green; -webkit-text-stroke: 1px black; } /* styling background image */ .bg-img { background-image: url(\"https://media.geeksforgeeks.org/wp-content/uploads/20191212174641/bg1.png\"); min-height: 380px; background-size: cover; } /* Styling the form container */ .container { position: absolute; left: 28px; top: 50px; margin: 20px; max-width: 300px; padding: 16px; } b { color: green; font-size:26px; -webkit-text-stroke: 1px black; } /* Full-width input */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 15px 0px; border: 2px solid green; } /* Styling the submit button */ .button { background-color: green; color: white; padding: 16px 16px; border: none; cursor: pointer; width: 100%; } .button:hover { transform: scale(1.1); transition: transform 0.3s; } </style></head> <body> <div class=\"bg-img\"> <h1>GeeksforGeeks</h1> <form class=\"container\"> <b>Username</b> <input type=\"text\" placeholder=\"Username Please\" name=\"username\" required> <b>Password</b> <input type=\"password\" placeholder=\"Enter Password\" name=\"password\" required> <button type=\"submit\" class=\"button\">Login</button> </form> </div></body> </html>", "e": 5317, "s": 3251, "text": null }, { "code": null, "e": 5327, "s": 5317, "text": "Output: " }, { "code": null, "e": 5343, "s": 5329, "text": "sumitgumber28" }, { "code": null, "e": 5352, "s": 5343, "text": "CSS-Misc" }, { "code": null, "e": 5362, "s": 5352, "text": "HTML-Misc" }, { "code": null, "e": 5366, "s": 5362, "text": "CSS" }, { "code": null, "e": 5371, "s": 5366, "text": "HTML" }, { "code": null, "e": 5388, "s": 5371, "text": "Web Technologies" }, { "code": null, "e": 5415, "s": 5388, "text": "Web technologies Questions" }, { "code": null, "e": 5420, "s": 5415, "text": "HTML" }, { "code": null, "e": 5518, "s": 5420, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5566, "s": 5518, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5628, "s": 5566, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5678, "s": 5628, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5736, "s": 5678, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 5786, "s": 5736, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 5834, "s": 5786, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5896, "s": 5834, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5946, "s": 5896, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5970, "s": 5946, "text": "REST API (Introduction)" } ]
HTML | Marquee scrolldelay attribute
11 Jan, 2022 The Marquee scrolldelay attribute in HTML is used to set the interval between each scroll movement in milliseconds. The default value of Scrolldelay is 85. Note: Value less then 60 is not acceptable, unless truespeed is specified.Syntax: <marquee scrolldelay=number> Attribute value: number: Define the speed of marquee. Example: html <!DOCTYPE html><html> <head> <title>HTML | Marquee scrolldelay attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <div class="main"> <marquee class="marq" bgcolor="Green" direction="left" loop=""> scrolldealy: default(85) </marquee> <marquee class="marq" Scrolldelay=100 bgcolor="Green" direction="left" loop=""> scrolldelay: 100 </marquee> </div></body> </html> Output: Supported Browsers: The browsers supported by HTML Marquee scrolldelay attribute are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jan, 2022" }, { "code": null, "e": 293, "s": 53, "text": "The Marquee scrolldelay attribute in HTML is used to set the interval between each scroll movement in milliseconds. The default value of Scrolldelay is 85. Note: Value less then 60 is not acceptable, unless truespeed is specified.Syntax: " }, { "code": null, "e": 322, "s": 293, "text": "<marquee scrolldelay=number>" }, { "code": null, "e": 341, "s": 322, "text": "Attribute value: " }, { "code": null, "e": 378, "s": 341, "text": "number: Define the speed of marquee." }, { "code": null, "e": 389, "s": 378, "text": "Example: " }, { "code": null, "e": 394, "s": 389, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML | Marquee scrolldelay attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <div class=\"main\"> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"left\" loop=\"\"> scrolldealy: default(85) </marquee> <marquee class=\"marq\" Scrolldelay=100 bgcolor=\"Green\" direction=\"left\" loop=\"\"> scrolldelay: 100 </marquee> </div></body> </html>", "e": 1157, "s": 394, "text": null }, { "code": null, "e": 1167, "s": 1157, "text": "Output: " }, { "code": null, "e": 1268, "s": 1167, "text": "Supported Browsers: The browsers supported by HTML Marquee scrolldelay attribute are listed below: " }, { "code": null, "e": 1282, "s": 1268, "text": "Google Chrome" }, { "code": null, "e": 1300, "s": 1282, "text": "Internet Explorer" }, { "code": null, "e": 1308, "s": 1300, "text": "Firefox" }, { "code": null, "e": 1321, "s": 1308, "text": "Apple Safari" }, { "code": null, "e": 1327, "s": 1321, "text": "Opera" }, { "code": null, "e": 1343, "s": 1329, "text": "ManasChhabra2" }, { "code": null, "e": 1359, "s": 1343, "text": "HTML-Attributes" }, { "code": null, "e": 1364, "s": 1359, "text": "HTML" }, { "code": null, "e": 1381, "s": 1364, "text": "Web Technologies" }, { "code": null, "e": 1386, "s": 1381, "text": "HTML" }, { "code": null, "e": 1484, "s": 1386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1532, "s": 1484, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 1556, "s": 1532, "text": "REST API (Introduction)" }, { "code": null, "e": 1606, "s": 1556, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 1643, "s": 1606, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 1682, "s": 1643, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1715, "s": 1682, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1776, "s": 1715, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1819, "s": 1776, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1891, "s": 1819, "text": "Differences between Functional Components and Class Components in React" } ]
HTML | Marquee bgcolor attribute
14 Jan, 2022 The Marquee bgcolor attribute in HTML is used to set the backgroundcolor of marquee. Note: This attribute is no longer supported in HTML5. Syntax: <marquee bgcolor="colorname" > Attribute value: color name: Define the background color of the marquee. Example: html <!DOCTYPE html><html> <head> <title>HTML Marquee bgcolor attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <marquee class="marq" bgcolor="Green" direction="left" loop=""> Background color is green </marquee> </body> </html> Google Chrome Internet Explorer Firefox Apple Safari Opera ManasChhabra2 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Jan, 2022" }, { "code": null, "e": 113, "s": 28, "text": "The Marquee bgcolor attribute in HTML is used to set the backgroundcolor of marquee." }, { "code": null, "e": 167, "s": 113, "text": "Note: This attribute is no longer supported in HTML5." }, { "code": null, "e": 175, "s": 167, "text": "Syntax:" }, { "code": null, "e": 206, "s": 175, "text": "<marquee bgcolor=\"colorname\" >" }, { "code": null, "e": 223, "s": 206, "text": "Attribute value:" }, { "code": null, "e": 279, "s": 223, "text": "color name: Define the background color of the marquee." }, { "code": null, "e": 288, "s": 279, "text": "Example:" }, { "code": null, "e": 293, "s": 288, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML Marquee bgcolor attribute</title> <style> .main { text-align: center; } .marq { padding-top: 30px; padding-bottom: 30px; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <marquee class=\"marq\" bgcolor=\"Green\" direction=\"left\" loop=\"\"> Background color is green </marquee> </body> </html>", "e": 808, "s": 293, "text": null }, { "code": null, "e": 822, "s": 808, "text": "Google Chrome" }, { "code": null, "e": 840, "s": 822, "text": "Internet Explorer" }, { "code": null, "e": 848, "s": 840, "text": "Firefox" }, { "code": null, "e": 861, "s": 848, "text": "Apple Safari" }, { "code": null, "e": 867, "s": 861, "text": "Opera" }, { "code": null, "e": 881, "s": 867, "text": "ManasChhabra2" }, { "code": null, "e": 897, "s": 881, "text": "HTML-Attributes" }, { "code": null, "e": 902, "s": 897, "text": "HTML" }, { "code": null, "e": 919, "s": 902, "text": "Web Technologies" }, { "code": null, "e": 924, "s": 919, "text": "HTML" }, { "code": null, "e": 1022, "s": 924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1046, "s": 1022, "text": "REST API (Introduction)" }, { "code": null, "e": 1074, "s": 1046, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 1113, "s": 1074, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1163, "s": 1113, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 1227, "s": 1163, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 1260, "s": 1227, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1321, "s": 1260, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1364, "s": 1321, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1436, "s": 1364, "text": "Differences between Functional Components and Class Components in React" } ]
What is GAV (Global as View)?
24 Apr, 2020 There are many databases and data sources that need integration. Almost every application has many sources of data that can be used to work together. Data integration involves integrating data from various sources and it has a single view over the sources. It is done to answer queries using the information that’s been combined. It can be physical and virtual. Physical data integration survives the data to the warehouse. Virtual integration keeps the data at the sources itself. Problem that arises due to the integration is the heterogeneity of data across the sources. There can be various heterogeneity issues while collecting data from the sources like semantic (different names of the attributes having similar data), communication, schema or data type. To overcome these issues, there are three models designed for integrating data, they are Federated databases, Data warehousing and Mediation. Global as View (GAV) :Global as view is one of the mediator types of view based data integration. Global schema act as a view over source schema i.e the mediator schema is described in terms of local schema. Given a query over the global schema, the mediator will follow the existing rules and templates to convert the query into source specific queries. It sends the new queries to wrappers for execution. Wrapper searches for all the possible expressions and how they can be combined to answer the given query. Applications : Enterprise Information Integration which makes separate databases that are owned by a company, and they work together.Scientific databases for example genome’s database.Integrating catalogs – that involves combining information of the product from every supplier. Enterprise Information Integration which makes separate databases that are owned by a company, and they work together. Scientific databases for example genome’s database. Integrating catalogs – that involves combining information of the product from every supplier. How it works :Mediation involves a mediator which is a virtual view of the data and it doesn’t store any data as the data is stored at sources. Schema from various sources is combined forming a virtual schema of mediator. Mapping takes place at query time. When a user queries, it is mapped to multiple other queries and each query is sent to the sources. Sources evaluate them and send back the results. Results are merged together and sent to the end user. This process is called mediation. It uses wrappers which are responsible for performing the mapping of the queries. They use templates (which are already created) who represent many queries and thus are made flexible. If the mediator query matches a template then the results are returned, else not. There are two types of mediator, they are Global as View and Local as View. We will discuss Global As View. Example :Let’s take an example to understand the working of GAV.To integrate catalogs. Suppose Zexmon (a company) wants to buy chips like DIPs and PGAs which has the same protocol. Global Schema – DIP ( manufacturer, model, protocol ) PGA ( manufacturer, model, protocol ) Local Schema –Every DIP and PGA manufacturer has relation (model, protocol). Zexmon will query the mediator. Mediator will start by querying every DIP manufacturers for the model and protocol pair. The wrapper will turn them to a triplet by adding attribute manufacturer. The protocols from all the sources for every DIP chips is returned to the mediator. Now the mediator starts querying all the PGA manufacturers using the protocol returned previously. Again the wrapper adds the manufacturer attribute to the ( model, protocol ) pair. And this is how the mediator retrieves the DIP and PGA chips which has similar protocols. This is turn helps zexmon to buy the desired chips. Advantages : Global as view is simpler to implement because you have the control over the working of the mediator.It is simple to design.The query answering approach is procedural and thus it is practiced by many Industrial Systems. Global as view is simpler to implement because you have the control over the working of the mediator. It is simple to design. The query answering approach is procedural and thus it is practiced by many Industrial Systems. Disadvantages : Since the global database is in terms of multiple sources, the global schema cannot frame any information which is absent in any of the source schemas.It is an overhead when it comes to adding new sources to the existing ones as it has to be ensured that the present sources are dependent on it i.e independent sources are rarely added. If the new source is added, the mappings also have to be changed.The view of the content that could be generated is narrowed.Removing a data source may also require a lot of work making it inflexible. Since the global database is in terms of multiple sources, the global schema cannot frame any information which is absent in any of the source schemas. It is an overhead when it comes to adding new sources to the existing ones as it has to be ensured that the present sources are dependent on it i.e independent sources are rarely added. If the new source is added, the mappings also have to be changed. The view of the content that could be generated is narrowed. Removing a data source may also require a lot of work making it inflexible. Picked DBMS Write From Home DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Introduction of DBMS (Database Management System) | Set 1 Difference between Clustered and Non-clustered index SQL Trigger | Student Database Introduction of B-Tree Convert integer to string in Python Convert string to integer in Python How to set input type date in dd-mm-yyyy format using HTML ? Python infinity Similarities and Difference between Java and C++
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Apr, 2020" }, { "code": null, "e": 452, "s": 28, "text": "There are many databases and data sources that need integration. Almost every application has many sources of data that can be used to work together. Data integration involves integrating data from various sources and it has a single view over the sources. It is done to answer queries using the information that’s been combined. It can be physical and virtual. Physical data integration survives the data to the warehouse." }, { "code": null, "e": 932, "s": 452, "text": "Virtual integration keeps the data at the sources itself. Problem that arises due to the integration is the heterogeneity of data across the sources. There can be various heterogeneity issues while collecting data from the sources like semantic (different names of the attributes having similar data), communication, schema or data type. To overcome these issues, there are three models designed for integrating data, they are Federated databases, Data warehousing and Mediation." }, { "code": null, "e": 1445, "s": 932, "text": "Global as View (GAV) :Global as view is one of the mediator types of view based data integration. Global schema act as a view over source schema i.e the mediator schema is described in terms of local schema. Given a query over the global schema, the mediator will follow the existing rules and templates to convert the query into source specific queries. It sends the new queries to wrappers for execution. Wrapper searches for all the possible expressions and how they can be combined to answer the given query." }, { "code": null, "e": 1460, "s": 1445, "text": "Applications :" }, { "code": null, "e": 1724, "s": 1460, "text": "Enterprise Information Integration which makes separate databases that are owned by a company, and they work together.Scientific databases for example genome’s database.Integrating catalogs – that involves combining information of the product from every supplier." }, { "code": null, "e": 1843, "s": 1724, "text": "Enterprise Information Integration which makes separate databases that are owned by a company, and they work together." }, { "code": null, "e": 1895, "s": 1843, "text": "Scientific databases for example genome’s database." }, { "code": null, "e": 1990, "s": 1895, "text": "Integrating catalogs – that involves combining information of the product from every supplier." }, { "code": null, "e": 2395, "s": 1990, "text": "How it works :Mediation involves a mediator which is a virtual view of the data and it doesn’t store any data as the data is stored at sources. Schema from various sources is combined forming a virtual schema of mediator. Mapping takes place at query time. When a user queries, it is mapped to multiple other queries and each query is sent to the sources. Sources evaluate them and send back the results." }, { "code": null, "e": 2857, "s": 2395, "text": "Results are merged together and sent to the end user. This process is called mediation. It uses wrappers which are responsible for performing the mapping of the queries. They use templates (which are already created) who represent many queries and thus are made flexible. If the mediator query matches a template then the results are returned, else not. There are two types of mediator, they are Global as View and Local as View. We will discuss Global As View." }, { "code": null, "e": 3038, "s": 2857, "text": "Example :Let’s take an example to understand the working of GAV.To integrate catalogs. Suppose Zexmon (a company) wants to buy chips like DIPs and PGAs which has the same protocol." }, { "code": null, "e": 3054, "s": 3038, "text": "Global Schema –" }, { "code": null, "e": 3131, "s": 3054, "text": "DIP ( manufacturer, model, protocol )\nPGA ( manufacturer, model, protocol ) " }, { "code": null, "e": 3208, "s": 3131, "text": "Local Schema –Every DIP and PGA manufacturer has relation (model, protocol)." }, { "code": null, "e": 3487, "s": 3208, "text": "Zexmon will query the mediator. Mediator will start by querying every DIP manufacturers for the model and protocol pair. The wrapper will turn them to a triplet by adding attribute manufacturer. The protocols from all the sources for every DIP chips is returned to the mediator." }, { "code": null, "e": 3811, "s": 3487, "text": "Now the mediator starts querying all the PGA manufacturers using the protocol returned previously. Again the wrapper adds the manufacturer attribute to the ( model, protocol ) pair. And this is how the mediator retrieves the DIP and PGA chips which has similar protocols. This is turn helps zexmon to buy the desired chips." }, { "code": null, "e": 3824, "s": 3811, "text": "Advantages :" }, { "code": null, "e": 4044, "s": 3824, "text": "Global as view is simpler to implement because you have the control over the working of the mediator.It is simple to design.The query answering approach is procedural and thus it is practiced by many Industrial Systems." }, { "code": null, "e": 4146, "s": 4044, "text": "Global as view is simpler to implement because you have the control over the working of the mediator." }, { "code": null, "e": 4170, "s": 4146, "text": "It is simple to design." }, { "code": null, "e": 4266, "s": 4170, "text": "The query answering approach is procedural and thus it is practiced by many Industrial Systems." }, { "code": null, "e": 4282, "s": 4266, "text": "Disadvantages :" }, { "code": null, "e": 4820, "s": 4282, "text": "Since the global database is in terms of multiple sources, the global schema cannot frame any information which is absent in any of the source schemas.It is an overhead when it comes to adding new sources to the existing ones as it has to be ensured that the present sources are dependent on it i.e independent sources are rarely added. If the new source is added, the mappings also have to be changed.The view of the content that could be generated is narrowed.Removing a data source may also require a lot of work making it inflexible." }, { "code": null, "e": 4972, "s": 4820, "text": "Since the global database is in terms of multiple sources, the global schema cannot frame any information which is absent in any of the source schemas." }, { "code": null, "e": 5224, "s": 4972, "text": "It is an overhead when it comes to adding new sources to the existing ones as it has to be ensured that the present sources are dependent on it i.e independent sources are rarely added. If the new source is added, the mappings also have to be changed." }, { "code": null, "e": 5285, "s": 5224, "text": "The view of the content that could be generated is narrowed." }, { "code": null, "e": 5361, "s": 5285, "text": "Removing a data source may also require a lot of work making it inflexible." }, { "code": null, "e": 5368, "s": 5361, "text": "Picked" }, { "code": null, "e": 5373, "s": 5368, "text": "DBMS" }, { "code": null, "e": 5389, "s": 5373, "text": "Write From Home" }, { "code": null, "e": 5394, "s": 5389, "text": "DBMS" }, { "code": null, "e": 5492, "s": 5394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5503, "s": 5492, "text": "CTE in SQL" }, { "code": null, "e": 5561, "s": 5503, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 5614, "s": 5561, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 5645, "s": 5614, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 5668, "s": 5645, "text": "Introduction of B-Tree" }, { "code": null, "e": 5704, "s": 5668, "text": "Convert integer to string in Python" }, { "code": null, "e": 5740, "s": 5704, "text": "Convert string to integer in Python" }, { "code": null, "e": 5801, "s": 5740, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 5817, "s": 5801, "text": "Python infinity" } ]
ResourceBundle and ListResourceBundle class in Java with Examples
12 Oct, 2021 The ResourceBundle and ListResourceBundle classes are part java.util package. These classes are designed to aid in the internationalization of programs. ResourceBundle: The class ResourceBundle is an abstract class. It defines methods that enable you to manage a collection of locale-sensitive resources. Resource bundles are identified by their family name. To the family name is added a two-character lowercase language code that specifies the language. We can also specify a country code after the language code. It is a two-character uppercase identifier and is preceded by an underscore when linked to a resource bundle name. Class Hierarchy: java.lang.Object ↳java.util.ResourceBundle Constructors: 1. ResourceBundle(): The default constructor which is mainly designed for use by the subclasses and the factory methods. public ResourceBundle() Methods: 1. clearCache(): This method deletes all resource bundles from the cache that were loaded by the default class loader. static final void clearCache() 2. containsKey(): This method returns true if the passed string argument is a key within the invoking resource bundle. boolean containsKey(String k) 3. getBundle(): This method loads the resource bundle with the given name and the specified locale. static final ResourceBundle getBundle(String familyName) static final ResourceBundle getBundle(String familyName, Locale loc) 4. setParent(): This method sets the passed bundle as parent of the invoking bundle. In case of a lookup, if the key is not found in the invoking object, then it is looked up in the parent bundle. protected void setParent(ResourceBundle parent) 5. getObject(): This method retrieves and returns the Object associated with the key passed as argument either from the current resource bundle or the parent. public final Object getObject(String key) 6. getHandleObject(): This method returns the object associated with the given key from the resource bundle. If no object is available null is returned. protected abstract Object handleGetObject(String key) 7. getString(): This method retrieves and returns the string associated with the key passed as argument either from the current resource bundle or the parent. public final String getString(String key) 8. getStringArray(): This method retrieves and returns the string array associated with the key passed as argument either from the current resource bundle or the parent. public final String[] getStringArray(String key) 9. getLocale(): This method returns the Locale associated with the current bundle. public Locale getLocale() 10. containsKey(): This method checks whether a given key exists within a resource bundle or its parent or not. public boolean containsKey(String key) 11. keySet(): This method returns the set of all the keys in the current bundle or its parent bundle. public Set keySet() ListResourceBundle: It is a subclass of ResourceBundle. It is an abstract class, which manages the resources in an array of key/value pairs. It adds only one new method getContents(), which must be implemented by every subclass. Constructors: 1. ListResourceBundle(): The default constructor to create an object. public ListResourceBundle() Methods: 1. getContents(): This method returns a two dimensional array that contains key/value pairs that represent resources. protected abstract Object[][] getContents() 2. handleGetObject(): This method returns the object associated with the key in the current bundle if it exists. public final Object handleGetObject(String key) 3. getKeys(): This method returns an enumeration of the keys in the resource bundle. public Enumeration getKeys() 4. handleKeySet(): This method returns the set of all the keys in the current resource bundle. protected Set handleKeySet() Example to demonstrate the use of a ResourceBundle Java import java.util.Locale;import java.util.ResourceBundle;import java.util.ListResourceBundle; class SampleRB extends ListResourceBundle { protected Object[][] getContents() { Object[][] resources = new Object[3][2]; resources[0][0] = "title"; resources[0][1] = "My Program"; resources[1][0] = "StopText"; resources[1][1] = "Stop"; resources[2][0] = "StartText"; resources[2][1] = "Start"; return resources; }}class SampleRB_de extends ListResourceBundle { protected Object[][] getContents() { Object[][] resources = new Object[3][2]; resources[0][0] = "title"; resources[0][1] = "Mein Program"; resources[1][0] = "StopText"; resources[1][1] = "Anschlag"; resources[2][0] = "StartText"; resources[2][1] = "Anfang"; return resources; }}public class LRBDemo { public static void main(String[] args) { ResourceBundle rd = ResourceBundle .getBundle("SampleRB", Locale.ENGLISH); System.out.println("English Version:"); System.out.println("String for Title key: " + rd.getString("title")); System.out.println("String for StopText key: " + rd.getString("StopText")); System.out.println("String for StartText key: " + rd.getString("StartText")); rd = ResourceBundle .getBundle("SampleRB", Locale.GERMAN); System.out.println("\nGerman Version"); System.out.println("String for Title key: " + rd.getString("title")); System.out.println("String for StopText key: " + rd.getString("StopText")); System.out.println("String for StartText key: " + rd.getString("StartText")); }} Output: English Version: String for Title key: My Program String for StopText key: Stop String for StartText key: Start German Version String for Title key: Mein Program String for StopText key: Anschlag String for StartText key: Anfang Reference: https://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.html surindertarika1234 sagartomar9927 Java - util package Java-Classes Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2021" }, { "code": null, "e": 182, "s": 28, "text": "The ResourceBundle and ListResourceBundle classes are part java.util package. These classes are designed to aid in the internationalization of programs. " }, { "code": null, "e": 661, "s": 182, "text": "ResourceBundle: The class ResourceBundle is an abstract class. It defines methods that enable you to manage a collection of locale-sensitive resources. Resource bundles are identified by their family name. To the family name is added a two-character lowercase language code that specifies the language. We can also specify a country code after the language code. It is a two-character uppercase identifier and is preceded by an underscore when linked to a resource bundle name. " }, { "code": null, "e": 680, "s": 661, "text": "Class Hierarchy: " }, { "code": null, "e": 723, "s": 680, "text": "java.lang.Object\n↳java.util.ResourceBundle" }, { "code": null, "e": 738, "s": 723, "text": "Constructors: " }, { "code": null, "e": 860, "s": 738, "text": "1. ResourceBundle(): The default constructor which is mainly designed for use by the subclasses and the factory methods. " }, { "code": null, "e": 884, "s": 860, "text": "public ResourceBundle()" }, { "code": null, "e": 894, "s": 884, "text": "Methods: " }, { "code": null, "e": 1014, "s": 894, "text": "1. clearCache(): This method deletes all resource bundles from the cache that were loaded by the default class loader. " }, { "code": null, "e": 1045, "s": 1014, "text": "static final void clearCache()" }, { "code": null, "e": 1165, "s": 1045, "text": "2. containsKey(): This method returns true if the passed string argument is a key within the invoking resource bundle. " }, { "code": null, "e": 1195, "s": 1165, "text": "boolean containsKey(String k)" }, { "code": null, "e": 1296, "s": 1195, "text": "3. getBundle(): This method loads the resource bundle with the given name and the specified locale. " }, { "code": null, "e": 1422, "s": 1296, "text": "static final ResourceBundle getBundle(String familyName)\nstatic final ResourceBundle getBundle(String familyName, Locale loc)" }, { "code": null, "e": 1620, "s": 1422, "text": "4. setParent(): This method sets the passed bundle as parent of the invoking bundle. In case of a lookup, if the key is not found in the invoking object, then it is looked up in the parent bundle. " }, { "code": null, "e": 1668, "s": 1620, "text": "protected void setParent(ResourceBundle parent)" }, { "code": null, "e": 1828, "s": 1668, "text": "5. getObject(): This method retrieves and returns the Object associated with the key passed as argument either from the current resource bundle or the parent. " }, { "code": null, "e": 1870, "s": 1828, "text": "public final Object getObject(String key)" }, { "code": null, "e": 2024, "s": 1870, "text": "6. getHandleObject(): This method returns the object associated with the given key from the resource bundle. If no object is available null is returned. " }, { "code": null, "e": 2078, "s": 2024, "text": "protected abstract Object handleGetObject(String key)" }, { "code": null, "e": 2238, "s": 2078, "text": "7. getString(): This method retrieves and returns the string associated with the key passed as argument either from the current resource bundle or the parent. " }, { "code": null, "e": 2280, "s": 2238, "text": "public final String getString(String key)" }, { "code": null, "e": 2451, "s": 2280, "text": "8. getStringArray(): This method retrieves and returns the string array associated with the key passed as argument either from the current resource bundle or the parent. " }, { "code": null, "e": 2500, "s": 2451, "text": "public final String[] getStringArray(String key)" }, { "code": null, "e": 2584, "s": 2500, "text": "9. getLocale(): This method returns the Locale associated with the current bundle. " }, { "code": null, "e": 2610, "s": 2584, "text": "public Locale getLocale()" }, { "code": null, "e": 2723, "s": 2610, "text": "10. containsKey(): This method checks whether a given key exists within a resource bundle or its parent or not. " }, { "code": null, "e": 2762, "s": 2723, "text": "public boolean containsKey(String key)" }, { "code": null, "e": 2865, "s": 2762, "text": "11. keySet(): This method returns the set of all the keys in the current bundle or its parent bundle. " }, { "code": null, "e": 2885, "s": 2865, "text": "public Set keySet()" }, { "code": null, "e": 3114, "s": 2885, "text": "ListResourceBundle: It is a subclass of ResourceBundle. It is an abstract class, which manages the resources in an array of key/value pairs. It adds only one new method getContents(), which must be implemented by every subclass." }, { "code": null, "e": 3200, "s": 3114, "text": "Constructors: 1. ListResourceBundle(): The default constructor to create an object. " }, { "code": null, "e": 3228, "s": 3200, "text": "public ListResourceBundle()" }, { "code": null, "e": 3238, "s": 3228, "text": "Methods: " }, { "code": null, "e": 3357, "s": 3238, "text": "1. getContents(): This method returns a two dimensional array that contains key/value pairs that represent resources. " }, { "code": null, "e": 3401, "s": 3357, "text": "protected abstract Object[][] getContents()" }, { "code": null, "e": 3515, "s": 3401, "text": "2. handleGetObject(): This method returns the object associated with the key in the current bundle if it exists. " }, { "code": null, "e": 3563, "s": 3515, "text": "public final Object handleGetObject(String key)" }, { "code": null, "e": 3648, "s": 3563, "text": "3. getKeys(): This method returns an enumeration of the keys in the resource bundle." }, { "code": null, "e": 3677, "s": 3648, "text": "public Enumeration getKeys()" }, { "code": null, "e": 3773, "s": 3677, "text": "4. handleKeySet(): This method returns the set of all the keys in the current resource bundle. " }, { "code": null, "e": 3802, "s": 3773, "text": "protected Set handleKeySet()" }, { "code": null, "e": 3855, "s": 3802, "text": "Example to demonstrate the use of a ResourceBundle " }, { "code": null, "e": 3860, "s": 3855, "text": "Java" }, { "code": "import java.util.Locale;import java.util.ResourceBundle;import java.util.ListResourceBundle; class SampleRB extends ListResourceBundle { protected Object[][] getContents() { Object[][] resources = new Object[3][2]; resources[0][0] = \"title\"; resources[0][1] = \"My Program\"; resources[1][0] = \"StopText\"; resources[1][1] = \"Stop\"; resources[2][0] = \"StartText\"; resources[2][1] = \"Start\"; return resources; }}class SampleRB_de extends ListResourceBundle { protected Object[][] getContents() { Object[][] resources = new Object[3][2]; resources[0][0] = \"title\"; resources[0][1] = \"Mein Program\"; resources[1][0] = \"StopText\"; resources[1][1] = \"Anschlag\"; resources[2][0] = \"StartText\"; resources[2][1] = \"Anfang\"; return resources; }}public class LRBDemo { public static void main(String[] args) { ResourceBundle rd = ResourceBundle .getBundle(\"SampleRB\", Locale.ENGLISH); System.out.println(\"English Version:\"); System.out.println(\"String for Title key: \" + rd.getString(\"title\")); System.out.println(\"String for StopText key: \" + rd.getString(\"StopText\")); System.out.println(\"String for StartText key: \" + rd.getString(\"StartText\")); rd = ResourceBundle .getBundle(\"SampleRB\", Locale.GERMAN); System.out.println(\"\\nGerman Version\"); System.out.println(\"String for Title key: \" + rd.getString(\"title\")); System.out.println(\"String for StopText key: \" + rd.getString(\"StopText\")); System.out.println(\"String for StartText key: \" + rd.getString(\"StartText\")); }}", "e": 5795, "s": 3860, "text": null }, { "code": null, "e": 5803, "s": 5795, "text": "Output:" }, { "code": null, "e": 6033, "s": 5803, "text": "English Version:\nString for Title key: My Program\nString for StopText key: Stop\nString for StartText key: Start\n\nGerman Version\nString for Title key: Mein Program\nString for StopText key: Anschlag\nString for StartText key: Anfang" }, { "code": null, "e": 6117, "s": 6033, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.html " }, { "code": null, "e": 6136, "s": 6117, "text": "surindertarika1234" }, { "code": null, "e": 6151, "s": 6136, "text": "sagartomar9927" }, { "code": null, "e": 6171, "s": 6151, "text": "Java - util package" }, { "code": null, "e": 6184, "s": 6171, "text": "Java-Classes" }, { "code": null, "e": 6189, "s": 6184, "text": "Java" }, { "code": null, "e": 6194, "s": 6189, "text": "Java" } ]
Count pairs with given sum | Practice | GeeksforGeeks
Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K. Example 1: Input: N = 4, K = 6 arr[] = {1, 5, 7, 1} Output: 2 Explanation: arr[0] + arr[1] = 1 + 5 = 6 and arr[1] + arr[3] = 5 + 1 = 6. Example 2: Input: N = 4, K = 2 arr[] = {1, 1, 1, 1} Output: 6 Explanation: Each 1 will produce sum 2 with any 1. Your Task: You don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 <= N <= 105 1 <= K <= 108 1 <= Arr[i] <= 106 0 vermaankush99110 hours ago // very simple code class Solution{ public: int getPairsCount(int arr[], int n, int k) { int count=0; unordered_map<int,int>map; for(int i=0; i<n; i++){ if(map.find(k-arr[i])!=map.end()) count+=map[k-arr[i]]; map[arr[i]]++; } return count; }}; 0 dhanakdeepak421 day ago class Solution { int getPairsCount(int[] a, int n, int sum) { // code here int c=0; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { if(!hm.containsKey(a[i])) { hm.put(a[i],0); } hm.put(a[i],hm.get(a[i])+1); } for(int i=0;i<n;i++) { if(hm.get(sum-a[i])!=null) { c=c+hm.get(sum-a[i]); } if(sum-a[i]==a[i]) { c--; } } return c/2; }} 0 aakasshuit1 day ago Easy Java Solution: int count = 0; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i<n;i++){ if(map.containsKey(k-arr[i])){ count+=map.get(k-arr[i]); } map.put(arr[i],map.getOrDefault(arr[i],0)+1); } return count; } 0 praveenanan44621 day ago class Solution{ public: int getPairsCount(int arr[], int n, int k) { // code here unordered_map<int, int >mapp; for(int i= 0;i<n;i++) { mapp[arr[i]]++; } int ans= 0; for(int i= 0;i<n;i++) { mapp[arr[i]]--; if(mapp.find(k-arr[i])!=mapp.end()) { ans +=mapp[k-arr[i]];// mapp[k-arr[i]] will give the //frequency of the particular element } } return ans; }}; 0 afredhussain693 days ago Java Soultion : int getPairsCount(int[] arr, int n, int k) { int pairCount=0; HashMap<Integer,Integer> pairs=new HashMap<>(); for(int i=0;i<n;i++){ if(pairs.containsKey(k-arr[i])){ pairCount=pairCount+pairs.get(k-arr[i]); } pairs.put(arr[i],pairs.getOrDefault(arr[i],0)+1); } return pairCount; } 0 dkbhargava1013 days ago Easy ad fast c++ solution in O(n) time and O(n) space takes 0.7/1.82 sec code: class Solution{ public: int getPairsCount(int arr[], int n, int k) { int ans=0; map<int,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(int i=0;i<n;i++){ mp[arr[i]]--; if(k-arr[i]>0){ ans=ans+mp[k-arr[i]];} } return ans; }}; 0 badgujarsachin833 days ago int getPairsCount(int arr[], int n, int k) { unordered_map<int,int> mp; int c=0; for(int i=0;i<n;i++){ if(mp.find(k-arr[i])!=mp.end()){ c+=mp[k-arr[i]]; } mp[arr[i]]++; } return c; } 0 hoodninja5 days ago Easy C++ solution int getPairsCount(int arr[], int n, int k) { // code here unordered_map<int,int> u; for(int i = 0;i<n;i++) u[arr[i]]++; int count = 0; for(int i=0;i<n;i++) { count = count+u[k-arr[i]]; if(k-arr[i] == arr[i]) count--; } return count/2; } +1 kumarr32035 days ago //c++ solution unordered_map<int ,int >m; int cnt=0; for(int i=0;i<n;i++) { if(m.find(k-a[i])!=m.end()) { cnt=cnt+m[k-a[i]]; } m[a[i]]++; } return cnt; -1 thebadguy6 days ago python solution def getPairsCount(self, arr, n, k): # code here count=0 seen={} for i in arr: c=k-i if c in seen: count+=seen[c] seen[i]=seen.get(i,0)+1 return count We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 361, "s": 238, "text": "Given an array of N integers, and an integer K, find the number of pairs of elements in the array whose sum is equal to K." }, { "code": null, "e": 373, "s": 361, "text": "\nExample 1:" }, { "code": null, "e": 501, "s": 373, "text": "Input:\nN = 4, K = 6\narr[] = {1, 5, 7, 1}\nOutput: 2\nExplanation: \narr[0] + arr[1] = 1 + 5 = 6 \nand arr[1] + arr[3] = 5 + 1 = 6.\n" }, { "code": null, "e": 513, "s": 501, "text": "\nExample 2:" }, { "code": null, "e": 616, "s": 513, "text": "Input:\nN = 4, K = 2\narr[] = {1, 1, 1, 1}\nOutput: 6\nExplanation: \nEach 1 will produce sum 2 with any 1." }, { "code": null, "e": 826, "s": 616, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getPairsCount() which takes arr[], n and k as input parameters and returns the number of pairs that have sum K." }, { "code": null, "e": 950, "s": 826, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n\nConstraints:\n1 <= N <= 105\n1 <= K <= 108\n1 <= Arr[i] <= 106" }, { "code": null, "e": 954, "s": 952, "text": "0" }, { "code": null, "e": 981, "s": 954, "text": "vermaankush99110 hours ago" }, { "code": null, "e": 1001, "s": 981, "text": "// very simple code" }, { "code": null, "e": 1303, "s": 1001, "text": "class Solution{ public: int getPairsCount(int arr[], int n, int k) { int count=0; unordered_map<int,int>map; for(int i=0; i<n; i++){ if(map.find(k-arr[i])!=map.end()) count+=map[k-arr[i]]; map[arr[i]]++; } return count; }}; " }, { "code": null, "e": 1305, "s": 1303, "text": "0" }, { "code": null, "e": 1329, "s": 1305, "text": "dhanakdeepak421 day ago" }, { "code": null, "e": 1740, "s": 1329, "text": "class Solution { int getPairsCount(int[] a, int n, int sum) { // code here int c=0; HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { if(!hm.containsKey(a[i])) { hm.put(a[i],0); } hm.put(a[i],hm.get(a[i])+1); } for(int i=0;i<n;i++) { if(hm.get(sum-a[i])!=null) { c=c+hm.get(sum-a[i]); } if(sum-a[i]==a[i]) { c--; } } return c/2; }} " }, { "code": null, "e": 1742, "s": 1740, "text": "0" }, { "code": null, "e": 1762, "s": 1742, "text": "aakasshuit1 day ago" }, { "code": null, "e": 1782, "s": 1762, "text": "Easy Java Solution:" }, { "code": null, "e": 2098, "s": 1784, "text": " int count = 0;\n HashMap<Integer, Integer> map = new HashMap<>();\n \n for(int i=0;i<n;i++){\n if(map.containsKey(k-arr[i])){\n count+=map.get(k-arr[i]);\n }\n map.put(arr[i],map.getOrDefault(arr[i],0)+1);\n }\n return count;\n }" }, { "code": null, "e": 2100, "s": 2098, "text": "0" }, { "code": null, "e": 2125, "s": 2100, "text": "praveenanan44621 day ago" }, { "code": null, "e": 2595, "s": 2125, "text": "class Solution{ public: int getPairsCount(int arr[], int n, int k) { // code here unordered_map<int, int >mapp; for(int i= 0;i<n;i++) { mapp[arr[i]]++; } int ans= 0; for(int i= 0;i<n;i++) { mapp[arr[i]]--; if(mapp.find(k-arr[i])!=mapp.end()) { ans +=mapp[k-arr[i]];// mapp[k-arr[i]] will give the //frequency of the particular element } } return ans; }};" }, { "code": null, "e": 2597, "s": 2595, "text": "0" }, { "code": null, "e": 2622, "s": 2597, "text": "afredhussain693 days ago" }, { "code": null, "e": 2640, "s": 2624, "text": "Java Soultion :" }, { "code": null, "e": 2998, "s": 2642, "text": "int getPairsCount(int[] arr, int n, int k) { int pairCount=0; HashMap<Integer,Integer> pairs=new HashMap<>(); for(int i=0;i<n;i++){ if(pairs.containsKey(k-arr[i])){ pairCount=pairCount+pairs.get(k-arr[i]); } pairs.put(arr[i],pairs.getOrDefault(arr[i],0)+1); } return pairCount; }" }, { "code": null, "e": 3000, "s": 2998, "text": "0" }, { "code": null, "e": 3024, "s": 3000, "text": "dkbhargava1013 days ago" }, { "code": null, "e": 3097, "s": 3024, "text": "Easy ad fast c++ solution in O(n) time and O(n) space takes 0.7/1.82 sec" }, { "code": null, "e": 3103, "s": 3097, "text": "code:" }, { "code": null, "e": 3419, "s": 3103, "text": "class Solution{ public: int getPairsCount(int arr[], int n, int k) { int ans=0; map<int,int> mp; for(int i=0;i<n;i++){ mp[arr[i]]++; } for(int i=0;i<n;i++){ mp[arr[i]]--; if(k-arr[i]>0){ ans=ans+mp[k-arr[i]];} } return ans; }};" }, { "code": null, "e": 3421, "s": 3419, "text": "0" }, { "code": null, "e": 3448, "s": 3421, "text": "badgujarsachin833 days ago" }, { "code": null, "e": 3737, "s": 3448, "text": " int getPairsCount(int arr[], int n, int k) {\n unordered_map<int,int> mp;\n int c=0;\n for(int i=0;i<n;i++){\n if(mp.find(k-arr[i])!=mp.end()){\n c+=mp[k-arr[i]];\n }\n mp[arr[i]]++;\n }\n return c;\n \n }" }, { "code": null, "e": 3739, "s": 3737, "text": "0" }, { "code": null, "e": 3759, "s": 3739, "text": "hoodninja5 days ago" }, { "code": null, "e": 3778, "s": 3759, "text": "Easy C++ solution " }, { "code": null, "e": 4157, "s": 3778, "text": " int getPairsCount(int arr[], int n, int k) {\n // code here\n unordered_map<int,int> u;\n for(int i = 0;i<n;i++)\n u[arr[i]]++;\n \n int count = 0;\n for(int i=0;i<n;i++)\n {\n count = count+u[k-arr[i]];\n if(k-arr[i] == arr[i])\n count--;\n }\n return count/2;\n }\n " }, { "code": null, "e": 4160, "s": 4157, "text": "+1" }, { "code": null, "e": 4181, "s": 4160, "text": "kumarr32035 days ago" }, { "code": null, "e": 4493, "s": 4181, "text": " //c++ solution\n \n \n \n unordered_map<int ,int >m;\n int cnt=0;\n for(int i=0;i<n;i++)\n {\n if(m.find(k-a[i])!=m.end())\n {\n cnt=cnt+m[k-a[i]];\n }\n m[a[i]]++;\n \n }\n return cnt;\n " }, { "code": null, "e": 4496, "s": 4493, "text": "-1" }, { "code": null, "e": 4516, "s": 4496, "text": "thebadguy6 days ago" }, { "code": null, "e": 4532, "s": 4516, "text": "python solution" }, { "code": null, "e": 4799, "s": 4534, "text": "def getPairsCount(self, arr, n, k):\n # code here\n count=0\n seen={} \n for i in arr:\n c=k-i\n if c in seen:\n count+=seen[c]\n seen[i]=seen.get(i,0)+1\n \n return count" }, { "code": null, "e": 4945, "s": 4799, "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": 4981, "s": 4945, "text": " Login to access your submissions. " }, { "code": null, "e": 4991, "s": 4981, "text": "\nProblem\n" }, { "code": null, "e": 5001, "s": 4991, "text": "\nContest\n" }, { "code": null, "e": 5064, "s": 5001, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5249, "s": 5064, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5533, "s": 5249, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 5679, "s": 5533, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 5756, "s": 5679, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 5797, "s": 5756, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 5825, "s": 5797, "text": "Disable browser extensions." }, { "code": null, "e": 5896, "s": 5825, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6083, "s": 5896, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
Difference between System Testing and Acceptance Testing
21 May, 2020 System Testing:System Testing is done to check whether the software or product meets the specified requirements or not. It is done by both testers and developers. It contains the Testings: System testing, Integration Testing. It is done through more positive and negative test cases. Acceptance Testing:Acceptance Testing is done after the system testing. It is used to check whether the software meets the customer requirements or not. Acceptance testing is used by testers, stakeholders as well as clients. It includes only Functional Testing and it contain two testing Alpha Testing and Beta Testing. Difference between System Testing and Acceptance Testing: ashushrma378 Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Functional vs Non Functional Requirements Differences between Verification and Validation Unit Testing | Software Testing Software Engineering | Classical Waterfall Model Software Requirement Specification (SRS) Format Difference between Spring and Spring Boot Software Engineering | Requirements Engineering Process Software Testing Life Cycle (STLC) Difference between IAAS, PAAS and SAAS Equivalence Partitioning Method
[ { "code": null, "e": 28, "s": 0, "text": "\n21 May, 2020" }, { "code": null, "e": 312, "s": 28, "text": "System Testing:System Testing is done to check whether the software or product meets the specified requirements or not. It is done by both testers and developers. It contains the Testings: System testing, Integration Testing. It is done through more positive and negative test cases." }, { "code": null, "e": 632, "s": 312, "text": "Acceptance Testing:Acceptance Testing is done after the system testing. It is used to check whether the software meets the customer requirements or not. Acceptance testing is used by testers, stakeholders as well as clients. It includes only Functional Testing and it contain two testing Alpha Testing and Beta Testing." }, { "code": null, "e": 690, "s": 632, "text": "Difference between System Testing and Acceptance Testing:" }, { "code": null, "e": 703, "s": 690, "text": "ashushrma378" }, { "code": null, "e": 720, "s": 703, "text": "Software Testing" }, { "code": null, "e": 741, "s": 720, "text": "Software Engineering" }, { "code": null, "e": 839, "s": 741, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 881, "s": 839, "text": "Functional vs Non Functional Requirements" }, { "code": null, "e": 929, "s": 881, "text": "Differences between Verification and Validation" }, { "code": null, "e": 961, "s": 929, "text": "Unit Testing | Software Testing" }, { "code": null, "e": 1010, "s": 961, "text": "Software Engineering | Classical Waterfall Model" }, { "code": null, "e": 1058, "s": 1010, "text": "Software Requirement Specification (SRS) Format" }, { "code": null, "e": 1100, "s": 1058, "text": "Difference between Spring and Spring Boot" }, { "code": null, "e": 1156, "s": 1100, "text": "Software Engineering | Requirements Engineering Process" }, { "code": null, "e": 1191, "s": 1156, "text": "Software Testing Life Cycle (STLC)" }, { "code": null, "e": 1230, "s": 1191, "text": "Difference between IAAS, PAAS and SAAS" } ]
Heap Sort
Heap sort is performed on the heap data structure. We know that heap is a complete binary tree. Heap tree can be of two types. Min-heap or max heap. For min heap the root element is minimum and for max heap the root is maximum. After forming a heap, we can delete an element from the root and send the last element to the root. After these swapping procedure, we need to re-heap the whole array. By deleting elements from root we can sort the whole array. Time Complexity: O(n log n) Space Complexity: O(1) Input: A list of unsorted data: 30 8 99 11 24 39 Output: Array before Sorting: 30 8 99 11 24 39 Array after Sorting: 8 11 24 30 39 99 heapify(array, size) Input βˆ’ An array of data, and the total number in the array Output βˆ’ The max heap using an array element Begin for i := 1 to size do node := i par := floor (node / 2) while par >= 1 do if array[par] < array[node] then swap array[par] with array[node] node := par par := floor (node / 2) done done End heapSort(array, size) Output βˆ’nbsp;sorted array Begin for i := n to 1 decrease by 1 do heapify(array, i) swap array[1] with array[i] done End #include<iostream> using namespace std; void display(int *array, int size) { for(int i = 1; i<=size; i++) cout << array[i] << " "; cout << endl; } void heapify(int *array, int n) { int i, par, l, r, node; // create max heap for(i = 1; i<= n; i++) { node = i; par = (int)node/2; while(par >= 1) { //if new node bigger than parent, then swap if(array[par] < array[node]) swap(array[par], array[node]); node = par; par = (int)node/2;//update parent to check } } } void heapSort(int *array, int n) { int i; for(i = n; i>= 1; i--) { heapify(array, i);//heapify each time swap(array[1], array[i]);//swap last element with first } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; int arr[n+1]; //effective index starts from i = 1. cout << "Enter elements:" << endl; for(int i = 1; i<=n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); heapSort(arr, n); cout << "Array after Sorting: "; display(arr, n); } Enter the number of elements: 6 Enter elements: 30 8 99 11 24 39 Array before Sorting: 30 8 99 11 24 39 Array after Sorting: 8 11 24 30 39 99
[ { "code": null, "e": 1643, "s": 1187, "text": "Heap sort is performed on the heap data structure. We know that heap is a complete binary tree. Heap tree can be of two types. Min-heap or max heap. For min heap the root element is minimum and for max heap the root is maximum. After forming a heap, we can delete an element from the root and send the last element to the root. After these swapping procedure, we need to re-heap the whole array. By deleting elements from root we can sort the whole array." }, { "code": null, "e": 1671, "s": 1643, "text": "Time Complexity: O(n log n)" }, { "code": null, "e": 1694, "s": 1671, "text": "Space Complexity: O(1)" }, { "code": null, "e": 1828, "s": 1694, "text": "Input:\nA list of unsorted data: 30 8 99 11 24 39\nOutput:\nArray before Sorting: 30 8 99 11 24 39\nArray after Sorting: 8 11 24 30 39 99" }, { "code": null, "e": 1849, "s": 1828, "text": "heapify(array, size)" }, { "code": null, "e": 1909, "s": 1849, "text": "Input βˆ’ An array of data, and the total number in the array" }, { "code": null, "e": 1954, "s": 1909, "text": "Output βˆ’ The max heap using an array element" }, { "code": null, "e": 2219, "s": 1954, "text": "Begin\n for i := 1 to size do\n node := i\n par := floor (node / 2)\n while par >= 1 do\n if array[par] < array[node] then\n swap array[par] with array[node]\n node := par\n par := floor (node / 2)\n done\n done\nEnd" }, { "code": null, "e": 2241, "s": 2219, "text": "heapSort(array, size)" }, { "code": null, "e": 2267, "s": 2241, "text": "Output βˆ’nbsp;sorted array" }, { "code": null, "e": 2379, "s": 2267, "text": "Begin\n for i := n to 1 decrease by 1 do\n heapify(array, i)\n swap array[1] with array[i]\n done\nEnd" }, { "code": null, "e": 3490, "s": 2379, "text": "#include<iostream>\nusing namespace std;\n\nvoid display(int *array, int size) {\n for(int i = 1; i<=size; i++)\n cout << array[i] << \" \";\n cout << endl;\n}\n\nvoid heapify(int *array, int n) {\n int i, par, l, r, node;\n // create max heap\n\n for(i = 1; i<= n; i++) {\n node = i; par = (int)node/2;\n while(par >= 1) {\n //if new node bigger than parent, then swap\n if(array[par] < array[node])\n swap(array[par], array[node]);\n node = par;\n par = (int)node/2;//update parent to check\n }\n }\n}\n\nvoid heapSort(int *array, int n) {\n int i;\n\n for(i = n; i>= 1; i--) {\n heapify(array, i);//heapify each time\n swap(array[1], array[i]);//swap last element with first\n }\n}\n\nint main() {\n int n;\n cout << \"Enter the number of elements: \";\n cin >> n;\n int arr[n+1]; //effective index starts from i = 1.\n cout << \"Enter elements:\" << endl;\n\n for(int i = 1; i<=n; i++) {\n cin >> arr[i];\n }\n\n cout << \"Array before Sorting: \";\n display(arr, n);\n heapSort(arr, n);\n cout << \"Array after Sorting: \";\n display(arr, n);\n}" }, { "code": null, "e": 3632, "s": 3490, "text": "Enter the number of elements: 6\nEnter elements:\n30 8 99 11 24 39\nArray before Sorting: 30 8 99 11 24 39\nArray after Sorting: 8 11 24 30 39 99" } ]
numpy.cos() in Python
09 Feb, 2021 numpy.cos(x[, out]) = ufunc β€˜cos’) : This mathematical function helps user to calculate trigonometric cosine for all x(being the array elements). Parameters : array : [array_like]elements are in radians. 2pi Radians = 360 degrees Return : An array with trigonometric cosine of x for all x i.e. array elements Code #1 : Working Python # Python program explaining# cos() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print ("Input array : \n", in_array) cos_Values = np.cos(in_array)print ("\nCosine values : \n", cos_Values) Output : Input array : [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793] Cosine values : [ 1.00000000e+00 6.12323400e-17 5.00000000e-01 -1.00000000e+00] Code #2 : Graphical representation Python # Python program showing# Graphical representation of# cos() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-(2*np.pi), 2*np.pi, 20)out_array = np.cos(in_array) print("in_array : ", in_array)print("\nout_array : ", out_array) # red for numpy.cos()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.cos()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : in_array : [-6.28318531 -5.62179738 -4.96040945 -4.29902153 -3.6376336 -2.97624567 -2.31485774 -1.65346982 -0.99208189 -0.33069396 0.33069396 0.99208189 1.65346982 2.31485774 2.97624567 3.6376336 4.29902153 4.96040945 5.62179738 6.28318531] out_array : [ 1. 0.78914051 0.24548549 -0.40169542 -0.87947375 -0.9863613 -0.67728157 -0.08257935 0.54694816 0.94581724 0.94581724 0.54694816 -0.08257935 -0.67728157 -0.9863613 -0.87947375 -0.40169542 0.24548549 0.78914051 1. ] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.cos.html#numpy.cos . AshokJaiswal Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Feb, 2021" }, { "code": null, "e": 189, "s": 28, "text": "numpy.cos(x[, out]) = ufunc β€˜cos’) : This mathematical function helps user to calculate trigonometric cosine for all x(being the array elements). Parameters : " }, { "code": null, "e": 236, "s": 189, "text": "array : [array_like]elements are in radians. " }, { "code": null, "e": 264, "s": 238, "text": "2pi Radians = 360 degrees" }, { "code": null, "e": 275, "s": 264, "text": "Return : " }, { "code": null, "e": 347, "s": 275, "text": "An array with trigonometric cosine \nof x for all x i.e. array elements " }, { "code": null, "e": 369, "s": 347, "text": " Code #1 : Working " }, { "code": null, "e": 376, "s": 369, "text": "Python" }, { "code": "# Python program explaining# cos() function import numpy as npimport math in_array = [0, math.pi / 2, np.pi / 3, np.pi]print (\"Input array : \\n\", in_array) cos_Values = np.cos(in_array)print (\"\\nCosine values : \\n\", cos_Values)", "e": 604, "s": 376, "text": null }, { "code": null, "e": 615, "s": 604, "text": "Output : " }, { "code": null, "e": 783, "s": 615, "text": "Input array : \n [0, 1.5707963267948966, 1.0471975511965976, 3.141592653589793]\n\nCosine values : \n [ 1.00000000e+00 6.12323400e-17 5.00000000e-01 -1.00000000e+00]" }, { "code": null, "e": 822, "s": 783, "text": " Code #2 : Graphical representation " }, { "code": null, "e": 829, "s": 822, "text": "Python" }, { "code": "# Python program showing# Graphical representation of# cos() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(-(2*np.pi), 2*np.pi, 20)out_array = np.cos(in_array) print(\"in_array : \", in_array)print(\"\\nout_array : \", out_array) # red for numpy.cos()plt.plot(in_array, out_array, color = 'red', marker = \"o\")plt.title(\"numpy.cos()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show()", "e": 1234, "s": 829, "text": null }, { "code": null, "e": 1245, "s": 1234, "text": "Output : " }, { "code": null, "e": 1760, "s": 1245, "text": "in_array : [-6.28318531 -5.62179738 -4.96040945 -4.29902153 -3.6376336 -2.97624567\n -2.31485774 -1.65346982 -0.99208189 -0.33069396 0.33069396 0.99208189\n 1.65346982 2.31485774 2.97624567 3.6376336 4.29902153 4.96040945\n 5.62179738 6.28318531]\n\nout_array : [ 1. 0.78914051 0.24548549 -0.40169542 -0.87947375 -0.9863613\n -0.67728157 -0.08257935 0.54694816 0.94581724 0.94581724 0.54694816\n -0.08257935 -0.67728157 -0.9863613 -0.87947375 -0.40169542 0.24548549\n 0.78914051 1. ]" }, { "code": null, "e": 1860, "s": 1762, "text": "References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.cos.html#numpy.cos . " }, { "code": null, "e": 1873, "s": 1860, "text": "AshokJaiswal" }, { "code": null, "e": 1908, "s": 1873, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1921, "s": 1908, "text": "Python-numpy" }, { "code": null, "e": 1928, "s": 1921, "text": "Python" }, { "code": null, "e": 2026, "s": 1928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2044, "s": 2026, "text": "Python Dictionary" }, { "code": null, "e": 2086, "s": 2044, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2108, "s": 2086, "text": "Enumerate() in Python" }, { "code": null, "e": 2143, "s": 2108, "text": "Read a file line by line in Python" }, { "code": null, "e": 2169, "s": 2143, "text": "Python String | replace()" }, { "code": null, "e": 2201, "s": 2169, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2230, "s": 2201, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2260, "s": 2230, "text": "Iterate over a list in Python" }, { "code": null, "e": 2287, "s": 2260, "text": "Python Classes and Objects" } ]
Arduino - Variables & Constants
Before we start explaining the variable types, a very important subject we need to make sure, you fully understand is called the variable scope. Variables in C programming language, which Arduino uses, have a property called scope. A scope is a region of the program and there are three places where variables can be declared. They are βˆ’ Inside a function or a block, which is called local variables. In the definition of function parameters, which is called formal parameters. Outside of all functions, which is called global variables. Variables that are declared inside a function or block are local variables. They can be used only by the statements that are inside that function or block of code. Local variables are not known to function outside their own. Following is the example using local variables βˆ’ Void setup () { } Void loop () { int x , y ; int z ; Local variable declaration x = 0; y = 0; actual initialization z = 10; } Global variables are defined outside of all the functions, usually at the top of the program. The global variables will hold their value throughout the life-time of your program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. The following example uses global and local variables βˆ’ Int T , S ; float c = 0 ; Global variable declaration Void setup () { } Void loop () { int x , y ; int z ; Local variable declaration x = 0; y = 0; actual initialization z = 10;
[ { "code": null, "e": 3149, "s": 3004, "text": "Before we start explaining the variable types, a very important subject we need to make sure, you fully understand is called the variable scope." }, { "code": null, "e": 3342, "s": 3149, "text": "Variables in C programming language, which Arduino uses, have a property called scope. A scope is a region of the program and there are three places where variables can be declared. They are βˆ’" }, { "code": null, "e": 3405, "s": 3342, "text": "Inside a function or a block, which is called local variables." }, { "code": null, "e": 3482, "s": 3405, "text": "In the definition of function parameters, which is called formal parameters." }, { "code": null, "e": 3542, "s": 3482, "text": "Outside of all functions, which is called global variables." }, { "code": null, "e": 3816, "s": 3542, "text": "Variables that are declared inside a function or block are local variables. They can be used only by the statements that are inside that function or block of code. Local variables are not known to function outside their own. Following is the example using local variables βˆ’" }, { "code": null, "e": 3959, "s": 3816, "text": "Void setup () {\n\n}\n\nVoid loop () {\n int x , y ;\n int z ; Local variable declaration\n x = 0;\n y = 0; actual initialization\n z = 10;\n}" }, { "code": null, "e": 4138, "s": 3959, "text": "Global variables are defined outside of all the functions, usually at the top of the program. The global variables will hold their value throughout the life-time of your program." }, { "code": null, "e": 4291, "s": 4138, "text": "A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration." }, { "code": null, "e": 4347, "s": 4291, "text": "The following example uses global and local variables βˆ’" } ]
PImpl Idiom in C++ with Examples
27 Dec, 2021 When changes are made to a header file, all sources including it needs to be recompiled. In large projects and libraries, it can cause build time issues due to the fact that even when a small change to the implementation is made everyone has to wait some time until they compile their code. One way to solve this problem is by using the PImpl Idiom, which hides the implementation in the headers and includes an interface file that compiles instantly. The PImpl Idiom (Pointer to IMPLementation) is a technique used for separating implementation from the interface. It minimizes header exposure and helps programmers to reduce build dependencies by moving the private data members in a separate class and accessing them through an opaque pointer. How to implement: Create a separate class ( or struct ) for implementationPut all private members from the header to that class.Define an Implementation class ( Impl ) in the header file.In the header file create a forward declaration (a pointer), pointing at the implementation class.Define a destructor and a copy/assignment operators. Create a separate class ( or struct ) for implementation Put all private members from the header to that class. Define an Implementation class ( Impl ) in the header file. In the header file create a forward declaration (a pointer), pointing at the implementation class. Define a destructor and a copy/assignment operators. The reason to declare explicitly a destructor is that when compiling, the smart pointer ( std::unique_ptr ) checks if in the definition of the type exists a visible destructor and throws a compilation error if it’s only forward declared. Using a smart pointer is a better approach since the pointer takes control over the life cycle of the PImpl. Example: The class definition in the header file included is the public interface of the class. We define a unique pointer instead of a raw one because the object of the interface type is responsible for the lifetime of the object. Since std::unique_ptr is a complete type it requires a user-declared destructor and copy/assignment operators in order for the implementation class to be complete. The pimpl approach is transparent from the user’s viewpoint. Changes made to the IMPLementation structure, internally, affect only the file containing it (User.cpp). This means that the user does not need to recompile in order for these changes to get applied. Header file Implementation file /* |INTERFACE| User.h file */ #pragma once#include <memory> // PImpl#include <string>using namespace std; class User {public: // Constructor and Destructors ~User(); User(string name); // Assignment Operator and Copy Constructor User(const User& other); User& operator=(User rhs); // Getter int getSalary(); // Setter void setSalary(int); private: // Internal implementation class class Impl; // Pointer to the internal implementation unique_ptr<Impl> pimpl;}; /* |IMPLEMENTATION| User.cpp file */ #include "User.h"#include <iostream>using namespace std; struct User::Impl { Impl(string name) : name(move(name)){}; ~Impl(); void welcomeMessage() { cout << "Welcome, " << name << endl; } string name; int salary = -1;}; // Constructor connected with our Impl structureUser::User(string name) : pimpl(new Impl(move(name))){ pimpl->welcomeMessage();} // Default ConstructorUser::~User() = default; // Assignment operator and Copy constructor User::User(const User& other) : pimpl(new Impl(*other.pimpl)){} User& User::operator=(User rhs){ swap(pimpl, rhs.pimpl); return *this;} // Getter and setterint User::getSalary(){ return pimpl->salary;} void User::setSalary(int salary){ pimpl->salary = salary; cout << "Salary set to " << salary << endl;} Advantages of PImpl: Binary Compatibility: The binary interface is independent of the private fields. Making changes to the implementation would not break the dependent code. Compilation time: Compilation time drops due to the fact that only the implementation file needs to be rebuilt instead of every client recompiling his file. Data Hiding: Can easily hide certain internal details such as implementation techniques and other libraries used to implement the public interface. Disadvantages of PImpl: Memory Management: Possible increase in memory usage due to more memory allocation than with the default structure which can be critical in embedded software development. Maintenance Effort: The maintenance is becoming more complex due to the additional class in order to use pimpl and additional pointer indirection (Interface can be used only via pointer/reference). Inheritance: Hidden implementation cannot be inherited, although a class PImpl can. Reference: https://en.cppreference.com/w/cpp/language/pimpl anikakapoor bh5peo6qcfmksnh36kx7ugqdzds1gs5q8nv43m4j C++ Programming Language CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Polymorphism in C++ Queue in C++ Standard Template Library (STL) List in C++ Standard Template Library (STL) Command line arguments in C/C++ Exception Handling in C++ Modulo Operator (%) in C/C++ with Examples Arrow operator -> in C/C++ with Examples Differences between Procedural and Object Oriented Programming Advantages and Disadvantages of OOP Difference between while and do-while loop in C, C++, Java
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Dec, 2021" }, { "code": null, "e": 506, "s": 54, "text": "When changes are made to a header file, all sources including it needs to be recompiled. In large projects and libraries, it can cause build time issues due to the fact that even when a small change to the implementation is made everyone has to wait some time until they compile their code. One way to solve this problem is by using the PImpl Idiom, which hides the implementation in the headers and includes an interface file that compiles instantly." }, { "code": null, "e": 801, "s": 506, "text": "The PImpl Idiom (Pointer to IMPLementation) is a technique used for separating implementation from the interface. It minimizes header exposure and helps programmers to reduce build dependencies by moving the private data members in a separate class and accessing them through an opaque pointer." }, { "code": null, "e": 820, "s": 801, "text": "How to implement: " }, { "code": null, "e": 1140, "s": 820, "text": "Create a separate class ( or struct ) for implementationPut all private members from the header to that class.Define an Implementation class ( Impl ) in the header file.In the header file create a forward declaration (a pointer), pointing at the implementation class.Define a destructor and a copy/assignment operators." }, { "code": null, "e": 1197, "s": 1140, "text": "Create a separate class ( or struct ) for implementation" }, { "code": null, "e": 1252, "s": 1197, "text": "Put all private members from the header to that class." }, { "code": null, "e": 1312, "s": 1252, "text": "Define an Implementation class ( Impl ) in the header file." }, { "code": null, "e": 1411, "s": 1312, "text": "In the header file create a forward declaration (a pointer), pointing at the implementation class." }, { "code": null, "e": 1464, "s": 1411, "text": "Define a destructor and a copy/assignment operators." }, { "code": null, "e": 1702, "s": 1464, "text": "The reason to declare explicitly a destructor is that when compiling, the smart pointer ( std::unique_ptr ) checks if in the definition of the type exists a visible destructor and throws a compilation error if it’s only forward declared." }, { "code": null, "e": 1811, "s": 1702, "text": "Using a smart pointer is a better approach since the pointer takes control over the life cycle of the PImpl." }, { "code": null, "e": 1821, "s": 1811, "text": "Example: " }, { "code": null, "e": 1908, "s": 1821, "text": "The class definition in the header file included is the public interface of the class." }, { "code": null, "e": 2044, "s": 1908, "text": "We define a unique pointer instead of a raw one because the object of the interface type is responsible for the lifetime of the object." }, { "code": null, "e": 2208, "s": 2044, "text": "Since std::unique_ptr is a complete type it requires a user-declared destructor and copy/assignment operators in order for the implementation class to be complete." }, { "code": null, "e": 2469, "s": 2208, "text": "The pimpl approach is transparent from the user’s viewpoint. Changes made to the IMPLementation structure, internally, affect only the file containing it (User.cpp). This means that the user does not need to recompile in order for these changes to get applied." }, { "code": null, "e": 2481, "s": 2469, "text": "Header file" }, { "code": null, "e": 2501, "s": 2481, "text": "Implementation file" }, { "code": "/* |INTERFACE| User.h file */ #pragma once#include <memory> // PImpl#include <string>using namespace std; class User {public: // Constructor and Destructors ~User(); User(string name); // Assignment Operator and Copy Constructor User(const User& other); User& operator=(User rhs); // Getter int getSalary(); // Setter void setSalary(int); private: // Internal implementation class class Impl; // Pointer to the internal implementation unique_ptr<Impl> pimpl;};", "e": 3010, "s": 2501, "text": null }, { "code": "/* |IMPLEMENTATION| User.cpp file */ #include \"User.h\"#include <iostream>using namespace std; struct User::Impl { Impl(string name) : name(move(name)){}; ~Impl(); void welcomeMessage() { cout << \"Welcome, \" << name << endl; } string name; int salary = -1;}; // Constructor connected with our Impl structureUser::User(string name) : pimpl(new Impl(move(name))){ pimpl->welcomeMessage();} // Default ConstructorUser::~User() = default; // Assignment operator and Copy constructor User::User(const User& other) : pimpl(new Impl(*other.pimpl)){} User& User::operator=(User rhs){ swap(pimpl, rhs.pimpl); return *this;} // Getter and setterint User::getSalary(){ return pimpl->salary;} void User::setSalary(int salary){ pimpl->salary = salary; cout << \"Salary set to \" << salary << endl;}", "e": 3876, "s": 3010, "text": null }, { "code": null, "e": 3897, "s": 3876, "text": "Advantages of PImpl:" }, { "code": null, "e": 4051, "s": 3897, "text": "Binary Compatibility: The binary interface is independent of the private fields. Making changes to the implementation would not break the dependent code." }, { "code": null, "e": 4208, "s": 4051, "text": "Compilation time: Compilation time drops due to the fact that only the implementation file needs to be rebuilt instead of every client recompiling his file." }, { "code": null, "e": 4356, "s": 4208, "text": "Data Hiding: Can easily hide certain internal details such as implementation techniques and other libraries used to implement the public interface." }, { "code": null, "e": 4380, "s": 4356, "text": "Disadvantages of PImpl:" }, { "code": null, "e": 4551, "s": 4380, "text": "Memory Management: Possible increase in memory usage due to more memory allocation than with the default structure which can be critical in embedded software development." }, { "code": null, "e": 4749, "s": 4551, "text": "Maintenance Effort: The maintenance is becoming more complex due to the additional class in order to use pimpl and additional pointer indirection (Interface can be used only via pointer/reference)." }, { "code": null, "e": 4833, "s": 4749, "text": "Inheritance: Hidden implementation cannot be inherited, although a class PImpl can." }, { "code": null, "e": 4893, "s": 4833, "text": "Reference: https://en.cppreference.com/w/cpp/language/pimpl" }, { "code": null, "e": 4905, "s": 4893, "text": "anikakapoor" }, { "code": null, "e": 4946, "s": 4905, "text": "bh5peo6qcfmksnh36kx7ugqdzds1gs5q8nv43m4j" }, { "code": null, "e": 4950, "s": 4946, "text": "C++" }, { "code": null, "e": 4971, "s": 4950, "text": "Programming Language" }, { "code": null, "e": 4975, "s": 4971, "text": "CPP" }, { "code": null, "e": 5073, "s": 4975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5093, "s": 5073, "text": "Polymorphism in C++" }, { "code": null, "e": 5138, "s": 5093, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5182, "s": 5138, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 5214, "s": 5182, "text": "Command line arguments in C/C++" }, { "code": null, "e": 5240, "s": 5214, "text": "Exception Handling in C++" }, { "code": null, "e": 5283, "s": 5240, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 5324, "s": 5283, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 5387, "s": 5324, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 5423, "s": 5387, "text": "Advantages and Disadvantages of OOP" } ]
Difference Between notify() and notifyAll() in Java
21 Dec, 2021 The notify() and notifyAll() methods with wait() methods are used for communication between the threads. A thread that goes into waiting for state by calling the wait() method will be in waiting for the state until any other thread calls either notify() or notifyAll() method on the same object. notify(): The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread. notifyAll(): The notifyAll() wakes up all threads that are waiting on this object’s monitor. A thread waits on an object’s monitor by calling one of the wait methods. The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object. Now the question is both notify() and notifyAll() the method is used to give notification to the waiting thread, then what is the difference between them or where we should use notify() method and where we should go for the notifyAll() method? Let’s understand how the notify() method behaves: Java // Java program to illustrate the// behaviour of notify() methodclass Geek1 extends Thread { public void run() { synchronized (this) { System.out.println( Thread.currentThread().getName() + "...starts"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + "...notified"); } }}class Geek2 extends Thread { Geek1 geeks1; Geek2(Geek1 geeks1){ this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + "...starts"); try { this.geeks1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + "...notified"); } }}class Geek3 extends Thread { Geek1 geeks1; Geek3(Geek1 geeks1) { this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + "...starts"); this.geeks1.notify(); System.out.println( Thread.currentThread().getName() + "...notified"); } }}class MainClass { public static void main(String[] args) throws InterruptedException { Geek1 geeks1 = new Geek1(); Geek2 geeks2 = new Geek2(geeks1); Geek3 geeks3 = new Geek3(geeks1); Thread t1 = new Thread(geeks1, "Thread-1"); Thread t2 = new Thread(geeks2, "Thread-2"); Thread t3 = new Thread(geeks3, "Thread-3"); t1.start(); t2.start(); Thread.sleep(100); t3.start(); }} Output: Thread-1...start Thread-2...starts Thread-3...starts Thread-3...notified Thread-1...notified Lets understand how notifyAll() method behaves: Java // Java program to illustrate the// behavior of notifyAll() method class Geek1 extends Thread { public void run() { synchronized (this) { System.out.println( Thread.currentThread().getName() + "...starts"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + "...notified"); } }}class Geek2 extends Thread { Geek1 geeks1; Geek2(Geek1 geeks1){ this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + "...starts"); try { this.geeks1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + "...notified"); } }}class Geek3 extends Thread { Geek1 geeks1; Geek3(Geek1 geeks1) { this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + "...starts"); this.geeks1.notifyAll(); System.out.println( Thread.currentThread().getName() + "...notified"); } }}class MainClass { public static void main(String[] args) throws InterruptedException { Geek1 geeks1 = new Geek1(); Geek2 geeks2 = new Geek2(geeks1); Geek3 geeks3 = new Geek3(geeks1); Thread t1 = new Thread(geeks1, "Thread-1"); Thread t2 = new Thread(geeks2, "Thread-2"); Thread t3 = new Thread(geeks3, "Thread-3"); t1.start(); t2.start(); Thread.sleep(100); t3.start(); }} Thread-1...starts Thread-2...starts Thread-3...starts Thread-3...notified Thread-1...notified Thread-2...notified In the case of mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can’t do anything anyway. In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time. A maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource; for these, we should go for notifyAll(). Let’s say we have a producer thread and a consumer thread. Each β€œpacket” produced by the producer should be consumed by a consumer. The consumer puts something in a queue and then calls notify(). We want to have a notification when a lengthy process has finished. You want a beep and a screen update. The process performs notifyAll() to notify both the beeping thread and the screen-update-thread. This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nishkarshgandhi Java-Multithreading Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n21 Dec, 2021" }, { "code": null, "e": 351, "s": 54, "text": "The notify() and notifyAll() methods with wait() methods are used for communication between the threads. A thread that goes into waiting for state by calling the wait() method will be in waiting for the state until any other thread calls either notify() or notifyAll() method on the same object. " }, { "code": null, "e": 621, "s": 351, "text": "notify(): The notify() method is defined in the Object class, which is Java’s top-level class. It’s used to wake up only one thread that’s waiting for an object, and that thread then begins execution. The thread class notify() method is used to wake up a single thread." }, { "code": null, "e": 900, "s": 621, "text": "notifyAll(): The notifyAll() wakes up all threads that are waiting on this object’s monitor. A thread waits on an object’s monitor by calling one of the wait methods. The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object." }, { "code": null, "e": 1145, "s": 900, "text": "Now the question is both notify() and notifyAll() the method is used to give notification to the waiting thread, then what is the difference between them or where we should use notify() method and where we should go for the notifyAll() method? " }, { "code": null, "e": 1195, "s": 1145, "text": "Let’s understand how the notify() method behaves:" }, { "code": null, "e": 1200, "s": 1195, "text": "Java" }, { "code": "// Java program to illustrate the// behaviour of notify() methodclass Geek1 extends Thread { public void run() { synchronized (this) { System.out.println( Thread.currentThread().getName() + \"...starts\"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + \"...notified\"); } }}class Geek2 extends Thread { Geek1 geeks1; Geek2(Geek1 geeks1){ this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + \"...starts\"); try { this.geeks1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + \"...notified\"); } }}class Geek3 extends Thread { Geek1 geeks1; Geek3(Geek1 geeks1) { this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + \"...starts\"); this.geeks1.notify(); System.out.println( Thread.currentThread().getName() + \"...notified\"); } }}class MainClass { public static void main(String[] args) throws InterruptedException { Geek1 geeks1 = new Geek1(); Geek2 geeks2 = new Geek2(geeks1); Geek3 geeks3 = new Geek3(geeks1); Thread t1 = new Thread(geeks1, \"Thread-1\"); Thread t2 = new Thread(geeks2, \"Thread-2\"); Thread t3 = new Thread(geeks3, \"Thread-3\"); t1.start(); t2.start(); Thread.sleep(100); t3.start(); }}", "e": 3213, "s": 1200, "text": null }, { "code": null, "e": 3222, "s": 3213, "text": "Output: " }, { "code": null, "e": 3315, "s": 3222, "text": "Thread-1...start\nThread-2...starts\nThread-3...starts\nThread-3...notified\nThread-1...notified" }, { "code": null, "e": 3365, "s": 3315, "text": "Lets understand how notifyAll() method behaves: " }, { "code": null, "e": 3370, "s": 3365, "text": "Java" }, { "code": "// Java program to illustrate the// behavior of notifyAll() method class Geek1 extends Thread { public void run() { synchronized (this) { System.out.println( Thread.currentThread().getName() + \"...starts\"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + \"...notified\"); } }}class Geek2 extends Thread { Geek1 geeks1; Geek2(Geek1 geeks1){ this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + \"...starts\"); try { this.geeks1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( Thread.currentThread().getName() + \"...notified\"); } }}class Geek3 extends Thread { Geek1 geeks1; Geek3(Geek1 geeks1) { this.geeks1 = geeks1; } public void run() { synchronized (this.geeks1) { System.out.println( Thread.currentThread().getName() + \"...starts\"); this.geeks1.notifyAll(); System.out.println( Thread.currentThread().getName() + \"...notified\"); } }}class MainClass { public static void main(String[] args) throws InterruptedException { Geek1 geeks1 = new Geek1(); Geek2 geeks2 = new Geek2(geeks1); Geek3 geeks3 = new Geek3(geeks1); Thread t1 = new Thread(geeks1, \"Thread-1\"); Thread t2 = new Thread(geeks2, \"Thread-2\"); Thread t3 = new Thread(geeks3, \"Thread-3\"); t1.start(); t2.start(); Thread.sleep(100); t3.start(); }}", "e": 5392, "s": 3370, "text": null }, { "code": null, "e": 5506, "s": 5392, "text": "Thread-1...starts\nThread-2...starts\nThread-3...starts\nThread-3...notified\nThread-1...notified\nThread-2...notified" }, { "code": null, "e": 5853, "s": 5506, "text": "In the case of mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use notify(). Properly implemented, you could use notifyAll() in this situation as well, but you would unnecessarily wake threads that can’t do anything anyway." }, { "code": null, "e": 6182, "s": 5853, "text": "In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use notifyAll() to wake up all waiting threads at the same time." }, { "code": null, "e": 6365, "s": 6182, "text": "A maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource; for these, we should go for notifyAll()." }, { "code": null, "e": 6561, "s": 6365, "text": "Let’s say we have a producer thread and a consumer thread. Each β€œpacket” produced by the producer should be consumed by a consumer. The consumer puts something in a queue and then calls notify()." }, { "code": null, "e": 6763, "s": 6561, "text": "We want to have a notification when a lengthy process has finished. You want a beep and a screen update. The process performs notifyAll() to notify both the beeping thread and the screen-update-thread." }, { "code": null, "e": 7194, "s": 6763, "text": "This article is contributed by Bishal Kumar Dubey. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7210, "s": 7194, "text": "nishkarshgandhi" }, { "code": null, "e": 7230, "s": 7210, "text": "Java-Multithreading" }, { "code": null, "e": 7249, "s": 7230, "text": "Difference Between" }, { "code": null, "e": 7254, "s": 7249, "text": "Java" }, { "code": null, "e": 7259, "s": 7254, "text": "Java" }, { "code": null, "e": 7357, "s": 7259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7418, "s": 7357, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7486, "s": 7418, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 7535, "s": 7486, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 7590, "s": 7535, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 7656, "s": 7590, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 7671, "s": 7656, "text": "Arrays in Java" }, { "code": null, "e": 7715, "s": 7671, "text": "Split() String method in Java with examples" }, { "code": null, "e": 7751, "s": 7715, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 7802, "s": 7751, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Remove common elements from two list in Python
19 Dec, 2021 Given two lists, the task is to write a Python program to remove all the common elements of two lists. Examples: Input : list1 = [1, 2, 3, 4, 5] list2 = [4, 5, 6, 7, 8,] Output : list1 = [1, 2, 3] list2 = [6, 7, 8] Explanation: Lists after removing common elements of both the lists i.e, 4 and 5. Input : list1 = [1, 2, 3] list2 = [1, 2, 3] Output : list1 = [] list2 = [] Explanation: They have all the elements in common in between them. The remove() method removes the first matching element (which is passed as an argument) from the list. Python3 # Python program to remove common elements# in the two lists using remove methoddef remove_common(a, b): for i in a[:]: if i in b: a.remove(i) b.remove(i) print("list1 : ", a) print("list2 : ", b) if __name__ == "__main__": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b) Output: list1 : [1, 2, 3] list2 : [6, 7, 8] List comprehension gives a shorter syntax when you want to create a new list based on the elements of the existing list. Python3 # Python program to remove common elements# in the two lists using list comprehensiondef remove_common(a, b): a, b = [i for i in a if i not in b], [j for j in b if j not in a] print("list1 : ", a) print("list2 : ", b) if __name__ == "__main__": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b) Output: list1 : [1, 2, 3] list2 : [6, 7, 8] The difference operator – gets items in the first set but not in the second. Python3 # Python program to remove common elements# in the two lists using Set’s difference# operatordef remove_common(a, b): a, b = list(set(a) - set(b)), list(set(b) - set(a)) print("list1 : ", a) print("list2 : ", b) if __name__ == "__main__": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b) Output: list1 : [1, 2, 3] list2 : [6, 7, 8] The difference() method in python returns a set that contains the difference between two sets i.e, the returned set contains items that exist only in the first set and excludes elements present in both sets. Python3 # Python program to remove common elements# in the two lists using Set difference()# methoddef remove_common(a, b): a, b = list(set(a).difference(b)), list(set(b).difference(a)) print("list1 : ", a) print("list2 : ", b) if __name__ == "__main__": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b) Output: list1 : [1, 2, 3] list2 : [6, 7, 8] Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Dec, 2021" }, { "code": null, "e": 158, "s": 54, "text": "Given two lists, the task is to write a Python program to remove all the common elements of two lists. " }, { "code": null, "e": 168, "s": 158, "text": "Examples:" }, { "code": null, "e": 202, "s": 168, "text": "Input : list1 = [1, 2, 3, 4, 5] " }, { "code": null, "e": 237, "s": 202, "text": " list2 = [4, 5, 6, 7, 8,]" }, { "code": null, "e": 266, "s": 237, "text": "Output : list1 = [1, 2, 3] " }, { "code": null, "e": 298, "s": 266, "text": " list2 = [6, 7, 8]" }, { "code": null, "e": 381, "s": 298, "text": "Explanation: Lists after removing common elements of both the lists i.e, 4 and 5." }, { "code": null, "e": 409, "s": 381, "text": "Input : list1 = [1, 2, 3] " }, { "code": null, "e": 438, "s": 409, "text": " list2 = [1, 2, 3]" }, { "code": null, "e": 461, "s": 438, "text": "Output : list1 = [] " }, { "code": null, "e": 487, "s": 461, "text": " list2 = []" }, { "code": null, "e": 541, "s": 487, "text": "Explanation: They have all the elements in common in " }, { "code": null, "e": 555, "s": 541, "text": "between them." }, { "code": null, "e": 658, "s": 555, "text": "The remove() method removes the first matching element (which is passed as an argument) from the list." }, { "code": null, "e": 666, "s": 658, "text": "Python3" }, { "code": "# Python program to remove common elements# in the two lists using remove methoddef remove_common(a, b): for i in a[:]: if i in b: a.remove(i) b.remove(i) print(\"list1 : \", a) print(\"list2 : \", b) if __name__ == \"__main__\": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b)", "e": 1006, "s": 666, "text": null }, { "code": null, "e": 1014, "s": 1006, "text": "Output:" }, { "code": null, "e": 1052, "s": 1014, "text": "list1 : [1, 2, 3]\nlist2 : [6, 7, 8]" }, { "code": null, "e": 1173, "s": 1052, "text": "List comprehension gives a shorter syntax when you want to create a new list based on the elements of the existing list." }, { "code": null, "e": 1181, "s": 1173, "text": "Python3" }, { "code": "# Python program to remove common elements# in the two lists using list comprehensiondef remove_common(a, b): a, b = [i for i in a if i not in b], [j for j in b if j not in a] print(\"list1 : \", a) print(\"list2 : \", b) if __name__ == \"__main__\": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b)", "e": 1517, "s": 1181, "text": null }, { "code": null, "e": 1525, "s": 1517, "text": "Output:" }, { "code": null, "e": 1563, "s": 1525, "text": "list1 : [1, 2, 3]\nlist2 : [6, 7, 8]" }, { "code": null, "e": 1640, "s": 1563, "text": "The difference operator – gets items in the first set but not in the second." }, { "code": null, "e": 1648, "s": 1640, "text": "Python3" }, { "code": "# Python program to remove common elements# in the two lists using Set’s difference# operatordef remove_common(a, b): a, b = list(set(a) - set(b)), list(set(b) - set(a)) print(\"list1 : \", a) print(\"list2 : \", b) if __name__ == \"__main__\": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b)", "e": 1980, "s": 1648, "text": null }, { "code": null, "e": 1988, "s": 1980, "text": "Output:" }, { "code": null, "e": 2026, "s": 1988, "text": "list1 : [1, 2, 3]\nlist2 : [6, 7, 8]" }, { "code": null, "e": 2234, "s": 2026, "text": "The difference() method in python returns a set that contains the difference between two sets i.e, the returned set contains items that exist only in the first set and excludes elements present in both sets." }, { "code": null, "e": 2242, "s": 2234, "text": "Python3" }, { "code": "# Python program to remove common elements# in the two lists using Set difference()# methoddef remove_common(a, b): a, b = list(set(a).difference(b)), list(set(b).difference(a)) print(\"list1 : \", a) print(\"list2 : \", b) if __name__ == \"__main__\": a = [1, 2, 3, 4, 5] b = [4, 5, 6, 7, 8] remove_common(a, b)", "e": 2576, "s": 2242, "text": null }, { "code": null, "e": 2584, "s": 2576, "text": "Output:" }, { "code": null, "e": 2622, "s": 2584, "text": "list1 : [1, 2, 3]\nlist2 : [6, 7, 8]" }, { "code": null, "e": 2643, "s": 2622, "text": "Python list-programs" }, { "code": null, "e": 2655, "s": 2643, "text": "python-list" }, { "code": null, "e": 2662, "s": 2655, "text": "Python" }, { "code": null, "e": 2678, "s": 2662, "text": "Python Programs" }, { "code": null, "e": 2690, "s": 2678, "text": "python-list" } ]
Python | Pandas Series.to_dense()
05 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.to_dense() function return dense representation of NDFrame (as opposed to sparse). This basically mean that memory will be allocated to store even the missing values in the dataframe. Syntax: Series.to_dense() Parameter : None Returns : Dense series Example #1: Use Series.to_dense() function to convert the given series object to dense series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr) Output : Now we will use Series.to_dense() function to achieve the conversion of the given Series object to dense series object. # convert to dense objectsr.to_dense() Output : < As we can see in the output, the Series.to_dense() function has returned the dense representation of the given series object. If we notice our series object does not have any missing values for this reason both the outputs looks the same. Let’s see another example which contains some missing values. Example #2: Use Series.to_dense() function to convert the given series object to dense series object. # importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr) Output : But, before we go ahead let’s convert the given series object to SparseSeries object to see the difference between the sparse and dense versions. Now we will use Series.to_sparse() function to achieve the conversion of the given Series object to SparseSeries object. # convert to Sparse objectsr.to_sparse() Output : As we can see in the output, the Series.to_sparse() function has successfully converted the given series object to sparseseries object. If we look at the bottom two lines, it has returned the info about memory Block location and the number of values contained in those blocks. Now we will use Series.to_dense() function to achieve the conversion of the given Series object to dense series object. # convert to dense objectsr.to_dense() Output : As we can see in the output, the Series.to_dense() function has returned the dense representation of the given series object. It has allocated memory to store even the missing values in the Series. Dense representation is not memory efficient when lots of data is missing. Python pandas-series 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": "\n05 Feb, 2019" }, { "code": null, "e": 285, "s": 28, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 483, "s": 285, "text": "Pandas Series.to_dense() function return dense representation of NDFrame (as opposed to sparse). This basically mean that memory will be allocated to store even the missing values in the dataframe." }, { "code": null, "e": 509, "s": 483, "text": "Syntax: Series.to_dense()" }, { "code": null, "e": 526, "s": 509, "text": "Parameter : None" }, { "code": null, "e": 549, "s": 526, "text": "Returns : Dense series" }, { "code": null, "e": 651, "s": 549, "text": "Example #1: Use Series.to_dense() function to convert the given series object to dense series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W', periods = 6, tz = 'Europe/Berlin') # set the indexsr.index = didx # Print the seriesprint(sr)", "e": 1003, "s": 651, "text": null }, { "code": null, "e": 1012, "s": 1003, "text": "Output :" }, { "code": null, "e": 1132, "s": 1012, "text": "Now we will use Series.to_dense() function to achieve the conversion of the given Series object to dense series object." }, { "code": "# convert to dense objectsr.to_dense()", "e": 1171, "s": 1132, "text": null }, { "code": null, "e": 1180, "s": 1171, "text": "Output :" }, { "code": null, "e": 1182, "s": 1180, "text": "<" }, { "code": null, "e": 1585, "s": 1182, "text": "As we can see in the output, the Series.to_dense() function has returned the dense representation of the given series object. If we notice our series object does not have any missing values for this reason both the outputs looks the same. Let’s see another example which contains some missing values. Example #2: Use Series.to_dense() function to convert the given series object to dense series object." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None]) # Print the seriesprint(sr)", "e": 1757, "s": 1585, "text": null }, { "code": null, "e": 1766, "s": 1757, "text": "Output :" }, { "code": null, "e": 1912, "s": 1766, "text": "But, before we go ahead let’s convert the given series object to SparseSeries object to see the difference between the sparse and dense versions." }, { "code": null, "e": 2033, "s": 1912, "text": "Now we will use Series.to_sparse() function to achieve the conversion of the given Series object to SparseSeries object." }, { "code": "# convert to Sparse objectsr.to_sparse()", "e": 2074, "s": 2033, "text": null }, { "code": null, "e": 2083, "s": 2074, "text": "Output :" }, { "code": null, "e": 2360, "s": 2083, "text": "As we can see in the output, the Series.to_sparse() function has successfully converted the given series object to sparseseries object. If we look at the bottom two lines, it has returned the info about memory Block location and the number of values contained in those blocks." }, { "code": null, "e": 2480, "s": 2360, "text": "Now we will use Series.to_dense() function to achieve the conversion of the given Series object to dense series object." }, { "code": "# convert to dense objectsr.to_dense()", "e": 2519, "s": 2480, "text": null }, { "code": null, "e": 2528, "s": 2519, "text": "Output :" }, { "code": null, "e": 2801, "s": 2528, "text": "As we can see in the output, the Series.to_dense() function has returned the dense representation of the given series object. It has allocated memory to store even the missing values in the Series. Dense representation is not memory efficient when lots of data is missing." }, { "code": null, "e": 2822, "s": 2801, "text": "Python pandas-series" }, { "code": null, "e": 2851, "s": 2822, "text": "Python pandas-series-methods" }, { "code": null, "e": 2865, "s": 2851, "text": "Python-pandas" }, { "code": null, "e": 2872, "s": 2865, "text": "Python" } ]
How to apply radial gradient (color) to a node in JavaFX?
You can apply colors to shapes in JavaFX using the setFill() method it adds color to the interior of the geometrical shapes or background. This method accepts an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color. The javafx.scene.paint.RadialGradient class in JavaFX is a subclass of the Paint and using this you can fill a shape with a circular color gradient pattern. To apply a radial gradient pattern to a geometrical shape βˆ’ Instantiate the RadialGradient class by passing the required parameters. Instantiate the RadialGradient class by passing the required parameters. Set the created gradient to the shape using the setFill() method. Set the created gradient to the shape using the setFill() method. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Polygon; import javafx.scene.shape.Rectangle; public class RadialGradientExample extends Application { public void start(Stage stage) { //Drawing a circle Circle circle = new Circle(75.0f, 65.0f, 40.0f ); //Drawing a Rectangle Rectangle rect = new Rectangle(150, 30, 100, 65); //Drawing an ellipse Ellipse ellipse = new Ellipse(330, 60, 60, 35); //Drawing Polygon Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 ); //Setting the radial gradient Stop[] stops = new Stop[] { new Stop(0.0, Color.WHITE), new Stop(0.3, Color.RED), new Stop(1.0, Color.DARKRED) }; RadialGradient gradient = new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops); //Setting the pattern circle.setFill(gradient); circle.setStrokeWidth(3); circle.setStroke(Color.CADETBLUE); rect.setFill(gradient); rect.setStrokeWidth(3); rect.setStroke(Color.CADETBLUE); ellipse.setFill(gradient); ellipse.setStrokeWidth(3); ellipse.setStroke(Color.CADETBLUE); poly.setFill(gradient); poly.setStrokeWidth(3); poly.setStroke(Color.CADETBLUE); //Setting the stage Group root = new Group(circle, ellipse, rect, poly); Scene scene = new Scene(root, 600, 150); stage.setTitle("Radial Gradient"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1201, "s": 1062, "text": "You can apply colors to shapes in JavaFX using the setFill() method it adds color to the interior of the geometrical shapes or background." }, { "code": null, "e": 1395, "s": 1201, "text": "This method accepts an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color." }, { "code": null, "e": 1552, "s": 1395, "text": "The javafx.scene.paint.RadialGradient class in JavaFX is a subclass of the Paint and using this you can fill a shape with a circular color gradient pattern." }, { "code": null, "e": 1612, "s": 1552, "text": "To apply a radial gradient pattern to a geometrical shape βˆ’" }, { "code": null, "e": 1685, "s": 1612, "text": "Instantiate the RadialGradient class by passing the required parameters." }, { "code": null, "e": 1758, "s": 1685, "text": "Instantiate the RadialGradient class by passing the required parameters." }, { "code": null, "e": 1824, "s": 1758, "text": "Set the created gradient to the shape using the setFill() method." }, { "code": null, "e": 1890, "s": 1824, "text": "Set the created gradient to the shape using the setFill() method." }, { "code": null, "e": 3784, "s": 1890, "text": "import javafx.application.Application;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.paint.Color;\nimport javafx.scene.paint.CycleMethod;\nimport javafx.scene.paint.RadialGradient;\nimport javafx.scene.paint.Stop;\nimport javafx.stage.Stage;\nimport javafx.scene.shape.Circle;\nimport javafx.scene.shape.Ellipse;\nimport javafx.scene.shape.Polygon;\nimport javafx.scene.shape.Rectangle;\npublic class RadialGradientExample extends Application {\n public void start(Stage stage) {\n //Drawing a circle\n Circle circle = new Circle(75.0f, 65.0f, 40.0f );\n //Drawing a Rectangle\n Rectangle rect = new Rectangle(150, 30, 100, 65);\n //Drawing an ellipse\n Ellipse ellipse = new Ellipse(330, 60, 60, 35);\n //Drawing Polygon\n Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );\n //Setting the radial gradient\n Stop[] stops = new Stop[] {\n new Stop(0.0, Color.WHITE),\n new Stop(0.3, Color.RED),\n new Stop(1.0, Color.DARKRED)\n };\n RadialGradient gradient = new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops);\n //Setting the pattern\n circle.setFill(gradient);\n circle.setStrokeWidth(3);\n circle.setStroke(Color.CADETBLUE);\n rect.setFill(gradient);\n rect.setStrokeWidth(3);\n rect.setStroke(Color.CADETBLUE);\n ellipse.setFill(gradient);\n ellipse.setStrokeWidth(3);\n ellipse.setStroke(Color.CADETBLUE);\n poly.setFill(gradient);\n poly.setStrokeWidth(3);\n poly.setStroke(Color.CADETBLUE);\n //Setting the stage\n Group root = new Group(circle, ellipse, rect, poly);\n Scene scene = new Scene(root, 600, 150);\n stage.setTitle(\"Radial Gradient\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Division Operators in Java
The division operator in Java includes the Division, Modulus, and the Divide And Assignment operator. Let us work with them one by one βˆ’ The division operator divides left-hand operand by right-hand operand. The modulus operator divides left-hand operand by right-hand operand and returns remainder. This operator divides left operand with the right operand and assign the result to left operand. Let us now see an example βˆ’ public class Demo { public static void main( String args[] ) { int a = 10; int b = 20; int c = 25; System.out.println("b / a = " + (b / a) ); System.out.println("b % a = " + (b % a) ); c /= a ; System.out.println("c /= a = " + c ); } } b / a = 2 b % a = 0 c /= a = 2
[ { "code": null, "e": 1199, "s": 1062, "text": "The division operator in Java includes the Division, Modulus, and the Divide And Assignment operator. Let us work with them one by one βˆ’" }, { "code": null, "e": 1270, "s": 1199, "text": "The division operator divides left-hand operand by right-hand operand." }, { "code": null, "e": 1362, "s": 1270, "text": "The modulus operator divides left-hand operand by right-hand operand and returns remainder." }, { "code": null, "e": 1459, "s": 1362, "text": "This operator divides left operand with the right operand and assign the result to left operand." }, { "code": null, "e": 1487, "s": 1459, "text": "Let us now see an example βˆ’" }, { "code": null, "e": 1771, "s": 1487, "text": "public class Demo {\n public static void main( String args[] ) {\n int a = 10;\n int b = 20;\n int c = 25;\n System.out.println(\"b / a = \" + (b / a) );\n System.out.println(\"b % a = \" + (b % a) );\n c /= a ;\n System.out.println(\"c /= a = \" + c );\n }\n}" }, { "code": null, "e": 1802, "s": 1771, "text": "b / a = 2\nb % a = 0\nc /= a = 2" } ]
Build a Calculate Expression Game in Java
03 Jan, 2022 Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++. What is 2+3 ? Yupp, 5 is Correct!! What about 5*8? 40, right !! Did it take time to calculate it ?! Let’s find out how many such simple questions can you and your friends do in just 60 seconds. The game will allow us to find out how many questions we will be able to correctly do in just 60 seconds !! For this, we will be creating a SIMPLE and Interactive Time Based β€œCalculate Expression Game” in java using the Java swing components. A sample video is given below to get an idea about what we are going to do in this article. So the learning outcomes will be: Creating Interactive GUI for our GameIntegration of Two JFrameCreation of Workable TimerDeveloping a Style to manage Components Creating Interactive GUI for our Game Integration of Two JFrame Creation of Workable Timer Developing a Style to manage Components The project will contain 3 java classes: Main.javaHome.javaPlay.java Main.java Home.java Play.java We will design two pages or JFrames as we call it. 1st JFrame will give the option to PLAY or EXIT from the game. In case the user chooses to play, the 2nd JFrame will contain the game in which the player has to answer maximum mathematical expression-based questions in 60 seconds. Step 1. We will start by first importing all the classes which we will require for this Game. We will learn how they will be useful as we proceed further in this project. Java // File name is Main.javaimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random; Step 2. We will define a class Main which will call the class Home Constructor. Java // File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame "HOME" frame.setTitle("HOME"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }} Step 3. We will now define our class Home and prepare a style for it so that tracking the components does not make our head go haywire. Also, time to make some concepts clear !! We will inherit the JFrame class which is a swing component (part of javax.swing package). In order to define what should be done when a user performs certain operations, we will implement the ActionListener interface. ActionListener (found in java.awt.event package) has only one method actionPerformed(ActionEvent) which is called when the user performs some action. Java // File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Home extends JFrame implements ActionListener { Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() {} public void setLocationAndSize() {} public void addComponentsToContainer() {} public void addActionEvent() {} @Override public void actionPerformed(ActionEvent e) {}} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame "HOME" frame.setTitle("HOME"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }} Step 4. We will define the components and add them to the Home frame. Java // File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Home extends JFrame implements ActionListener { Container container = getContentPane(); JLabel home = new JLabel("HOME", JLabel.CENTER); JButton playbutton = new JButton("PLAY"); JButton exitbutton = new JButton("EXIT"); Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() { // Content panes use // BorderLayout by default container.setLayout(null); } public void setLocationAndSize() { // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125, 20, 125, 30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75, 200, 225, 30); exitbutton.setBounds(75, 250, 225, 30); } public void addComponentsToContainer() { container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent() { // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) {}} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame "HOME" frame.setTitle("HOME"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }} Step 5. Time for adding functionalities to the buttons. Java // File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Home extends JFrame implements ActionListener { Container container = getContentPane(); JLabel home = new JLabel("HOME", JLabel.CENTER); JButton playbutton = new JButton("PLAY"); JButton exitbutton = new JButton("EXIT"); Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() { // Content panes use BorderLayout by default container.setLayout(null); } public void setLocationAndSize() { // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125, 20, 125, 30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75, 200, 225, 30); exitbutton.setBounds(75, 250, 225, 30); } public void addComponentsToContainer() { container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent() { // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == playbutton) { // dispose() method clear // resources at each frame dispose(); // to call the constructor of class Play Play frame = new Play(); // Sets the title for this frame "PLAY" frame.setTitle("PLAY"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame using // setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); } if (e.getSource() == exitbutton) { // asks for confirmation from the user to exit // or not int option = JOptionPane.showConfirmDialog( this, "Do You Really Want To Quit", "Thank you", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); if (option == JOptionPane.YES_OPTION) { dispose(); } } }} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame "HOME" frame.setTitle("HOME"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }} Step 6. Let us look into two utility functions that will be used for our project. Calculate function to generate mathematical expression. Here we are generating two random numbers using the imported class import java.util.Random in the given range. Java int Calculate(){ int num1 = new Random().nextInt(11); // 0 to 10 int num2 = new Random().nextInt(11) + 1; // 1 to 11 String operator = "+-/*%"; int random_operator = new Random().nextInt(5); questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")"); return switch (operator.charAt(random_operator)) { case ('+') -> num1 + num2; case ('-') -> num1 - num2; case ('*') -> num1 * num2; case ('/') -> num1 / num2; case ('%') -> num1 % num2; default -> 0; }; } Score function to display the updated score of the player. Java void Score(){ score += 1; presentscoretext.setText(" " +score + " ");} Step 7. Now we will define the skeleton of the class Play. Here we are requesting the focus of our JFrame object on the text field using WindowActionListener. Also, we are creating a TIMER of 60 seconds so that no input will be accepted just after a delay of 60 seconds and also this will ensure that not more than 60 inputs are taken (In case a user keeps pressing the same input many times). In practice, the timer is running after a delay of 1000 milliseconds waiting for user input and that is why we are surrounding the ActionEvent to try-catch blocks in cases when the user does not provide input for that particular second. Java // File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Game extends JFrame implements ActionListener { Container container = getContentPane(); JLabel questionlabel = new JLabel("QUESTION : "); JTextField questiontext = new JTextField(); JLabel answerlabel = new JLabel("ANSWER : "); JTextField answertext = new JTextField(); JLabel presentscorelabel = new JLabel("PRESENT SCORE : "); JTextField presentscoretext = new JTextField(); int result = 0; int score = -1; Timer gametimer; // GAME TIMER in seconds int start = 60; Game() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); result = Calculate(); Score(); setTimer(); } public void setLayoutManager() { container.setLayout(null); } public void setLocationAndSize() { questionlabel.setBounds(100, 100, 150, 30); questiontext.setBounds(100, 140, 150, 30); answerlabel.setBounds(100, 200, 150, 30); answertext.setBounds(100, 240, 150, 30); presentscorelabel.setBounds(100, 290, 150, 30); presentscoretext.setBounds(100, 330, 150, 30); } public void addComponentsToContainer() { container.add(questionlabel); container.add(questiontext); container.add(answerlabel); container.add(answertext); container.add(presentscorelabel); container.add(presentscoretext); } public void addActionEvent() { questiontext.setEditable(false); presentscoretext.setEditable(false); answertext.addActionListener(this); this.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent evt) { super.windowOpened(evt); answertext.requestFocus(); } }); } public void setTimer() { gametimer = new Timer(1000, this); gametimer.start(); } @Override public void actionPerformed(ActionEvent e1) {}} class Home extends JFrame implements ActionListener { Container container = getContentPane(); JLabel home = new JLabel("HOME", JLabel.CENTER); JButton playbutton = new JButton("PLAY"); JButton exitbutton = new JButton("EXIT"); Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() { // Content panes use // BorderLayout by default container.setLayout(null); } public void setLocationAndSize() { // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125, 20, 125, 30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75, 200, 225, 30); exitbutton.setBounds(75, 250, 225, 30); } public void addComponentsToContainer() { container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent() { // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == playbutton) { // dispose() method clear resources at each // frame dispose(); // to call the constructor of class Play Game frame = new Game(); // Sets the title for this frame "PLAY" frame.setTitle("PLAY"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); } if (e.getSource() == exitbutton) { // asks for confirmation from the user to exit // or not int option = JOptionPane.showConfirmDialog( this, "Do You Really Want To Quit", "Thank you", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); if (option == JOptionPane.YES_OPTION) { dispose(); } } }} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame "HOME" frame.setTitle("HOME"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }} Step 8. We are now at the last stage where we add the utilities to our source code and also add two messages so that the user is able to view the score as 60 seconds are elapsed as well as ask the user for playing again. Below is the Working Source Code for this Game. Java // File name is Main.javaimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.Random; class Game extends JFrame implements ActionListener{ Container container = getContentPane(); JLabel questionlabel = new JLabel("QUESTION : "); JTextField questiontext = new JTextField(); JLabel answerlabel = new JLabel("ANSWER : "); JTextField answertext = new JTextField(); JLabel presentscorelabel = new JLabel("PRESENT SCORE : "); JTextField presentscoretext = new JTextField(); int result = 0; int score = -1; Timer gametimer; // GAME TIMER in seconds int start = 60; Game(){ setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); result = Calculate(); Score(); setTimer(); } public void setLayoutManager() { container.setLayout(null); } public void setLocationAndSize() { questionlabel.setBounds(100, 100, 150, 30); questiontext.setBounds(100, 140, 150, 30); answerlabel.setBounds(100, 200, 150, 30); answertext.setBounds(100, 240, 150, 30); presentscorelabel.setBounds(100, 290, 150, 30); presentscoretext.setBounds(100, 330, 150, 30); } public void addComponentsToContainer() { container.add(questionlabel); container.add(questiontext); container.add(answerlabel); container.add( answertext); container.add(presentscorelabel); container.add( presentscoretext); } public void addActionEvent() { questiontext.setEditable(false); presentscoretext.setEditable(false); answertext.addActionListener(this); this.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent evt) { super.windowOpened(evt); answertext.requestFocus(); } }); } public void setTimer(){ gametimer = new Timer(1000,this); gametimer.start(); } @Override public void actionPerformed(ActionEvent e1) { start -= 1; if(start >= 0){ try{ String s = e1.getActionCommand(); if(result == Integer.parseInt(s)){ Score(); } result = Calculate(); answertext.setText(null); } catch(Exception e3){ } }else{ gametimer.stop(); JOptionPane.showMessageDialog(this,"TIME IS UP. YOUR SCORE IS : " + score ,"SCORE",JOptionPane.PLAIN_MESSAGE); int option = JOptionPane.showConfirmDialog(this,"DO YOU WANT TO PLAY AGAIN ?","PLAY AGAIN SCORE : " + score,JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); if(option == JOptionPane.YES_OPTION){ dispose(); Game frame = new Game(); frame.setTitle("PLAY"); frame.setVisible(true); frame.setBounds(10,10,370,600); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setResizable(false); } else{ dispose(); Home frame = new Home(); frame.setTitle("HOME"); frame.setVisible(true); frame.setBounds(10,10,370,600); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setResizable(false); } } } int Calculate(){ int num1 = new Random().nextInt(11); // 1 to 10 int num2 = new Random().nextInt(11) + 1; // 0 to 10 String operator = "+-/*%"; int random_operator = new Random().nextInt(5); questiontext.setText("(" + num1 + ") " + operator.charAt(random_operator) + " (" + num2 + ")"); return switch (operator.charAt(random_operator)) { case ('+') -> num1 + num2; case ('-') -> num1 - num2; case ('*') -> num1 * num2; case ('/') -> num1 / num2; case ('%') -> num1 % num2; default -> 0; }; } void Score(){ score += 1; presentscoretext.setText(" " +score + " "); }} class Home extends JFrame implements ActionListener{ Container container = getContentPane(); JLabel home = new JLabel("HOME",JLabel.CENTER); JButton playbutton = new JButton("PLAY"); JButton exitbutton = new JButton("EXIT"); Home(){ setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager(){ // Content panes use // BorderLayout by default container.setLayout(null); } public void setLocationAndSize(){ // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125,20,125,30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75,200,225,30); exitbutton.setBounds(75,250,225,30); } public void addComponentsToContainer(){ container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent(){ // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e){ if(e.getSource() == playbutton){ // dispose() method clear // resources at each frame dispose(); // to call the constructor of class Play Game frame = new Game(); // Sets the title for this frame "PLAY" frame.setTitle("PLAY"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10,10,370,600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); } if(e.getSource() == exitbutton){ // asks for confirmation from the user to exit or not int option = JOptionPane.showConfirmDialog(this,"Do You Really Want To Quit","Thank you", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE); if(option == JOptionPane.YES_OPTION){ dispose(); } } }} public class MAN { public static void main(String[] arg){ // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame "HOME" frame.setTitle("HOME"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10,10,370,600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }} Output: Java Project 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 SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Jan, 2022" }, { "code": null, "e": 469, "s": 53, "text": "Java is a class-based, object-oriented programming language and is designed to have as few implementation dependencies as possible. A general-purpose programming language made for developers to write once run anywhere that is compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is similar to c/c++. " }, { "code": null, "e": 998, "s": 469, "text": "What is 2+3 ? Yupp, 5 is Correct!! What about 5*8? 40, right !! Did it take time to calculate it ?! Let’s find out how many such simple questions can you and your friends do in just 60 seconds. The game will allow us to find out how many questions we will be able to correctly do in just 60 seconds !! For this, we will be creating a SIMPLE and Interactive Time Based β€œCalculate Expression Game” in java using the Java swing components. A sample video is given below to get an idea about what we are going to do in this article." }, { "code": null, "e": 1032, "s": 998, "text": "So the learning outcomes will be:" }, { "code": null, "e": 1160, "s": 1032, "text": "Creating Interactive GUI for our GameIntegration of Two JFrameCreation of Workable TimerDeveloping a Style to manage Components" }, { "code": null, "e": 1198, "s": 1160, "text": "Creating Interactive GUI for our Game" }, { "code": null, "e": 1224, "s": 1198, "text": "Integration of Two JFrame" }, { "code": null, "e": 1251, "s": 1224, "text": "Creation of Workable Timer" }, { "code": null, "e": 1291, "s": 1251, "text": "Developing a Style to manage Components" }, { "code": null, "e": 1333, "s": 1291, "text": "The project will contain 3 java classes: " }, { "code": null, "e": 1361, "s": 1333, "text": "Main.javaHome.javaPlay.java" }, { "code": null, "e": 1371, "s": 1361, "text": "Main.java" }, { "code": null, "e": 1381, "s": 1371, "text": "Home.java" }, { "code": null, "e": 1391, "s": 1381, "text": "Play.java" }, { "code": null, "e": 1673, "s": 1391, "text": "We will design two pages or JFrames as we call it. 1st JFrame will give the option to PLAY or EXIT from the game. In case the user chooses to play, the 2nd JFrame will contain the game in which the player has to answer maximum mathematical expression-based questions in 60 seconds." }, { "code": null, "e": 1846, "s": 1673, "text": "Step 1. We will start by first importing all the classes which we will require for this Game. We will learn how they will be useful as we proceed further in this project. " }, { "code": null, "e": 1851, "s": 1846, "text": "Java" }, { "code": "// File name is Main.javaimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;", "e": 2098, "s": 1851, "text": null }, { "code": null, "e": 2178, "s": 2098, "text": "Step 2. We will define a class Main which will call the class Home Constructor." }, { "code": null, "e": 2183, "s": 2178, "text": "Java" }, { "code": "// File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame \"HOME\" frame.setTitle(\"HOME\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }}", "e": 3095, "s": 2183, "text": null }, { "code": null, "e": 3643, "s": 3095, "text": "Step 3. We will now define our class Home and prepare a style for it so that tracking the components does not make our head go haywire. Also, time to make some concepts clear !! We will inherit the JFrame class which is a swing component (part of javax.swing package). In order to define what should be done when a user performs certain operations, we will implement the ActionListener interface. ActionListener (found in java.awt.event package) has only one method actionPerformed(ActionEvent) which is called when the user performs some action." }, { "code": null, "e": 3648, "s": 3643, "text": "Java" }, { "code": "// File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Home extends JFrame implements ActionListener { Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() {} public void setLocationAndSize() {} public void addComponentsToContainer() {} public void addActionEvent() {} @Override public void actionPerformed(ActionEvent e) {}} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame \"HOME\" frame.setTitle(\"HOME\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }}", "e": 4967, "s": 3648, "text": null }, { "code": null, "e": 5038, "s": 4967, "text": "Step 4. We will define the components and add them to the Home frame. " }, { "code": null, "e": 5043, "s": 5038, "text": "Java" }, { "code": "// File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Home extends JFrame implements ActionListener { Container container = getContentPane(); JLabel home = new JLabel(\"HOME\", JLabel.CENTER); JButton playbutton = new JButton(\"PLAY\"); JButton exitbutton = new JButton(\"EXIT\"); Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() { // Content panes use // BorderLayout by default container.setLayout(null); } public void setLocationAndSize() { // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125, 20, 125, 30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75, 200, 225, 30); exitbutton.setBounds(75, 250, 225, 30); } public void addComponentsToContainer() { container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent() { // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) {}} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame \"HOME\" frame.setTitle(\"HOME\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }}", "e": 7312, "s": 5043, "text": null }, { "code": null, "e": 7368, "s": 7312, "text": "Step 5. Time for adding functionalities to the buttons." }, { "code": null, "e": 7373, "s": 7368, "text": "Java" }, { "code": "// File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Home extends JFrame implements ActionListener { Container container = getContentPane(); JLabel home = new JLabel(\"HOME\", JLabel.CENTER); JButton playbutton = new JButton(\"PLAY\"); JButton exitbutton = new JButton(\"EXIT\"); Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() { // Content panes use BorderLayout by default container.setLayout(null); } public void setLocationAndSize() { // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125, 20, 125, 30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75, 200, 225, 30); exitbutton.setBounds(75, 250, 225, 30); } public void addComponentsToContainer() { container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent() { // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == playbutton) { // dispose() method clear // resources at each frame dispose(); // to call the constructor of class Play Play frame = new Play(); // Sets the title for this frame \"PLAY\" frame.setTitle(\"PLAY\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame using // setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); } if (e.getSource() == exitbutton) { // asks for confirmation from the user to exit // or not int option = JOptionPane.showConfirmDialog( this, \"Do You Really Want To Quit\", \"Thank you\", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); if (option == JOptionPane.YES_OPTION) { dispose(); } } }} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame \"HOME\" frame.setTitle(\"HOME\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }}", "e": 10871, "s": 7373, "text": null }, { "code": null, "e": 11120, "s": 10871, "text": "Step 6. Let us look into two utility functions that will be used for our project. Calculate function to generate mathematical expression. Here we are generating two random numbers using the imported class import java.util.Random in the given range." }, { "code": null, "e": 11125, "s": 11120, "text": "Java" }, { "code": "int Calculate(){ int num1 = new Random().nextInt(11); // 0 to 10 int num2 = new Random().nextInt(11) + 1; // 1 to 11 String operator = \"+-/*%\"; int random_operator = new Random().nextInt(5); questiontext.setText(\"(\" + num1 + \") \" + operator.charAt(random_operator) + \" (\" + num2 + \")\"); return switch (operator.charAt(random_operator)) { case ('+') -> num1 + num2; case ('-') -> num1 - num2; case ('*') -> num1 * num2; case ('/') -> num1 / num2; case ('%') -> num1 % num2; default -> 0; }; }", "e": 11741, "s": 11125, "text": null }, { "code": null, "e": 11800, "s": 11741, "text": "Score function to display the updated score of the player." }, { "code": null, "e": 11805, "s": 11800, "text": "Java" }, { "code": "void Score(){ score += 1; presentscoretext.setText(\" \" +score + \" \");}", "e": 11880, "s": 11805, "text": null }, { "code": null, "e": 11940, "s": 11880, "text": "Step 7. Now we will define the skeleton of the class Play. " }, { "code": null, "e": 12512, "s": 11940, "text": "Here we are requesting the focus of our JFrame object on the text field using WindowActionListener. Also, we are creating a TIMER of 60 seconds so that no input will be accepted just after a delay of 60 seconds and also this will ensure that not more than 60 inputs are taken (In case a user keeps pressing the same input many times). In practice, the timer is running after a delay of 1000 milliseconds waiting for user input and that is why we are surrounding the ActionEvent to try-catch blocks in cases when the user does not provide input for that particular second." }, { "code": null, "e": 12517, "s": 12512, "text": "Java" }, { "code": "// File name is Main.javaimport java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.*;import java.util.Random;import javax.swing.*; class Game extends JFrame implements ActionListener { Container container = getContentPane(); JLabel questionlabel = new JLabel(\"QUESTION : \"); JTextField questiontext = new JTextField(); JLabel answerlabel = new JLabel(\"ANSWER : \"); JTextField answertext = new JTextField(); JLabel presentscorelabel = new JLabel(\"PRESENT SCORE : \"); JTextField presentscoretext = new JTextField(); int result = 0; int score = -1; Timer gametimer; // GAME TIMER in seconds int start = 60; Game() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); result = Calculate(); Score(); setTimer(); } public void setLayoutManager() { container.setLayout(null); } public void setLocationAndSize() { questionlabel.setBounds(100, 100, 150, 30); questiontext.setBounds(100, 140, 150, 30); answerlabel.setBounds(100, 200, 150, 30); answertext.setBounds(100, 240, 150, 30); presentscorelabel.setBounds(100, 290, 150, 30); presentscoretext.setBounds(100, 330, 150, 30); } public void addComponentsToContainer() { container.add(questionlabel); container.add(questiontext); container.add(answerlabel); container.add(answertext); container.add(presentscorelabel); container.add(presentscoretext); } public void addActionEvent() { questiontext.setEditable(false); presentscoretext.setEditable(false); answertext.addActionListener(this); this.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent evt) { super.windowOpened(evt); answertext.requestFocus(); } }); } public void setTimer() { gametimer = new Timer(1000, this); gametimer.start(); } @Override public void actionPerformed(ActionEvent e1) {}} class Home extends JFrame implements ActionListener { Container container = getContentPane(); JLabel home = new JLabel(\"HOME\", JLabel.CENTER); JButton playbutton = new JButton(\"PLAY\"); JButton exitbutton = new JButton(\"EXIT\"); Home() { setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager() { // Content panes use // BorderLayout by default container.setLayout(null); } public void setLocationAndSize() { // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125, 20, 125, 30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75, 200, 225, 30); exitbutton.setBounds(75, 250, 225, 30); } public void addComponentsToContainer() { container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent() { // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == playbutton) { // dispose() method clear resources at each // frame dispose(); // to call the constructor of class Play Game frame = new Game(); // Sets the title for this frame \"PLAY\" frame.setTitle(\"PLAY\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); } if (e.getSource() == exitbutton) { // asks for confirmation from the user to exit // or not int option = JOptionPane.showConfirmDialog( this, \"Do You Really Want To Quit\", \"Thank you\", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE); if (option == JOptionPane.YES_OPTION) { dispose(); } } }} public class Main { public static void main(String[] arg) { // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame \"HOME\" frame.setTitle(\"HOME\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10, 10, 370, 600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }}", "e": 18023, "s": 12517, "text": null }, { "code": null, "e": 18292, "s": 18023, "text": "Step 8. We are now at the last stage where we add the utilities to our source code and also add two messages so that the user is able to view the score as 60 seconds are elapsed as well as ask the user for playing again. Below is the Working Source Code for this Game." }, { "code": null, "e": 18297, "s": 18292, "text": "Java" }, { "code": "// File name is Main.javaimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.util.Random; class Game extends JFrame implements ActionListener{ Container container = getContentPane(); JLabel questionlabel = new JLabel(\"QUESTION : \"); JTextField questiontext = new JTextField(); JLabel answerlabel = new JLabel(\"ANSWER : \"); JTextField answertext = new JTextField(); JLabel presentscorelabel = new JLabel(\"PRESENT SCORE : \"); JTextField presentscoretext = new JTextField(); int result = 0; int score = -1; Timer gametimer; // GAME TIMER in seconds int start = 60; Game(){ setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); result = Calculate(); Score(); setTimer(); } public void setLayoutManager() { container.setLayout(null); } public void setLocationAndSize() { questionlabel.setBounds(100, 100, 150, 30); questiontext.setBounds(100, 140, 150, 30); answerlabel.setBounds(100, 200, 150, 30); answertext.setBounds(100, 240, 150, 30); presentscorelabel.setBounds(100, 290, 150, 30); presentscoretext.setBounds(100, 330, 150, 30); } public void addComponentsToContainer() { container.add(questionlabel); container.add(questiontext); container.add(answerlabel); container.add( answertext); container.add(presentscorelabel); container.add( presentscoretext); } public void addActionEvent() { questiontext.setEditable(false); presentscoretext.setEditable(false); answertext.addActionListener(this); this.addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent evt) { super.windowOpened(evt); answertext.requestFocus(); } }); } public void setTimer(){ gametimer = new Timer(1000,this); gametimer.start(); } @Override public void actionPerformed(ActionEvent e1) { start -= 1; if(start >= 0){ try{ String s = e1.getActionCommand(); if(result == Integer.parseInt(s)){ Score(); } result = Calculate(); answertext.setText(null); } catch(Exception e3){ } }else{ gametimer.stop(); JOptionPane.showMessageDialog(this,\"TIME IS UP. YOUR SCORE IS : \" + score ,\"SCORE\",JOptionPane.PLAIN_MESSAGE); int option = JOptionPane.showConfirmDialog(this,\"DO YOU WANT TO PLAY AGAIN ?\",\"PLAY AGAIN SCORE : \" + score,JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE); if(option == JOptionPane.YES_OPTION){ dispose(); Game frame = new Game(); frame.setTitle(\"PLAY\"); frame.setVisible(true); frame.setBounds(10,10,370,600); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setResizable(false); } else{ dispose(); Home frame = new Home(); frame.setTitle(\"HOME\"); frame.setVisible(true); frame.setBounds(10,10,370,600); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setResizable(false); } } } int Calculate(){ int num1 = new Random().nextInt(11); // 1 to 10 int num2 = new Random().nextInt(11) + 1; // 0 to 10 String operator = \"+-/*%\"; int random_operator = new Random().nextInt(5); questiontext.setText(\"(\" + num1 + \") \" + operator.charAt(random_operator) + \" (\" + num2 + \")\"); return switch (operator.charAt(random_operator)) { case ('+') -> num1 + num2; case ('-') -> num1 - num2; case ('*') -> num1 * num2; case ('/') -> num1 / num2; case ('%') -> num1 % num2; default -> 0; }; } void Score(){ score += 1; presentscoretext.setText(\" \" +score + \" \"); }} class Home extends JFrame implements ActionListener{ Container container = getContentPane(); JLabel home = new JLabel(\"HOME\",JLabel.CENTER); JButton playbutton = new JButton(\"PLAY\"); JButton exitbutton = new JButton(\"EXIT\"); Home(){ setLayoutManager(); setLocationAndSize(); addComponentsToContainer(); addActionEvent(); } public void setLayoutManager(){ // Content panes use // BorderLayout by default container.setLayout(null); } public void setLocationAndSize(){ // position and size of the components // using setBounds(x,y,width,height) home.setBounds(125,20,125,30); // to display content or BackGround // behind a given component home.setOpaque(true); home.setBackground(Color.BLACK); home.setForeground(Color.WHITE); playbutton.setBounds(75,200,225,30); exitbutton.setBounds(75,250,225,30); } public void addComponentsToContainer(){ container.add(home); container.add(playbutton); container.add(exitbutton); } public void addActionEvent(){ // listen for changes on the object playbutton.addActionListener(this); exitbutton.addActionListener(this); } @Override public void actionPerformed(ActionEvent e){ if(e.getSource() == playbutton){ // dispose() method clear // resources at each frame dispose(); // to call the constructor of class Play Game frame = new Game(); // Sets the title for this frame \"PLAY\" frame.setTitle(\"PLAY\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10,10,370,600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); } if(e.getSource() == exitbutton){ // asks for confirmation from the user to exit or not int option = JOptionPane.showConfirmDialog(this,\"Do You Really Want To Quit\",\"Thank you\", JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE); if(option == JOptionPane.YES_OPTION){ dispose(); } } }} public class MAN { public static void main(String[] arg){ // to call the constructor of class Home Home frame = new Home(); // Sets the title for this frame \"HOME\" frame.setTitle(\"HOME\"); // Component will be displayed on the screen frame.setVisible(true); // position and size of the frame // using setBounds(x,y,width,height) frame.setBounds(10,10,370,600); // application exits on close window // event from the operating system frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // user cannot re-size the frame frame.setResizable(false); }}", "e": 25765, "s": 18297, "text": null }, { "code": null, "e": 25773, "s": 25765, "text": "Output:" }, { "code": null, "e": 25778, "s": 25773, "text": "Java" }, { "code": null, "e": 25786, "s": 25778, "text": "Project" }, { "code": null, "e": 25791, "s": 25786, "text": "Java" }, { "code": null, "e": 25889, "s": 25791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25904, "s": 25889, "text": "Stream In Java" }, { "code": null, "e": 25925, "s": 25904, "text": "Introduction to Java" }, { "code": null, "e": 25946, "s": 25925, "text": "Constructors in Java" }, { "code": null, "e": 25965, "s": 25946, "text": "Exceptions in Java" }, { "code": null, "e": 25982, "s": 25965, "text": "Generics in Java" }, { "code": null, "e": 26031, "s": 25982, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 26086, "s": 26031, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 26119, "s": 26086, "text": "Working with zip files in Python" }, { "code": null, "e": 26141, "s": 26119, "text": "XML parsing in Python" } ]
How to use Breadcrumbs Component in ReactJS?
16 Feb, 2021 Breadcrumbs allow users to make selections from a range of values. Material UI for React has this component available for us, and it is very easy to integrate. We can use Breadcrumbs Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core Project Structure: It will look like the following. Project Structure Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from "react";import Link from "@material-ui/core/Link";import Typography from "@material-ui/core/Typography";import Breadcrumbs from "@material-ui/core/Breadcrumbs"; const App = () => { return ( <div style={{ margin: "auto", display: "table", }} > <h4>How to use Breadcrumbs in ReactJS?</h4> <Breadcrumbs aria-label="breadcrumb"> <Link color="inherit" href="/" onClick={(event) => { event.preventDefault(); alert("Home Page Clicked"); }} > Home Page </Link> <Link color="inherit" href="/getting-started/installation/" onClick={(event) => { event.preventDefault(); alert("Dashboard Clicked"); }} > Dashboard </Link> <Typography color="textPrimary"> Breadcrumb </Typography> </Breadcrumbs> </div> );}; export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. React-Questions ReactJS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? How to Use Bootstrap with React? React-Router Hooks How to navigate on path by button click in react router ? How to check the version of ReactJS ? How to Create a Countdown Timer Using ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Feb, 2021" }, { "code": null, "e": 262, "s": 28, "text": "Breadcrumbs allow users to make selections from a range of values. Material UI for React has this component available for us, and it is very easy to integrate. We can use Breadcrumbs Component in ReactJS using the following approach." }, { "code": null, "e": 312, "s": 262, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 376, "s": 312, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 408, "s": 376, "text": "npx create-react-app foldername" }, { "code": null, "e": 508, "s": 408, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 522, "s": 508, "text": "cd foldername" }, { "code": null, "e": 631, "s": 522, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 661, "s": 631, "text": "npm install @material-ui/core" }, { "code": null, "e": 713, "s": 661, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 731, "s": 713, "text": "Project Structure" }, { "code": null, "e": 870, "s": 731, "text": "Filename- App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 881, "s": 870, "text": "Javascript" }, { "code": "import React from \"react\";import Link from \"@material-ui/core/Link\";import Typography from \"@material-ui/core/Typography\";import Breadcrumbs from \"@material-ui/core/Breadcrumbs\"; const App = () => { return ( <div style={{ margin: \"auto\", display: \"table\", }} > <h4>How to use Breadcrumbs in ReactJS?</h4> <Breadcrumbs aria-label=\"breadcrumb\"> <Link color=\"inherit\" href=\"/\" onClick={(event) => { event.preventDefault(); alert(\"Home Page Clicked\"); }} > Home Page </Link> <Link color=\"inherit\" href=\"/getting-started/installation/\" onClick={(event) => { event.preventDefault(); alert(\"Dashboard Clicked\"); }} > Dashboard </Link> <Typography color=\"textPrimary\"> Breadcrumb </Typography> </Breadcrumbs> </div> );}; export default App;", "e": 1867, "s": 881, "text": null }, { "code": null, "e": 1980, "s": 1867, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1990, "s": 1980, "text": "npm start" }, { "code": null, "e": 2089, "s": 1990, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 2105, "s": 2089, "text": "React-Questions" }, { "code": null, "e": 2113, "s": 2105, "text": "ReactJS" }, { "code": null, "e": 2211, "s": 2113, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2249, "s": 2211, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2276, "s": 2249, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2315, "s": 2276, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 2367, "s": 2315, "text": "How to create a multi-page website using React.js ?" }, { "code": null, "e": 2406, "s": 2367, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 2439, "s": 2406, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 2458, "s": 2439, "text": "React-Router Hooks" }, { "code": null, "e": 2516, "s": 2458, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 2554, "s": 2516, "text": "How to check the version of ReactJS ?" } ]
How to Install Pyproj on Windows?
22 Sep, 2021 Pyproj is an Interface for the cartographic projections and coordinate transformations library (PROJ). In this article, we will look into the process of installing the Pyproj interface on a windows machine. The only thing that you need for installing Numpy on Windows are: Python PIP or Conda (depending upon user preference)) If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command: conda install -c anaconda pyproj Type y for yes when prompted. You will get a similar message once the installation is complete: Make sure you follow the best practices for installation using conda as: Use an environment for installation rather than in the base environment using the below command: conda create -n my-env conda activate my-env Note: If your preferred method of installation is conda-forge, use the below command: conda config --env --add channels conda-forge To verify if the Pyproj interface has been successfully installed in your system run the below command in Anaconda Powershell Prompt: conda list pyproj You’ll get the below message if the installation is complete: If you want the installation to be done through PIP, open up the Command Prompt and use the below command: pip install pyproj You will get a similar message once the installation is complete: To verify if the Pyproj interface has been successfully installed in your system run the below command in Command Prompt: python -m pip show pyproj You’ll get the below message if the installation is complete: Blogathon-2021 how-to-install Picked Blogathon How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Sep, 2021" }, { "code": null, "e": 235, "s": 28, "text": "Pyproj is an Interface for the cartographic projections and coordinate transformations library (PROJ). In this article, we will look into the process of installing the Pyproj interface on a windows machine." }, { "code": null, "e": 301, "s": 235, "text": "The only thing that you need for installing Numpy on Windows are:" }, { "code": null, "e": 309, "s": 301, "text": "Python " }, { "code": null, "e": 356, "s": 309, "text": "PIP or Conda (depending upon user preference))" }, { "code": null, "e": 478, "s": 356, "text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:" }, { "code": null, "e": 511, "s": 478, "text": "conda install -c anaconda pyproj" }, { "code": null, "e": 541, "s": 511, "text": "Type y for yes when prompted." }, { "code": null, "e": 607, "s": 541, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 680, "s": 607, "text": "Make sure you follow the best practices for installation using conda as:" }, { "code": null, "e": 777, "s": 680, "text": "Use an environment for installation rather than in the base environment using the below command:" }, { "code": null, "e": 822, "s": 777, "text": "conda create -n my-env\nconda activate my-env" }, { "code": null, "e": 908, "s": 822, "text": "Note: If your preferred method of installation is conda-forge, use the below command:" }, { "code": null, "e": 954, "s": 908, "text": "conda config --env --add channels conda-forge" }, { "code": null, "e": 1088, "s": 954, "text": "To verify if the Pyproj interface has been successfully installed in your system run the below command in Anaconda Powershell Prompt:" }, { "code": null, "e": 1106, "s": 1088, "text": "conda list pyproj" }, { "code": null, "e": 1168, "s": 1106, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 1276, "s": 1168, "text": "If you want the installation to be done through PIP, open up the Command Prompt and use the below command:" }, { "code": null, "e": 1295, "s": 1276, "text": "pip install pyproj" }, { "code": null, "e": 1361, "s": 1295, "text": "You will get a similar message once the installation is complete:" }, { "code": null, "e": 1483, "s": 1361, "text": "To verify if the Pyproj interface has been successfully installed in your system run the below command in Command Prompt:" }, { "code": null, "e": 1509, "s": 1483, "text": "python -m pip show pyproj" }, { "code": null, "e": 1571, "s": 1509, "text": "You’ll get the below message if the installation is complete:" }, { "code": null, "e": 1586, "s": 1571, "text": "Blogathon-2021" }, { "code": null, "e": 1601, "s": 1586, "text": "how-to-install" }, { "code": null, "e": 1608, "s": 1601, "text": "Picked" }, { "code": null, "e": 1618, "s": 1608, "text": "Blogathon" }, { "code": null, "e": 1625, "s": 1618, "text": "How To" }, { "code": null, "e": 1644, "s": 1625, "text": "Installation Guide" } ]
GATE | GATE-CS-2017 (Set 2) | Question 58
28 Jun, 2021 A message is made up entirely of characters from the set X = {P,Q,R,S,T} . The table of probabilities of each character is shown below : A message of 100 characters over X is encoded using Huffman coding. Then the excepted length of the encoded message in bits is _____(A) 225(B) 226(C) 227(D) 228Answer: (A)Explanation: In Huffman coding, we pick the least two frequent (or probable) character, combine them and create a new node. .08 (T) 0.17(R) 0.19(S) 0.22(P) \ / \ / 0.25 0.34(Q) 0.47 \ / / 0.59 / \ / 1 Looking at above tree structure, Number of bits required by each:P – 2Q – 2R – 3S – 2T – 3 Therefore, excepted length of the encoded message = 3*0.8 + 3*0.17 + 2*0.19 + 2 *0.22 + 2*0.34 = 2.25 For 100 characters, 2.25*100 = 225 Therefore, option A is correct. Quiz of this Question GATE-CS-2017 (Set 2) GATE-GATE-CS-2017 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE-CS-2016 (Set 1) | Question 45 GATE | GATE CS 1996 | Question 63
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 189, "s": 52, "text": "A message is made up entirely of characters from the set X = {P,Q,R,S,T} . The table of probabilities of each character is shown below :" }, { "code": null, "e": 373, "s": 189, "text": "A message of 100 characters over X is encoded using Huffman coding. Then the excepted length of the encoded message in bits is _____(A) 225(B) 226(C) 227(D) 228Answer: (A)Explanation:" }, { "code": null, "e": 746, "s": 373, "text": "In Huffman coding, we pick the least\ntwo frequent (or probable) character, combine them and create\na new node.\n\n .08 (T) 0.17(R) 0.19(S) 0.22(P)\n \\ / \\ /\n 0.25 0.34(Q) 0.47\n \\ / /\n 0.59 /\n \\ /\n 1" }, { "code": null, "e": 837, "s": 746, "text": "Looking at above tree structure, Number of bits required by each:P – 2Q – 2R – 3S – 2T – 3" }, { "code": null, "e": 887, "s": 837, "text": "Therefore, excepted length of the encoded message" }, { "code": null, "e": 934, "s": 887, "text": "= 3*0.8 + 3*0.17 + 2*0.19 + 2 *0.22 + 2*0.34" }, { "code": null, "e": 941, "s": 934, "text": "= 2.25" }, { "code": null, "e": 976, "s": 941, "text": "For 100 characters, 2.25*100 = 225" }, { "code": null, "e": 1008, "s": 976, "text": "Therefore, option A is correct." }, { "code": null, "e": 1031, "s": 1008, "text": " Quiz of this Question" }, { "code": null, "e": 1052, "s": 1031, "text": "GATE-CS-2017 (Set 2)" }, { "code": null, "e": 1078, "s": 1052, "text": "GATE-GATE-CS-2017 (Set 2)" }, { "code": null, "e": 1083, "s": 1078, "text": "GATE" }, { "code": null, "e": 1181, "s": 1083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1223, "s": 1181, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1285, "s": 1223, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1319, "s": 1285, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1361, "s": 1319, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1403, "s": 1361, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1437, "s": 1403, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 1471, "s": 1437, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 1505, "s": 1471, "text": "GATE | GATE-CS-2004 | Question 31" }, { "code": null, "e": 1547, "s": 1505, "text": "GATE | GATE-CS-2016 (Set 1) | Question 45" } ]
Runtime and Compile-time constants in C++
19 Oct, 2020 Run-time Constant: These are the constants whose respective values can only be known or computed at the time of running of source code. Run time Constants are a bit slower than compile-time constants but are more flexible than compile-time constants. However, once it is initialized, the value of these constants can’t be changed. Below is the program for illustration of Runtime constants: C++ // C++ program to illustrate// Run-time Constants#include <iostream>using namespace std; // Driver Codeint main(){ // Input a variable double electonmass; cin >> electonmass; // Define a constant // and initialize it at // run-time const double electon_mass{ electonmass }; // Known to the compiler // at the run-time cout << electon_mass << endl; return 0;} 2.07335e-317 Compile-time Constant: These are the constants whose respective value is known or computed at the time of compilation of source code. Compile-time constants are faster than run-time constants but are less flexible than run-time constants. Below is the program for illustration of Compile-time Constant: C++ // C++ program to illustrate// compile-time constants#include <iostream>using namespace std; // Driver Codeint main(){ // Declare and initialize // compile time constant const double electron_q{ 1.6e-19 }; // Value known to compiler // at compile-time cout << electron_q << endl; return 0;} 1.6e-19 A runtime constant can have a different value each time the source code is run. It is generally used while declaring an array size. It is not preferred for declaring an array size. Same compilation error, if runtime constant is used for initializing an enumerator. const keyword CPP-Basics cpp-data-types Programming Basics C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Oct, 2020" }, { "code": null, "e": 47, "s": 28, "text": "Run-time Constant:" }, { "code": null, "e": 359, "s": 47, "text": "These are the constants whose respective values can only be known or computed at the time of running of source code. Run time Constants are a bit slower than compile-time constants but are more flexible than compile-time constants. However, once it is initialized, the value of these constants can’t be changed." }, { "code": null, "e": 419, "s": 359, "text": "Below is the program for illustration of Runtime constants:" }, { "code": null, "e": 423, "s": 419, "text": "C++" }, { "code": "// C++ program to illustrate// Run-time Constants#include <iostream>using namespace std; // Driver Codeint main(){ // Input a variable double electonmass; cin >> electonmass; // Define a constant // and initialize it at // run-time const double electon_mass{ electonmass }; // Known to the compiler // at the run-time cout << electon_mass << endl; return 0;}", "e": 822, "s": 423, "text": null }, { "code": null, "e": 836, "s": 822, "text": "2.07335e-317\n" }, { "code": null, "e": 859, "s": 836, "text": "Compile-time Constant:" }, { "code": null, "e": 1075, "s": 859, "text": "These are the constants whose respective value is known or computed at the time of compilation of source code. Compile-time constants are faster than run-time constants but are less flexible than run-time constants." }, { "code": null, "e": 1139, "s": 1075, "text": "Below is the program for illustration of Compile-time Constant:" }, { "code": null, "e": 1143, "s": 1139, "text": "C++" }, { "code": "// C++ program to illustrate// compile-time constants#include <iostream>using namespace std; // Driver Codeint main(){ // Declare and initialize // compile time constant const double electron_q{ 1.6e-19 }; // Value known to compiler // at compile-time cout << electron_q << endl; return 0;}", "e": 1460, "s": 1143, "text": null }, { "code": null, "e": 1469, "s": 1460, "text": "1.6e-19\n" }, { "code": null, "e": 1549, "s": 1469, "text": "A runtime constant can have a different value each time the source code is run." }, { "code": null, "e": 1601, "s": 1549, "text": "It is generally used while declaring an array size." }, { "code": null, "e": 1650, "s": 1601, "text": "It is not preferred for declaring an array size." }, { "code": null, "e": 1734, "s": 1650, "text": "Same compilation error, if runtime constant is used for initializing an enumerator." }, { "code": null, "e": 1748, "s": 1734, "text": "const keyword" }, { "code": null, "e": 1759, "s": 1748, "text": "CPP-Basics" }, { "code": null, "e": 1774, "s": 1759, "text": "cpp-data-types" }, { "code": null, "e": 1793, "s": 1774, "text": "Programming Basics" }, { "code": null, "e": 1797, "s": 1793, "text": "C++" }, { "code": null, "e": 1810, "s": 1797, "text": "C++ Programs" }, { "code": null, "e": 1814, "s": 1810, "text": "CPP" } ]
JavaScript | Uint8Array.from() Method
28 Jan, 2020 The Uint8Array array represents an array of 8-bit unsigned integers. By default, the contents of Uint8Array are initialized to 0. The Uint8Array.from() method is used to create a new Uint8Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object then you can be used this function by passing the object as a parameter to this function along with map function and value used for map function if needed. Syntax: Uint8Array.from( source, mapFn, thisArg ) parameters: This method accept three parameters as mentioned above and described below: source: This parameter contains an array-like or iterable object which is used to convert to a Uint8Array object. mapFn: It is an optional parameter which is Map function to call on every element of the Uint8Array array. thisArg: It is an optional parameter which store the value to use as this when executing mapFn. Return Value: This method returns a new Uint8Array instance. Below example illustrate the working of Uint8Array.from() method in JavaScript: Program 1: <script> // Create a Uint8Array from a string like structurevar array = Uint8Array.from('45465768654323456'); // Print the resultdocument.write(array);</script> 4, 5, 4, 6, 5, 7, 6, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6 Program 2: <script> // Create a Uint8Array from a array by adding// 3 to each number using functionvar array = Uint8Array.from([1, 2, 3, 4, 5, 6], z => z+3); // Print the resultdocument.write(array);</script> 4, 5, 6, 7, 8, 9 References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from javascript-array javascript-functions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js | fs.writeFileSync() Method How do you run JavaScript script through the Terminal? Difference between var, let and const keywords in JavaScript JavaScript | console.log() with Examples Differences between Functional Components and Class Components in React Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript REST API (Introduction) How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2020" }, { "code": null, "e": 158, "s": 28, "text": "The Uint8Array array represents an array of 8-bit unsigned integers. By default, the contents of Uint8Array are initialized to 0." }, { "code": null, "e": 477, "s": 158, "text": "The Uint8Array.from() method is used to create a new Uint8Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object then you can be used this function by passing the object as a parameter to this function along with map function and value used for map function if needed." }, { "code": null, "e": 485, "s": 477, "text": "Syntax:" }, { "code": null, "e": 527, "s": 485, "text": "Uint8Array.from( source, mapFn, thisArg )" }, { "code": null, "e": 615, "s": 527, "text": "parameters: This method accept three parameters as mentioned above and described below:" }, { "code": null, "e": 729, "s": 615, "text": "source: This parameter contains an array-like or iterable object which is used to convert to a Uint8Array object." }, { "code": null, "e": 836, "s": 729, "text": "mapFn: It is an optional parameter which is Map function to call on every element of the Uint8Array array." }, { "code": null, "e": 932, "s": 836, "text": "thisArg: It is an optional parameter which store the value to use as this when executing mapFn." }, { "code": null, "e": 993, "s": 932, "text": "Return Value: This method returns a new Uint8Array instance." }, { "code": null, "e": 1073, "s": 993, "text": "Below example illustrate the working of Uint8Array.from() method in JavaScript:" }, { "code": null, "e": 1084, "s": 1073, "text": "Program 1:" }, { "code": "<script> // Create a Uint8Array from a string like structurevar array = Uint8Array.from('45465768654323456'); // Print the resultdocument.write(array);</script>", "e": 1248, "s": 1084, "text": null }, { "code": null, "e": 1298, "s": 1248, "text": "4, 5, 4, 6, 5, 7, 6, 8, 6, 5, 4, 3, 2, 3, 4, 5, 6" }, { "code": null, "e": 1309, "s": 1298, "text": "Program 2:" }, { "code": "<script> // Create a Uint8Array from a array by adding// 3 to each number using functionvar array = Uint8Array.from([1, 2, 3, 4, 5, 6], z => z+3); // Print the resultdocument.write(array);</script>", "e": 1510, "s": 1309, "text": null }, { "code": null, "e": 1527, "s": 1510, "text": "4, 5, 6, 7, 8, 9" }, { "code": null, "e": 1636, "s": 1527, "text": "References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from" }, { "code": null, "e": 1653, "s": 1636, "text": "javascript-array" }, { "code": null, "e": 1674, "s": 1653, "text": "javascript-functions" }, { "code": null, "e": 1685, "s": 1674, "text": "JavaScript" }, { "code": null, "e": 1702, "s": 1685, "text": "Web Technologies" }, { "code": null, "e": 1800, "s": 1702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1836, "s": 1800, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 1891, "s": 1836, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 1952, "s": 1891, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1993, "s": 1952, "text": "JavaScript | console.log() with Examples" }, { "code": null, "e": 2065, "s": 1993, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2098, "s": 2065, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2160, "s": 2098, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2221, "s": 2160, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2245, "s": 2221, "text": "REST API (Introduction)" } ]
jQuery | children() with Examples
03 Aug, 2021 children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements. Syntax: $(selector).children() Here selector is the selected element whose children are going to be found.Parameter: It does not accept any parameters.Return values: It returns all the children of the selected element. <html> <head> <style> .parent * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("div").children().css({ "color": "green", "border": "2px solid green" }); }); </script></head> <body> <div class="parent" style="width:500px;">This is the current element !!! <p>This is first children <span>This is grandchild</span> </p> <p>This is Second children <span>This is grandchild</span> </p> </div> </body> </html> Output: An optional parameter can also be used to the children() method to filter the search for children elements.Syntax: $(selector1).children("selector2") Here selector1 is the selected element whose children are going to be found.Parameters: It accepts a parameter which is specified below- selector2: This is the prior children among all the children of the selected element. Return value: It returns the prior children of the selected element. Code #2: In the below code, among all the paragraph element, elements of first paragraph gets selected and highlighted with thegreen color. <html> <head> <style> .descendants * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $("div").children("p.first").css({ "color": "green", "border": "2px solid green" }); }); </script></head> <body> <div class="descendants" style="width:500px;">This is the current element !!! <p class="first">This is the first paragraph element !!! <span>This is grandchild</span> </p> <p class="second">This is the second paragraph element !!! <span>This is grandchild</span> </p> </div> </body> </html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of β€œWrite less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Traversing JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Roadmap to Learn JavaScript For Beginners JQuery | Set the value of an input text field How to change selected value of a drop-down list using jQuery? Form validation using jQuery How to add options to a select element using jQuery? How to Dynamically Add/Remove Table Rows using jQuery ?
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 265, "s": 28, "text": "children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements." }, { "code": null, "e": 273, "s": 265, "text": "Syntax:" }, { "code": null, "e": 297, "s": 273, "text": "$(selector).children()\n" }, { "code": null, "e": 485, "s": 297, "text": "Here selector is the selected element whose children are going to be found.Parameter: It does not accept any parameters.Return values: It returns all the children of the selected element." }, { "code": "<html> <head> <style> .parent * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { $(\"div\").children().css({ \"color\": \"green\", \"border\": \"2px solid green\" }); }); </script></head> <body> <div class=\"parent\" style=\"width:500px;\">This is the current element !!! <p>This is first children <span>This is grandchild</span> </p> <p>This is Second children <span>This is grandchild</span> </p> </div> </body> </html>", "e": 1305, "s": 485, "text": null }, { "code": null, "e": 1313, "s": 1305, "text": "Output:" }, { "code": null, "e": 1428, "s": 1313, "text": "An optional parameter can also be used to the children() method to filter the search for children elements.Syntax:" }, { "code": null, "e": 1464, "s": 1428, "text": "$(selector1).children(\"selector2\")\n" }, { "code": null, "e": 1601, "s": 1464, "text": "Here selector1 is the selected element whose children are going to be found.Parameters: It accepts a parameter which is specified below-" }, { "code": null, "e": 1687, "s": 1601, "text": "selector2: This is the prior children among all the children of the selected element." }, { "code": null, "e": 1756, "s": 1687, "text": "Return value: It returns the prior children of the selected element." }, { "code": null, "e": 1896, "s": 1756, "text": "Code #2: In the below code, among all the paragraph element, elements of first paragraph gets selected and highlighted with thegreen color." }, { "code": "<html> <head> <style> .descendants * { display: block; border: 2px solid lightgrey; color: grey; padding: 5px; margin: 15px; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/ jquery/3.3.1/jquery.min.js\"></script> <script> $(document).ready(function() { $(\"div\").children(\"p.first\").css({ \"color\": \"green\", \"border\": \"2px solid green\" }); }); </script></head> <body> <div class=\"descendants\" style=\"width:500px;\">This is the current element !!! <p class=\"first\">This is the first paragraph element !!! <span>This is grandchild</span> </p> <p class=\"second\">This is the second paragraph element !!! <span>This is grandchild</span> </p> </div> </body> </html>", "e": 2799, "s": 1896, "text": null }, { "code": null, "e": 2807, "s": 2799, "text": "Output:" }, { "code": null, "e": 3075, "s": 2807, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of β€œWrite less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 3093, "s": 3075, "text": "jQuery-Traversing" }, { "code": null, "e": 3104, "s": 3093, "text": "JavaScript" }, { "code": null, "e": 3111, "s": 3104, "text": "JQuery" }, { "code": null, "e": 3209, "s": 3111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3270, "s": 3209, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3342, "s": 3270, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3382, "s": 3342, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3435, "s": 3382, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 3477, "s": 3435, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3523, "s": 3477, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 3586, "s": 3523, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 3615, "s": 3586, "text": "Form validation using jQuery" }, { "code": null, "e": 3668, "s": 3615, "text": "How to add options to a select element using jQuery?" } ]
Switch in Kotlin
27 Jan, 2022 Android Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = β€œtrue” in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically.First, we create a new project by following the below steps: Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish. Click on File, then New => New Project. After that include the Kotlin support and click on next. Select the minimum SDK as per convenience and click next button. Then select the Empty activity => next => finish. In this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <Switch android:id="@+id/switch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch1"/> <Switch android:id="@+id/switch2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch2"/></LinearLayout> Add application name in strings.xml. XML <resources> <string name="app_name">SwitchInKotlin</string></resources> Here, we will access the switches by using their respective id’s and set click Listener and Toast message if a switch is checked(ON) state. First of all, declare a variable to get the switch using it’s id. val sw1 = findViewById(R.id.switch1) then, set OnClick listener on the switch and use if condition to check the state of the button. sw1?.setOnCheckedChangeListener({ _ , isChecked -> val message = if (isChecked) "Switch1:ON" else "Switch1:OFF" Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() }) Repeat the process for another switch in the kotlin file. Kotlin package com.geeksforgeeks.myfirstkotlinappimport android.os.Bundleimport android.widget.Switchimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sw1 = findViewById<Switch>(R.id.switch1) sw1?.setOnCheckedChangeListener({ _ , isChecked -> val message = if (isChecked) "Switch1:ON" else "Switch1:OFF" Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() }) val sw2 = findViewById<Switch>(R.id.switch2) sw2?.setOnCheckedChangeListener({ _ , isChecked -> val message = if (isChecked) "Switch2:ON" else "Switch2:OFF" Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() }) }} XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <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> Here, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently. ayushpandey3july Kotlin Android Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android RecyclerView in Kotlin Broadcast Receiver in Android With Example How to Communicate Between Fragments in Android? Content Providers in Android with Example Retrofit with Kotlin Coroutine in Android Kotlin constructor Kotlin Setters and Getters How to Add and Customize Back Button of Action Bar in Android? Suspend Function In Kotlin Coroutines
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2022" }, { "code": null, "e": 759, "s": 28, "text": "Android Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = β€œtrue” in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically.First, we create a new project by following the below steps: " }, { "code": null, "e": 968, "s": 759, "text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish." }, { "code": null, "e": 1008, "s": 968, "text": "Click on File, then New => New Project." }, { "code": null, "e": 1065, "s": 1008, "text": "After that include the Kotlin support and click on next." }, { "code": null, "e": 1130, "s": 1065, "text": "Select the minimum SDK as per convenience and click next button." }, { "code": null, "e": 1180, "s": 1130, "text": "Then select the Empty activity => next => finish." }, { "code": null, "e": 1319, "s": 1186, "text": "In this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc. " }, { "code": null, "e": 1323, "s": 1319, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:orientation=\"vertical\"> <Switch android:id=\"@+id/switch1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Switch1\"/> <Switch android:id=\"@+id/switch2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Switch2\"/></LinearLayout>", "e": 1921, "s": 1323, "text": null }, { "code": null, "e": 1960, "s": 1921, "text": "Add application name in strings.xml. " }, { "code": null, "e": 1964, "s": 1960, "text": "XML" }, { "code": "<resources> <string name=\"app_name\">SwitchInKotlin</string></resources>", "e": 2039, "s": 1964, "text": null }, { "code": null, "e": 2247, "s": 2039, "text": "Here, we will access the switches by using their respective id’s and set click Listener and Toast message if a switch is checked(ON) state. First of all, declare a variable to get the switch using it’s id. " }, { "code": null, "e": 2284, "s": 2247, "text": "val sw1 = findViewById(R.id.switch1)" }, { "code": null, "e": 2382, "s": 2284, "text": "then, set OnClick listener on the switch and use if condition to check the state of the button. " }, { "code": null, "e": 2617, "s": 2382, "text": " \nsw1?.setOnCheckedChangeListener({ _ , isChecked ->\n val message = if (isChecked) \"Switch1:ON\" else \"Switch1:OFF\"\n Toast.makeText(this@MainActivity, message,\n Toast.LENGTH_SHORT).show()\n })" }, { "code": null, "e": 2677, "s": 2617, "text": "Repeat the process for another switch in the kotlin file. " }, { "code": null, "e": 2684, "s": 2677, "text": "Kotlin" }, { "code": "package com.geeksforgeeks.myfirstkotlinappimport android.os.Bundleimport android.widget.Switchimport android.widget.Toastimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sw1 = findViewById<Switch>(R.id.switch1) sw1?.setOnCheckedChangeListener({ _ , isChecked -> val message = if (isChecked) \"Switch1:ON\" else \"Switch1:OFF\" Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() }) val sw2 = findViewById<Switch>(R.id.switch2) sw2?.setOnCheckedChangeListener({ _ , isChecked -> val message = if (isChecked) \"Switch2:ON\" else \"Switch2:OFF\" Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() }) }}", "e": 3625, "s": 2684, "text": null }, { "code": null, "e": 3629, "s": 3625, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>", "e": 4281, "s": 3629, "text": null }, { "code": null, "e": 4411, "s": 4281, "text": "Here, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently. " }, { "code": null, "e": 4432, "s": 4415, "text": "ayushpandey3july" }, { "code": null, "e": 4447, "s": 4432, "text": "Kotlin Android" }, { "code": null, "e": 4454, "s": 4447, "text": "Kotlin" }, { "code": null, "e": 4552, "s": 4454, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4621, "s": 4552, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 4652, "s": 4621, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 4695, "s": 4652, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 4744, "s": 4695, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 4786, "s": 4744, "text": "Content Providers in Android with Example" }, { "code": null, "e": 4828, "s": 4786, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 4847, "s": 4828, "text": "Kotlin constructor" }, { "code": null, "e": 4874, "s": 4847, "text": "Kotlin Setters and Getters" }, { "code": null, "e": 4937, "s": 4874, "text": "How to Add and Customize Back Button of Action Bar in Android?" } ]
Java - String toUpperCase() Method
This method has two variants. The first variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.getDefault()). The second variant takes locale as an argument to be used while converting into upper case. Here is the syntax of this method βˆ’ public String toUpperCase() Here is the detail of parameters βˆ’ NA NA It returns the String, converted to uppercase. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :" ); System.out.println(Str.toUpperCase() ); } } This will produce the following result βˆ’ Return Value :WELCOME TO TUTORIALSPOINT.COM
[ { "code": null, "e": 2720, "s": 2511, "text": "This method has two variants. The first variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.getDefault())." }, { "code": null, "e": 2812, "s": 2720, "text": "The second variant takes locale as an argument to be used while converting into upper case." }, { "code": null, "e": 2848, "s": 2812, "text": "Here is the syntax of this method βˆ’" }, { "code": null, "e": 2877, "s": 2848, "text": "public String toUpperCase()\n" }, { "code": null, "e": 2912, "s": 2877, "text": "Here is the detail of parameters βˆ’" }, { "code": null, "e": 2915, "s": 2912, "text": "NA" }, { "code": null, "e": 2918, "s": 2915, "text": "NA" }, { "code": null, "e": 2965, "s": 2918, "text": "It returns the String, converted to uppercase." }, { "code": null, "e": 3209, "s": 2965, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.toUpperCase() );\n }\n}" }, { "code": null, "e": 3250, "s": 3209, "text": "This will produce the following result βˆ’" } ]
Find the common elements of more than two JavaScript arrays ?
02 Mar, 2020 Given an HTML document having multiple arrays with some elements and the task is to get the common elements from arrays with the help of JavaScript. There are two approaches that are discussed below. Approach 1: First get the arrays in 2-dimensional format then take the first array by shift() method and then filter out the elements from the first array which are common in all by using filter() method. The elements which are common in all arrays can be checked by every() method and if the element of first array matches with all elements then that element is returned. Example:<!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=""> <h1 > GeeksforGeeks </h1> <p id="geeks"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="gfg" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = "Click on button to get the common elements from these"+ " array<br>Array1 - [" + arr1 + "]<br>Array2 -"+ " [" + arr2 + "]<br>Array3 - [" + arr3 + "]"; function GFG_Fun() { arr4 = arr.slice(); down.innerHTML = arr4.shift().filter(function(v) { return arr4.every(function(a) { return a.indexOf(v) !== -1; }); }); } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=""> <h1 > GeeksforGeeks </h1> <p id="geeks"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="gfg" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = "Click on button to get the common elements from these"+ " array<br>Array1 - [" + arr1 + "]<br>Array2 -"+ " [" + arr2 + "]<br>Array3 - [" + arr3 + "]"; function GFG_Fun() { arr4 = arr.slice(); down.innerHTML = arr4.shift().filter(function(v) { return arr4.every(function(a) { return a.indexOf(v) !== -1; }); }); } </script></body> </html> Output: Approach 2: First get the arrays in 2-dimensional format then use the reduce() method to get the access to all arrays one by one. variable(p) contains each array one by one and returns only elements of the array which are in variable(c) array by using filter() method. At the end variable(c) contains the array of common elements. Example:<!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=""> <h1 > GeeksforGeeks </h1> <p id="geeks"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="gfg" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = "Click on button to get the common elements from these"+ " array<br>Array1 - [" + arr1 + "]<br>Array2 -"+ " [" + arr2 + "]<br>Array3 - [" + arr3 + "]"; function GFG_Fun() { down.innerHTML = arr.reduce((p, c) => p.filter(e => c.includes(e))); } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=""> <h1 > GeeksforGeeks </h1> <p id="geeks"> </p> <button onClick="GFG_Fun()"> click here </button> <p id="gfg" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = "Click on button to get the common elements from these"+ " array<br>Array1 - [" + arr1 + "]<br>Array2 -"+ " [" + arr2 + "]<br>Array3 - [" + arr3 + "]"; function GFG_Fun() { down.innerHTML = arr.reduce((p, c) => p.filter(e => c.includes(e))); } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Mar, 2020" }, { "code": null, "e": 253, "s": 53, "text": "Given an HTML document having multiple arrays with some elements and the task is to get the common elements from arrays with the help of JavaScript. There are two approaches that are discussed below." }, { "code": null, "e": 626, "s": 253, "text": "Approach 1: First get the arrays in 2-dimensional format then take the first array by shift() method and then filter out the elements from the first array which are common in all by using filter() method. The elements which are common in all arrays can be checked by every() method and if the element of first array matches with all elements then that element is returned." }, { "code": null, "e": 2016, "s": 626, "text": "Example:<!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=\"\"> <h1 > GeeksforGeeks </h1> <p id=\"geeks\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"gfg\" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = \"Click on button to get the common elements from these\"+ \" array<br>Array1 - [\" + arr1 + \"]<br>Array2 -\"+ \" [\" + arr2 + \"]<br>Array3 - [\" + arr3 + \"]\"; function GFG_Fun() { arr4 = arr.slice(); down.innerHTML = arr4.shift().filter(function(v) { return arr4.every(function(a) { return a.indexOf(v) !== -1; }); }); } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=\"\"> <h1 > GeeksforGeeks </h1> <p id=\"geeks\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"gfg\" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = \"Click on button to get the common elements from these\"+ \" array<br>Array1 - [\" + arr1 + \"]<br>Array2 -\"+ \" [\" + arr2 + \"]<br>Array3 - [\" + arr3 + \"]\"; function GFG_Fun() { arr4 = arr.slice(); down.innerHTML = arr4.shift().filter(function(v) { return arr4.every(function(a) { return a.indexOf(v) !== -1; }); }); } </script></body> </html>", "e": 3398, "s": 2016, "text": null }, { "code": null, "e": 3406, "s": 3398, "text": "Output:" }, { "code": null, "e": 3737, "s": 3406, "text": "Approach 2: First get the arrays in 2-dimensional format then use the reduce() method to get the access to all arrays one by one. variable(p) contains each array one by one and returns only elements of the array which are in variable(c) array by using filter() method. At the end variable(c) contains the array of common elements." }, { "code": null, "e": 4986, "s": 3737, "text": "Example:<!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=\"\"> <h1 > GeeksforGeeks </h1> <p id=\"geeks\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"gfg\" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = \"Click on button to get the common elements from these\"+ \" array<br>Array1 - [\" + arr1 + \"]<br>Array2 -\"+ \" [\" + arr2 + \"]<br>Array3 - [\" + arr3 + \"]\"; function GFG_Fun() { down.innerHTML = arr.reduce((p, c) => p.filter(e => c.includes(e))); } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> Finding matches between more than 2 JavaScript arrays </title> <style> body { text-align:center; } h1 { color: green; } #geeks { font-size: 16px; font-weight: bold; } #gfg { color: green; font-size: 18px; font-weight: bold; } </style></head> <body style=\"\"> <h1 > GeeksforGeeks </h1> <p id=\"geeks\"> </p> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"gfg\" > </p> <script> var up = document.getElementById('geeks'); var down = document.getElementById('gfg'); var arr1 = [1, 3, 5, 7, 9]; var arr2 = [1, 2, 4, 5, 7]; var arr3 = [1, 2, 5, 7, 8]; var arr = [arr1, arr2, arr3]; up.innerHTML = \"Click on button to get the common elements from these\"+ \" array<br>Array1 - [\" + arr1 + \"]<br>Array2 -\"+ \" [\" + arr2 + \"]<br>Array3 - [\" + arr3 + \"]\"; function GFG_Fun() { down.innerHTML = arr.reduce((p, c) => p.filter(e => c.includes(e))); } </script></body> </html>", "e": 6227, "s": 4986, "text": null }, { "code": null, "e": 6235, "s": 6227, "text": "Output:" }, { "code": null, "e": 6244, "s": 6235, "text": "CSS-Misc" }, { "code": null, "e": 6254, "s": 6244, "text": "HTML-Misc" }, { "code": null, "e": 6270, "s": 6254, "text": "JavaScript-Misc" }, { "code": null, "e": 6274, "s": 6270, "text": "CSS" }, { "code": null, "e": 6279, "s": 6274, "text": "HTML" }, { "code": null, "e": 6290, "s": 6279, "text": "JavaScript" }, { "code": null, "e": 6307, "s": 6290, "text": "Web Technologies" }, { "code": null, "e": 6334, "s": 6307, "text": "Web technologies Questions" }, { "code": null, "e": 6339, "s": 6334, "text": "HTML" } ]
Implementation of Bayesian Regression
12 Jan, 2022 Regression is a Machine Learning task to predict continuous values (real numbers), as compared to classification, that is used to predict categorical (discrete) values. To learn more about the basics of regression, you can follow this link. When you hear the word, β€˜Bayesian’, you might think of Naive Bayes. However, Bayesian principles can also be used to perform regression. In this article, we will discuss and implement Bayesian Ridge Regression, which is not the same as regular Ridge Regression. To understand more about regular Ridge Regression, you can follow this link. First of all, you must understand that Bayesian is just an approach to defining and estimating statistical models. Bayesian Regression can be very useful when we have insufficient data in the dataset or the data is poorly distributed. The output of a Bayesian Regression model is obtained from a probability distribution, as compared to regular regression techniques where the output is just obtained from a single value of each attribute. The output, β€˜y’ is generated from a normal distribution (where mean and variance are normalized). The aim of Bayesian Linear Regression is not to find the model parameters, but rather to find the β€˜posteriorβ€˜ distribution for the model parameters. Not just the output y, but the model parameters are also assumed to come from a distribution. The expression for Posterior is :where Posterior: It is the probability of an event to occur; say, H, given that another event; say, E has already occurred. i.e., P(H | E). Prior: It is the probability of an event H has occurred prior to another event. i.e., P(H) Likelihood: It is a likelihood function in which some parameter variable is marginalized. This is actually equivalent to the Bayes’ Theorem which says, where A and B are events, P(A) is the probability of occurrence of A, and P(A|B) is the probability of A to occur given that event B has already occurred. P(B), the probability of event B occurring cannot be 0 since it has already occurred. If you want to learn more about regular Naive Bayes and Bayes Theorem, you can follow this link. Looking at the formula above, we can see that, in contrast to Ordinary Least Square (OLS), we have a posterior distribution for the model parameters which is proportional to the likelihood of the data multiplied by the prior probability of the parameters. As the number of data points increase, the value of likelihood will increase and will become much larger than the prior value. In the case of an infinite number of data points, the values for the parameters converge to the values obtained from OLS. So, we begin our regression process with an initial estimate (the prior value). As we start to cover more data points, our model becomes less wrong. So for Bayesian Ridge Regression, a large amount of training data is needed to make the model accurate. Now, let us have a quick brief overview of the mathematical side of things. In a linear model, if β€˜y’ is the predicted value, then where, β€˜w’ is the vector w. w consists of w0, w1, ... . β€˜x’ is the value of the weights. So, now for Bayesian Regression to obtain a fully probabilistic model, the output β€˜y’ is assumed to be the Gaussian distribution around Xw as shown below: where alpha is a hyper-parameter for the Gamma distribution prior. It is treated as a random variable estimated from the data. Here, the implementation for Bayesian Ridge Regression is given below. The mathematical expression on which Bayesian Ridge Regression works is : where alpha is the shape parameter for the Gamma distribution prior to the alpha parameter and lambda is the shape parameter for the Gamma distribution prior to the Lambda parameter.This is only a brief introduction to the mathematics that goes behind a Bayesian Ridge Regressor. The goal of this article is to give you a brief high-level overview of Bayesian regression; when to use it, advantages, disadvantages, and show you how to implement it. So, we have just given you a brief introduction to the mathematics behind Bayesian regression and Bayesian Ridge regression. We will not go much into the depth of how the mathematics works. Advantages of Bayesian Regression: Very effective when the size of the dataset is small. Particularly well-suited for on-line based learning (data is received in real-time), as compared to batch based learning, where we have the entire dataset on our hands before we start training the model. This is because Bayesian Regression doesn’t need to store data. The Bayesian approach is a tried and tested approach and is very robust, mathematically. So, one can use this without having any extra prior knowledge about the dataset. Disadvantages of Bayesian Regression: The inference of the model can be time-consuming. If there is a large amount of data available for our dataset, the Bayesian approach is not worth it and the regular frequentist approach does a more efficient job Implementation of Bayesian Regression Using Python: In this example, we will perform Bayesian Ridge Regression. However, the Bayesian approach can be used with any Regression technique like Linear Regression, Lasso Regression, etc. We will the scikit-learn library to implement Bayesian Ridge Regression. We will use the Boston Housing dataset that has information about the median value of a house in an area in Boston. You can learn more about this dataset here. For evaluation, we will use the r2 score. The best possible value of the r2 score is 1.0. If the model makes a constant prediction regardless of the attributes, the value of r2 score is 0. r2 score may also be negative for even worse models. To learn more about r2 scores, you can follow the link here. But before we get on to the code, you must understand the important parameters of a Bayesian Ridge Regressor: n_iter: Number of iterations. Default value = 100. tol: When to stop the algorithm given that the model has converged. Default value = 1e-3. alpha_1: Shape parameter of the regressor line (Gamma distribution) over the alpha parameter (used for regularization). Default value = 1e-6. alpha_2: Inverse scale parameter for the Gamma distribution over the alpha parameter. Default value = 1e-6. lambda_1: Shape parameter of the Gamma distribution over the lambda parameter. Default value = 1e-6. lambda_2: Inverse scale parameter of the Gamma distribution over the lambda parameter. Default value = 1e-6. NOTE: This code may not work on an online IDE. Run it on Google Colab or on your local machine. Code: Python3 # Importing modules that are requiredfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import r2_scorefrom sklearn.linear_model import BayesianRidge # Loading datasetdataset = load_boston()X, y = dataset.data, dataset.target # Splitting dataset into training and testing setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15, random_state = 42) # Creating and training modelmodel = BayesianRidge()model.fit(X_train, y_train) # Model making a prediction on test dataprediction = model.predict(X_test) # Evaluation of r2 score of the model against the test setprint(f"r2 Score Of Test Set : {r2_score(y_test, prediction)}") Output: r2 Score Of Test Set : 0.7943355984883815 We get an r2 score of approximately 0.7934 on the test set using Bayesian Ridge Regressor with all default parameters. This is an acceptable score. However, you may alter the alpha and lambda parameters discussed above to obtain better results for your dataset. Conclusion: So now that you know how Bayesian regressors work and when to use it, you should try using it next time you want to perform a regression task, especially if the dataset is small. References: scikit-learn Documentation. simmytarika5 Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jan, 2022" }, { "code": null, "e": 269, "s": 28, "text": "Regression is a Machine Learning task to predict continuous values (real numbers), as compared to classification, that is used to predict categorical (discrete) values. To learn more about the basics of regression, you can follow this link." }, { "code": null, "e": 608, "s": 269, "text": "When you hear the word, β€˜Bayesian’, you might think of Naive Bayes. However, Bayesian principles can also be used to perform regression. In this article, we will discuss and implement Bayesian Ridge Regression, which is not the same as regular Ridge Regression. To understand more about regular Ridge Regression, you can follow this link." }, { "code": null, "e": 1429, "s": 608, "text": "First of all, you must understand that Bayesian is just an approach to defining and estimating statistical models. Bayesian Regression can be very useful when we have insufficient data in the dataset or the data is poorly distributed. The output of a Bayesian Regression model is obtained from a probability distribution, as compared to regular regression techniques where the output is just obtained from a single value of each attribute. The output, β€˜y’ is generated from a normal distribution (where mean and variance are normalized). The aim of Bayesian Linear Regression is not to find the model parameters, but rather to find the β€˜posteriorβ€˜ distribution for the model parameters. Not just the output y, but the model parameters are also assumed to come from a distribution. The expression for Posterior is :where " }, { "code": null, "e": 1563, "s": 1429, "text": "Posterior: It is the probability of an event to occur; say, H, given that another event; say, E has already occurred. i.e., P(H | E)." }, { "code": null, "e": 1654, "s": 1563, "text": "Prior: It is the probability of an event H has occurred prior to another event. i.e., P(H)" }, { "code": null, "e": 1744, "s": 1654, "text": "Likelihood: It is a likelihood function in which some parameter variable is marginalized." }, { "code": null, "e": 2144, "s": 1744, "text": "This is actually equivalent to the Bayes’ Theorem which says, where A and B are events, P(A) is the probability of occurrence of A, and P(A|B) is the probability of A to occur given that event B has already occurred. P(B), the probability of event B occurring cannot be 0 since it has already occurred. If you want to learn more about regular Naive Bayes and Bayes Theorem, you can follow this link." }, { "code": null, "e": 2902, "s": 2144, "text": "Looking at the formula above, we can see that, in contrast to Ordinary Least Square (OLS), we have a posterior distribution for the model parameters which is proportional to the likelihood of the data multiplied by the prior probability of the parameters. As the number of data points increase, the value of likelihood will increase and will become much larger than the prior value. In the case of an infinite number of data points, the values for the parameters converge to the values obtained from OLS. So, we begin our regression process with an initial estimate (the prior value). As we start to cover more data points, our model becomes less wrong. So for Bayesian Ridge Regression, a large amount of training data is needed to make the model accurate." }, { "code": null, "e": 4188, "s": 2902, "text": "Now, let us have a quick brief overview of the mathematical side of things. In a linear model, if β€˜y’ is the predicted value, then where, β€˜w’ is the vector w. w consists of w0, w1, ... . β€˜x’ is the value of the weights. So, now for Bayesian Regression to obtain a fully probabilistic model, the output β€˜y’ is assumed to be the Gaussian distribution around Xw as shown below: where alpha is a hyper-parameter for the Gamma distribution prior. It is treated as a random variable estimated from the data. Here, the implementation for Bayesian Ridge Regression is given below. The mathematical expression on which Bayesian Ridge Regression works is : where alpha is the shape parameter for the Gamma distribution prior to the alpha parameter and lambda is the shape parameter for the Gamma distribution prior to the Lambda parameter.This is only a brief introduction to the mathematics that goes behind a Bayesian Ridge Regressor. The goal of this article is to give you a brief high-level overview of Bayesian regression; when to use it, advantages, disadvantages, and show you how to implement it. So, we have just given you a brief introduction to the mathematics behind Bayesian regression and Bayesian Ridge regression. We will not go much into the depth of how the mathematics works." }, { "code": null, "e": 4224, "s": 4188, "text": "Advantages of Bayesian Regression: " }, { "code": null, "e": 4278, "s": 4224, "text": "Very effective when the size of the dataset is small." }, { "code": null, "e": 4546, "s": 4278, "text": "Particularly well-suited for on-line based learning (data is received in real-time), as compared to batch based learning, where we have the entire dataset on our hands before we start training the model. This is because Bayesian Regression doesn’t need to store data." }, { "code": null, "e": 4716, "s": 4546, "text": "The Bayesian approach is a tried and tested approach and is very robust, mathematically. So, one can use this without having any extra prior knowledge about the dataset." }, { "code": null, "e": 4756, "s": 4716, "text": "Disadvantages of Bayesian Regression: " }, { "code": null, "e": 4806, "s": 4756, "text": "The inference of the model can be time-consuming." }, { "code": null, "e": 4969, "s": 4806, "text": "If there is a large amount of data available for our dataset, the Bayesian approach is not worth it and the regular frequentist approach does a more efficient job" }, { "code": null, "e": 5737, "s": 4969, "text": "Implementation of Bayesian Regression Using Python: In this example, we will perform Bayesian Ridge Regression. However, the Bayesian approach can be used with any Regression technique like Linear Regression, Lasso Regression, etc. We will the scikit-learn library to implement Bayesian Ridge Regression. We will use the Boston Housing dataset that has information about the median value of a house in an area in Boston. You can learn more about this dataset here. For evaluation, we will use the r2 score. The best possible value of the r2 score is 1.0. If the model makes a constant prediction regardless of the attributes, the value of r2 score is 0. r2 score may also be negative for even worse models. To learn more about r2 scores, you can follow the link here." }, { "code": null, "e": 5849, "s": 5737, "text": "But before we get on to the code, you must understand the important parameters of a Bayesian Ridge Regressor: " }, { "code": null, "e": 5900, "s": 5849, "text": "n_iter: Number of iterations. Default value = 100." }, { "code": null, "e": 5990, "s": 5900, "text": "tol: When to stop the algorithm given that the model has converged. Default value = 1e-3." }, { "code": null, "e": 6132, "s": 5990, "text": "alpha_1: Shape parameter of the regressor line (Gamma distribution) over the alpha parameter (used for regularization). Default value = 1e-6." }, { "code": null, "e": 6240, "s": 6132, "text": "alpha_2: Inverse scale parameter for the Gamma distribution over the alpha parameter. Default value = 1e-6." }, { "code": null, "e": 6341, "s": 6240, "text": "lambda_1: Shape parameter of the Gamma distribution over the lambda parameter. Default value = 1e-6." }, { "code": null, "e": 6450, "s": 6341, "text": "lambda_2: Inverse scale parameter of the Gamma distribution over the lambda parameter. Default value = 1e-6." }, { "code": null, "e": 6546, "s": 6450, "text": "NOTE: This code may not work on an online IDE. Run it on Google Colab or on your local machine." }, { "code": null, "e": 6554, "s": 6546, "text": "Code: " }, { "code": null, "e": 6562, "s": 6554, "text": "Python3" }, { "code": "# Importing modules that are requiredfrom sklearn.datasets import load_bostonfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import r2_scorefrom sklearn.linear_model import BayesianRidge # Loading datasetdataset = load_boston()X, y = dataset.data, dataset.target # Splitting dataset into training and testing setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15, random_state = 42) # Creating and training modelmodel = BayesianRidge()model.fit(X_train, y_train) # Model making a prediction on test dataprediction = model.predict(X_test) # Evaluation of r2 score of the model against the test setprint(f\"r2 Score Of Test Set : {r2_score(y_test, prediction)}\")", "e": 7282, "s": 6562, "text": null }, { "code": null, "e": 7291, "s": 7282, "text": "Output: " }, { "code": null, "e": 7333, "s": 7291, "text": "r2 Score Of Test Set : 0.7943355984883815" }, { "code": null, "e": 7596, "s": 7333, "text": "We get an r2 score of approximately 0.7934 on the test set using Bayesian Ridge Regressor with all default parameters. This is an acceptable score. However, you may alter the alpha and lambda parameters discussed above to obtain better results for your dataset. " }, { "code": null, "e": 7788, "s": 7596, "text": "Conclusion: So now that you know how Bayesian regressors work and when to use it, you should try using it next time you want to perform a regression task, especially if the dataset is small. " }, { "code": null, "e": 7802, "s": 7788, "text": "References: " }, { "code": null, "e": 7830, "s": 7802, "text": "scikit-learn Documentation." }, { "code": null, "e": 7845, "s": 7832, "text": "simmytarika5" }, { "code": null, "e": 7862, "s": 7845, "text": "Machine Learning" }, { "code": null, "e": 7869, "s": 7862, "text": "Python" }, { "code": null, "e": 7886, "s": 7869, "text": "Machine Learning" } ]
How to detect HTML 5 is supported or not in the browser ?
10 Nov, 2021 HTML 5 is the latest standard of HTML that includes many new changes and features. HTML 5 support can be detected by using three approaches:Method 1: Checking for Geolocation support: The Geolocation API was added in HTML5. It is used for identifying the user’s location. The presence of this API could be detected by checking if the geolocation property is present in the navigator object. This is done by using navigator.geolocation which returns the Geolocation object. If the object exists, it means that HTML5 is supported by the browser.Example: html <!DOCTYPE html><html> <head> <title> How to detect HTML 5 is supported or not in the browser ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to detect HTML5 support in the browser ? </b> <p> Geolocation features is added in HTML5. Checking the Geolocation supports. </p> <p> Click on the button to check for Geolocation support </p> <p> Gelocation is supported: <span class="output"></span> </p> <button onclick="checkGeolocation()"> Check for Geolocation </button> <script type="text/javascript"> function checkGeolocation() { if (navigator.geolocation) isSupported = true; else isSupported = false; document.querySelector('.output').textContent = isSupported; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 2: Checking for the canvas element: The canvas element is used to render shapes or bitmap elements. This is a new feature added in HTML5. The canvas element has a getContext() method which is used to return the drawing context of the canvas element. It returns a null value if the context identifier is not supported. This property can be used to check whether the canvas element is supported. A new canvas element is created using the document.createElement() method. The getContext method is checked by accessing it on the created input object. The result of this expression is checked with an if-statement. If the result is true, it means that HTML5 is supported by the browser.Example: html <!DOCTYPE html><html> <head> <title> How to detect HTML 5 is supported or not in the browser ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to detect that HTML5 is not supported by JavaScript? </b> <p> The Canvas features added in HTML5. Checking for canvas support in HTML5. </p> <p> Click on the button to check for Canvas support </p> <p> Canvas is supported: <span class="output"></span> </p> <button onclick="checkCanvas()"> Check for canvas </button> <script type="text/javascript"> function checkCanvas() { if (document.createElement('canvas').getContext) isSupported = true; else isSupported = false; document.querySelector('.output').textContent = isSupported; } </script></body> </html> Output: Before clicking the button: After clicking the button: Method 3: Checking for text input types: HTML5 introduced new input types that can be used to enter different forms of data with validation. The input element before HTML5 didn’t support these new types and using them would automatically revert to the default β€˜text’ type. This can be used to check if the browser supports HTML5. A new input element is created using the document.createElement() method. The setAttribute method is then used on the created element to set the type of input to any of the newer input types. The type of this element is checked using an if-statement to see whether it matches the default β€˜text’ value. If the value does not revert back to the default setting, it means that HTML5 is supported by the browser.Example: html <!DOCTYPE html><html> <head> <title> How to detect HTML 5 is supported or not in the browser ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to detect HTML5 support in the browser ? </b> <p> New input types are one of the features added in HTML5. <br> Checking for the new input types means that HTML5 is supported. </p> <p> Click on the button to check if the new input types are supported </p> <p> New input types supported: <span class="output"></span> </p> <button onclick="checkInputType()"> Check for input types </button> <script type="text/javascript"> function checkInputType() { let tempElement = document.createElement("input"); tempElement.setAttribute("type", "color"); // Check if the type attribute falls back // to default text type if (tempElement.type !== "text") isSupported = true; else isSupported = false; document.querySelector('.output').textContent = isSupported; } </script></body> </html> Output: Before clicking the button: After clicking the button: rajeev0719singh JavaScript-Misc HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? REST API (Introduction) CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Nov, 2021" }, { "code": null, "e": 582, "s": 28, "text": "HTML 5 is the latest standard of HTML that includes many new changes and features. HTML 5 support can be detected by using three approaches:Method 1: Checking for Geolocation support: The Geolocation API was added in HTML5. It is used for identifying the user’s location. The presence of this API could be detected by checking if the geolocation property is present in the navigator object. This is done by using navigator.geolocation which returns the Geolocation object. If the object exists, it means that HTML5 is supported by the browser.Example: " }, { "code": null, "e": 587, "s": 582, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to detect HTML 5 is supported or not in the browser ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to detect HTML5 support in the browser ? </b> <p> Geolocation features is added in HTML5. Checking the Geolocation supports. </p> <p> Click on the button to check for Geolocation support </p> <p> Gelocation is supported: <span class=\"output\"></span> </p> <button onclick=\"checkGeolocation()\"> Check for Geolocation </button> <script type=\"text/javascript\"> function checkGeolocation() { if (navigator.geolocation) isSupported = true; else isSupported = false; document.querySelector('.output').textContent = isSupported; } </script></body> </html>", "e": 1581, "s": 587, "text": null }, { "code": null, "e": 1591, "s": 1581, "text": "Output: " }, { "code": null, "e": 1621, "s": 1591, "text": "Before clicking the button: " }, { "code": null, "e": 1650, "s": 1621, "text": "After clicking the button: " }, { "code": null, "e": 2349, "s": 1650, "text": "Method 2: Checking for the canvas element: The canvas element is used to render shapes or bitmap elements. This is a new feature added in HTML5. The canvas element has a getContext() method which is used to return the drawing context of the canvas element. It returns a null value if the context identifier is not supported. This property can be used to check whether the canvas element is supported. A new canvas element is created using the document.createElement() method. The getContext method is checked by accessing it on the created input object. The result of this expression is checked with an if-statement. If the result is true, it means that HTML5 is supported by the browser.Example: " }, { "code": null, "e": 2354, "s": 2349, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to detect HTML 5 is supported or not in the browser ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to detect that HTML5 is not supported by JavaScript? </b> <p> The Canvas features added in HTML5. Checking for canvas support in HTML5. </p> <p> Click on the button to check for Canvas support </p> <p> Canvas is supported: <span class=\"output\"></span> </p> <button onclick=\"checkCanvas()\"> Check for canvas </button> <script type=\"text/javascript\"> function checkCanvas() { if (document.createElement('canvas').getContext) isSupported = true; else isSupported = false; document.querySelector('.output').textContent = isSupported; } </script></body> </html>", "e": 3377, "s": 2354, "text": null }, { "code": null, "e": 3387, "s": 3377, "text": "Output: " }, { "code": null, "e": 3417, "s": 3387, "text": "Before clicking the button: " }, { "code": null, "e": 3446, "s": 3417, "text": "After clicking the button: " }, { "code": null, "e": 4195, "s": 3446, "text": "Method 3: Checking for text input types: HTML5 introduced new input types that can be used to enter different forms of data with validation. The input element before HTML5 didn’t support these new types and using them would automatically revert to the default β€˜text’ type. This can be used to check if the browser supports HTML5. A new input element is created using the document.createElement() method. The setAttribute method is then used on the created element to set the type of input to any of the newer input types. The type of this element is checked using an if-statement to see whether it matches the default β€˜text’ value. If the value does not revert back to the default setting, it means that HTML5 is supported by the browser.Example: " }, { "code": null, "e": 4200, "s": 4195, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> How to detect HTML 5 is supported or not in the browser ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to detect HTML5 support in the browser ? </b> <p> New input types are one of the features added in HTML5. <br> Checking for the new input types means that HTML5 is supported. </p> <p> Click on the button to check if the new input types are supported </p> <p> New input types supported: <span class=\"output\"></span> </p> <button onclick=\"checkInputType()\"> Check for input types </button> <script type=\"text/javascript\"> function checkInputType() { let tempElement = document.createElement(\"input\"); tempElement.setAttribute(\"type\", \"color\"); // Check if the type attribute falls back // to default text type if (tempElement.type !== \"text\") isSupported = true; else isSupported = false; document.querySelector('.output').textContent = isSupported; } </script></body> </html>", "e": 5479, "s": 4200, "text": null }, { "code": null, "e": 5489, "s": 5479, "text": "Output: " }, { "code": null, "e": 5519, "s": 5489, "text": "Before clicking the button: " }, { "code": null, "e": 5548, "s": 5519, "text": "After clicking the button: " }, { "code": null, "e": 5566, "s": 5550, "text": "rajeev0719singh" }, { "code": null, "e": 5582, "s": 5566, "text": "JavaScript-Misc" }, { "code": null, "e": 5587, "s": 5582, "text": "HTML" }, { "code": null, "e": 5598, "s": 5587, "text": "JavaScript" }, { "code": null, "e": 5615, "s": 5598, "text": "Web Technologies" }, { "code": null, "e": 5642, "s": 5615, "text": "Web technologies Questions" }, { "code": null, "e": 5647, "s": 5642, "text": "HTML" }, { "code": null, "e": 5745, "s": 5647, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5793, "s": 5745, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 5817, "s": 5793, "text": "REST API (Introduction)" }, { "code": null, "e": 5867, "s": 5817, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 5904, "s": 5867, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 5943, "s": 5904, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 6004, "s": 5943, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6076, "s": 6004, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6116, "s": 6076, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6157, "s": 6116, "text": "Difference Between PUT and PATCH Request" } ]
React-Bootstrap Form Component
27 Apr, 2022 React-Bootstrap is a front-end framework that was designed keeping react in mind. Form Component provides a way to make a form and take user input and then forward it to the server for further data processing. We can use the following approach in ReactJS to use the react-bootstrap Form Component. Form Props: ref: It is used to forward the form-ref to the underlying element. as: It can be used as a custom element type for this component. inline: It is used to display the series of labels, buttons, etc on a single horizontal row. validated: It is used to mark a form as having been validated with true/false value. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Form.Label Props: ref: It is used to forward the form-ref to the underlying element. as: It can be used as a custom element type for this component. column: It is used to render the FormLabel as a <Col> component. htmlFor: It is used to Uses controlId from <FormGroup> if not explicitly specified. srOnly: It is used to hide the label visually. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Form.Group Props: ref: It is used to forward the form-ref to the underlying element. as: It can be used as a custom element type for this component. controlId: It is used to set the id on <FormControl> and htmlFor on <FormGroup.Label> component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Form.Row Props: as: It can be used as a custom element type for this component. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Form.Text Props: ref: It is used to forward the formText ref to the underlying element. as: It can be used as a custom element type for this component. muted: It is used to add the text-muted class to it. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. Form.Check Props: as: It can be used as a custom element type for this component. id: It is the normal HTML id attribute used for the identification. isInvalid: It is used to manually set the styling of the input as invalid. isStatic: It is used to add the position-static style to it. isValid: It is used to manually set the styling of the input as valid. type: It is used for the checkable types. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. bsCustomPrefix: For custom controls, it is used as a separate bsPrefix. Form.Control Props: ref: It is used to forward the form-ref to the underlying element. as: It can be used as a custom element type for this component. custom: It is used to make use of Bootstrap’s custom form elements. disabled: It is used to make the control disabled. htmlSize: For the underlying element, it is used for its size attribute. id: It is used to make use of controlId from <FormGroup> isInvalid: For the control, it is used to add invalid validation styles. isValid: For the control, it is used to add valid validation styles. onChange: It is a callback function that is triggered on a change of value. plaintext: It is used to render the input as plain text. readOnly: It is used to make the control in the read-only state. size: It is used to denote the input size. type: It is used to denote the HTML input type for input. value: For underlying input, it is used for its value attribute. bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS. bsCustomPrefix: For custom controls, it is a separate bsPrefix. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. import React from 'react'; import 'bootstrap/dist/css/bootstrap.css'; import Form from 'react-bootstrap/Form'; import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap Form Component</h4> <Form> <Form.Group> <Form.Label>Enter your full name:</Form.Label> <Form.Control type="text" placeholder="Enter your full name" /> </Form.Group> <Form.Group> <Form.Label>Enter your email address:</Form.Label> <Form.Control type="email" placeholder="Enter your your email address" /> </Form.Group> <Form.Group> <Form.Label>Enter your age:</Form.Label> <Form.Control type="number" placeholder="Enter your age" /> </Form.Group> <Button variant="primary" type="submit"> Click here to submit form </Button> </Form> </div> ); } Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://react-bootstrap.github.io/components/forms/ sagartomar9927 React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Apr, 2022" }, { "code": null, "e": 326, "s": 28, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. Form Component provides a way to make a form and take user input and then forward it to the server for further data processing. We can use the following approach in ReactJS to use the react-bootstrap Form Component." }, { "code": null, "e": 338, "s": 326, "text": "Form Props:" }, { "code": null, "e": 405, "s": 338, "text": "ref: It is used to forward the form-ref to the underlying element." }, { "code": null, "e": 469, "s": 405, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 562, "s": 469, "text": "inline: It is used to display the series of labels, buttons, etc on a single horizontal row." }, { "code": null, "e": 647, "s": 562, "text": "validated: It is used to mark a form as having been validated with true/false value." }, { "code": null, "e": 731, "s": 647, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 749, "s": 731, "text": "Form.Label Props:" }, { "code": null, "e": 816, "s": 749, "text": "ref: It is used to forward the form-ref to the underlying element." }, { "code": null, "e": 880, "s": 816, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 945, "s": 880, "text": "column: It is used to render the FormLabel as a <Col> component." }, { "code": null, "e": 1029, "s": 945, "text": "htmlFor: It is used to Uses controlId from <FormGroup> if not explicitly specified." }, { "code": null, "e": 1076, "s": 1029, "text": "srOnly: It is used to hide the label visually." }, { "code": null, "e": 1160, "s": 1076, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1178, "s": 1160, "text": "Form.Group Props:" }, { "code": null, "e": 1245, "s": 1178, "text": "ref: It is used to forward the form-ref to the underlying element." }, { "code": null, "e": 1309, "s": 1245, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1406, "s": 1309, "text": "controlId: It is used to set the id on <FormControl> and htmlFor on <FormGroup.Label> component." }, { "code": null, "e": 1490, "s": 1406, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1506, "s": 1490, "text": "Form.Row Props:" }, { "code": null, "e": 1570, "s": 1506, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1654, "s": 1570, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1671, "s": 1654, "text": "Form.Text Props:" }, { "code": null, "e": 1742, "s": 1671, "text": "ref: It is used to forward the formText ref to the underlying element." }, { "code": null, "e": 1806, "s": 1742, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 1859, "s": 1806, "text": "muted: It is used to add the text-muted class to it." }, { "code": null, "e": 1943, "s": 1859, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 1961, "s": 1943, "text": "Form.Check Props:" }, { "code": null, "e": 2025, "s": 1961, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 2093, "s": 2025, "text": "id: It is the normal HTML id attribute used for the identification." }, { "code": null, "e": 2168, "s": 2093, "text": "isInvalid: It is used to manually set the styling of the input as invalid." }, { "code": null, "e": 2229, "s": 2168, "text": "isStatic: It is used to add the position-static style to it." }, { "code": null, "e": 2300, "s": 2229, "text": "isValid: It is used to manually set the styling of the input as valid." }, { "code": null, "e": 2342, "s": 2300, "text": "type: It is used for the checkable types." }, { "code": null, "e": 2426, "s": 2342, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 2498, "s": 2426, "text": "bsCustomPrefix: For custom controls, it is used as a separate bsPrefix." }, { "code": null, "e": 2518, "s": 2498, "text": "Form.Control Props:" }, { "code": null, "e": 2585, "s": 2518, "text": "ref: It is used to forward the form-ref to the underlying element." }, { "code": null, "e": 2649, "s": 2585, "text": "as: It can be used as a custom element type for this component." }, { "code": null, "e": 2717, "s": 2649, "text": "custom: It is used to make use of Bootstrap’s custom form elements." }, { "code": null, "e": 2768, "s": 2717, "text": "disabled: It is used to make the control disabled." }, { "code": null, "e": 2841, "s": 2768, "text": "htmlSize: For the underlying element, it is used for its size attribute." }, { "code": null, "e": 2898, "s": 2841, "text": "id: It is used to make use of controlId from <FormGroup>" }, { "code": null, "e": 2971, "s": 2898, "text": "isInvalid: For the control, it is used to add invalid validation styles." }, { "code": null, "e": 3040, "s": 2971, "text": "isValid: For the control, it is used to add valid validation styles." }, { "code": null, "e": 3116, "s": 3040, "text": "onChange: It is a callback function that is triggered on a change of value." }, { "code": null, "e": 3173, "s": 3116, "text": "plaintext: It is used to render the input as plain text." }, { "code": null, "e": 3238, "s": 3173, "text": "readOnly: It is used to make the control in the read-only state." }, { "code": null, "e": 3281, "s": 3238, "text": "size: It is used to denote the input size." }, { "code": null, "e": 3339, "s": 3281, "text": "type: It is used to denote the HTML input type for input." }, { "code": null, "e": 3404, "s": 3339, "text": "value: For underlying input, it is used for its value attribute." }, { "code": null, "e": 3488, "s": 3404, "text": "bsPrefix: It is an escape hatch for working with strongly customized bootstrap CSS." }, { "code": null, "e": 3552, "s": 3488, "text": "bsCustomPrefix: For custom controls, it is a separate bsPrefix." }, { "code": null, "e": 3602, "s": 3552, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 3666, "s": 3602, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 3698, "s": 3666, "text": "npx create-react-app foldername" }, { "code": null, "e": 3798, "s": 3698, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 3812, "s": 3798, "text": "cd foldername" }, { "code": null, "e": 3917, "s": 3812, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 3968, "s": 3917, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 4020, "s": 3968, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 4038, "s": 4020, "text": "Project Structure" }, { "code": null, "e": 4168, "s": 4038, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 5239, "s": 4168, "text": "import React from 'react';\nimport 'bootstrap/dist/css/bootstrap.css';\nimport Form from 'react-bootstrap/Form';\nimport Button from 'react-bootstrap/Button';\n\nexport default function App() {\n return (\n <div style={{ display: 'block', \n width: 700, \n padding: 30 }}>\n <h4>React-Bootstrap Form Component</h4>\n <Form>\n <Form.Group>\n <Form.Label>Enter your full name:</Form.Label>\n <Form.Control type=\"text\" \n placeholder=\"Enter your full name\" />\n </Form.Group>\n <Form.Group>\n <Form.Label>Enter your email address:</Form.Label>\n <Form.Control type=\"email\" \n placeholder=\"Enter your your email address\" />\n </Form.Group>\n <Form.Group>\n <Form.Label>Enter your age:</Form.Label>\n <Form.Control type=\"number\" placeholder=\"Enter your age\" />\n </Form.Group>\n <Button variant=\"primary\" type=\"submit\">\n Click here to submit form\n </Button>\n </Form>\n </div>\n );\n}" }, { "code": null, "e": 5352, "s": 5239, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 5362, "s": 5352, "text": "npm start" }, { "code": null, "e": 5461, "s": 5362, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 5524, "s": 5461, "text": "Reference: https://react-bootstrap.github.io/components/forms/" }, { "code": null, "e": 5539, "s": 5524, "text": "sagartomar9927" }, { "code": null, "e": 5555, "s": 5539, "text": "React-Bootstrap" }, { "code": null, "e": 5563, "s": 5555, "text": "ReactJS" }, { "code": null, "e": 5580, "s": 5563, "text": "Web Technologies" }, { "code": null, "e": 5678, "s": 5580, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5716, "s": 5678, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 5735, "s": 5716, "text": "ReactJS setState()" }, { "code": null, "e": 5803, "s": 5735, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 5838, "s": 5803, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 5859, "s": 5838, "text": "ReactJS defaultProps" }, { "code": null, "e": 5892, "s": 5859, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5954, "s": 5892, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6015, "s": 5954, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6065, "s": 6015, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python PIL | ImageEnhance.Brightness() and ImageEnhance.Sharpness() method
29 Jun, 2019 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageEnhance module contains a number of classes that can be used for image enhancement. This class can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image. Syntax: obj = ImageEnhance.Brightness(image) obj.enhance(factor) First, it is required to create an object of corresponding class in order to enhance image. # This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r"C:\Users\Admin\Pictures\images.png") # Creating object of Brightness classim3 = ImageEnhance.Brightness(im) # showing resultant imageim3.enhance(2.0).show() Output:For first image factor is 2.0 and for second 5.0 This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image. Syntax: obj = ImageEnhance.Sharpness(image) obj.enhance(factor) First, it is required to create an object of corresponding class in order to enhance image. # This will import Image and ImageChops modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r"C:\Users\Admin\Pictures\images.png") # Creating object of Sharpness classim3 = ImageEnhance.Sharpness(im) # showing resultant imageim3.enhance(-2.0).show() Output:For first image factor is -2.0 and for second image it is 5.0 Image-Processing python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2019" }, { "code": null, "e": 226, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageEnhance module contains a number of classes that can be used for image enhancement." }, { "code": null, "e": 380, "s": 226, "text": "This class can be used to control the brightness of an image. An enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the original image." }, { "code": null, "e": 388, "s": 380, "text": "Syntax:" }, { "code": null, "e": 446, "s": 388, "text": "obj = ImageEnhance.Brightness(image)\nobj.enhance(factor)\n" }, { "code": null, "e": 538, "s": 446, "text": "First, it is required to create an object of corresponding class in order to enhance image." }, { "code": "# This will import Image and ImageEnhance modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r\"C:\\Users\\Admin\\Pictures\\images.png\") # Creating object of Brightness classim3 = ImageEnhance.Brightness(im) # showing resultant imageim3.enhance(2.0).show()", "e": 816, "s": 538, "text": null }, { "code": null, "e": 872, "s": 816, "text": "Output:For first image factor is 2.0 and for second 5.0" }, { "code": null, "e": 1071, "s": 872, "text": "This class can be used to adjust the sharpness of an image. An enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the original image, and a factor of 2.0 gives a sharpened image." }, { "code": null, "e": 1079, "s": 1071, "text": "Syntax:" }, { "code": null, "e": 1136, "s": 1079, "text": "obj = ImageEnhance.Sharpness(image)\nobj.enhance(factor)\n" }, { "code": null, "e": 1228, "s": 1136, "text": "First, it is required to create an object of corresponding class in order to enhance image." }, { "code": "# This will import Image and ImageChops modulesfrom PIL import Image, ImageEnhance # Opening Imageim = Image.open(r\"C:\\Users\\Admin\\Pictures\\images.png\") # Creating object of Sharpness classim3 = ImageEnhance.Sharpness(im) # showing resultant imageim3.enhance(-2.0).show()", "e": 1503, "s": 1228, "text": null }, { "code": null, "e": 1572, "s": 1503, "text": "Output:For first image factor is -2.0 and for second image it is 5.0" }, { "code": null, "e": 1589, "s": 1572, "text": "Image-Processing" }, { "code": null, "e": 1604, "s": 1589, "text": "python-utility" }, { "code": null, "e": 1611, "s": 1604, "text": "Python" }, { "code": null, "e": 1709, "s": 1611, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1727, "s": 1709, "text": "Python Dictionary" }, { "code": null, "e": 1769, "s": 1727, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1791, "s": 1769, "text": "Enumerate() in Python" }, { "code": null, "e": 1826, "s": 1791, "text": "Read a file line by line in Python" }, { "code": null, "e": 1852, "s": 1826, "text": "Python String | replace()" }, { "code": null, "e": 1884, "s": 1852, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1913, "s": 1884, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1940, "s": 1913, "text": "Python Classes and Objects" }, { "code": null, "e": 1961, "s": 1940, "text": "Python OOPs Concepts" } ]
Personal Voice Assistant in Python
25 May, 2022 As we know Python is a suitable language for script writers and developers. Let’s write a script for Personal Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. The implemented assistant can open up the application (if it’s installed in the system), search Google, Wikipedia and YouTube about the query, calculate any mathematical question, etc by just giving the voice command. We can process the data as per the need or can add the functionality, depends upon how we code things. We are using Google speech recognition API and google text to speech for voice input and output respectively. Also, for calculating mathematical expression WolframAlpha API can be used. Playsound Package is used to play the saved mp3 sound from the system. Python external Package Requirements: -> gTTS – Google Text To Speech, for converting the given text to speech -> speech_recognition – for recognizing the voice command and converting to text -> selenium – for web based work from browser -> wolframalpha – for calculation given by user -> playsound – for playing the saved audio file. -> playaudio – for voice engine in python Well, let’s get started with code. We will divide each function as a single code for easy understanding. Here’s the main function, with get_audio() and assistant_speaks function. get_audio() function is created to get the audio from user using microphone, the phrase limit is set to 5 seconds (you can change it). Assistant speaks function is created to provide the output according to the processed data. Python3 # importing speech recognition package from google apiimport speech_recognition as srimport playsound # to play saved mp3 filefrom gtts import gTTS # google text to speechimport os # to save/open filesimport wolframalpha # to calculate strings into formulafrom selenium import webdriver # to control browser operations num = 1def assistant_speaks(output): global num # num to rename every audio file # with different name to remove ambiguity num += 1 print("PerSon : ", output) toSpeak = gTTS(text = output, lang ='en', slow = False) # saving the audio file given by google text to speech file = str(num)+".mp3 toSpeak.save(file) # playsound package is used to play the same file. playsound.playsound(file, True) os.remove(file) def get_audio(): rObject = sr.Recognizer() audio = '' with sr.Microphone() as source: print("Speak...") # recording the audio using speech recognition audio = rObject.listen(source, phrase_time_limit = 5) print("Stop.") # limit 5 secs try: text = rObject.recognize_google(audio, language ='en-US') print("You : ", text) return text except: assistant_speaks("Could not understand your audio, PLease try again !") return 0 # Driver Codeif __name__ == "__main__": assistant_speaks("What's your name, Human?") name ='Human' name = get_audio() assistant_speaks("Hello, " + name + '.') while(1): assistant_speaks("What can i do for you?") text = get_audio().lower() if text == 0: continue if "exit" in str(text) or "bye" in str(text) or "sleep" in str(text): assistant_speaks("Ok bye, "+ name+'.') break # calling process text to process the query process_text(text) So, we have got an idea here how we are giving voice to the machine and take input from user. The next step and the main step is how you want to process your input. This is just basic code, there is a lot of other algorithms(NLP) can be used to process the text in a proper manner. We have made it static. Also, Wolframalpha api has been used to calculate the calculations part. Python3 def process_text(input): try: if 'search' in input or 'play' in input: # a basic web crawler using selenium search_web(input) return elif "who are you" in input or "define yourself" in input: speak = '''Hello, I am Person. Your personal Assistant. I am here to make your life easier. You can command me to perform various tasks such as calculating sums or opening applications etcetra''' assistant_speaks(speak) return elif "who made you" in input or "created you" in input: speak = "I have been created by Sheetansh Kumar." assistant_speaks(speak) return elif "geeksforgeeks" in input:# just speak = """Geeks for Geeks is the Best Online Coding Platform for learning.""" assistant_speaks(speak) return elif "calculate" in input.lower(): # write your wolframalpha app_id here app_id = "WOLFRAMALPHA_APP_ID" client = wolframalpha.Client(app_id) indx = input.lower().split().index('calculate') query = input.split()[indx + 1:] res = client.query(' '.join(query)) answer = next(res.results).text assistant_speaks("The answer is " + answer) return elif 'open' in input: # another function to open # different application available open_application(input.lower()) return else: assistant_speaks("I can search the web for you, Do you want to continue?") ans = get_audio() if 'yes' in str(ans) or 'yeah' in str(ans): search_web(input) else: return except : assistant_speaks("I don't understand, I can search the web for you, Do you want to continue?") ans = get_audio() if 'yes' in str(ans) or 'yeah' in str(ans): search_web(input) Now we have processed the input, it’s time for action! There are two functions included that is search_web and open_application. search_web is just a web crawler which uses selenium package to process. It can search google, wikipedia and can open YouTube. You just have to say include the name and it will open it in the Firefox browser. For other browsers, you need to install a proper browser package in selenium. Here we are using webdriver for Firefox. open_application is just a function uses os package to open the application present in the system. Python3 def search_web(input): driver = webdriver.Firefox() driver.implicitly_wait(1) driver.maximize_window() if 'youtube' in input.lower(): assistant_speaks("Opening in youtube") indx = input.lower().split().index('youtube') query = input.split()[indx + 1:] driver.get("http://www.youtube.com/results?search_query =" + '+'.join(query)) return elif 'wikipedia' in input.lower(): assistant_speaks("Opening Wikipedia") indx = input.lower().split().index('wikipedia') query = input.split()[indx + 1:] driver.get("https://en.wikipedia.org/wiki/" + '_'.join(query)) return else: if 'google' in input: indx = input.lower().split().index('google') query = input.split()[indx + 1:] driver.get("https://www.google.com/search?q =" + '+'.join(query)) elif 'search' in input: indx = input.lower().split().index('google') query = input.split()[indx + 1:] driver.get("https://www.google.com/search?q =" + '+'.join(query)) else: driver.get("https://www.google.com/search?q =" + '+'.join(input.split())) return # function used to open application# present inside the system.def open_application(input): if "chrome" in input: assistant_speaks("Google Chrome") os.startfile('C:\Program Files (x86)\Google\Chrome\Application\chrome.exe') return elif "firefox" in input or "mozilla" in input: assistant_speaks("Opening Mozilla Firefox") os.startfile('C:\Program Files\Mozilla Firefox\\firefox.exe') return elif "word" in input: assistant_speaks("Opening Microsoft Word") os.startfile('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Word 2013.lnk') return elif "excel" in input: assistant_speaks("Opening Microsoft Excel") os.startfile('C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Office 2013\\Excel 2013.lnk') return else: assistant_speaks("Application not available") return Here are some of the examples and output, which can help you understand how the above processing works. 1. Say "Search google Geeks for Geeks" 2. Say "Play Youtube your favourite song" 3. Say "Wikipedia Dhoni" 4. Say "Open Microsoft Word" 5. Say "Calculate anything you want" In all the above cases, it will give do what is told. If the assistant can’t understand what is told it will ask you to google search it. For the thing which assistant can’t do is handled by this assistant. Below are some screenshots for the talk between human and the assistant. Well, that’s it. The above functionality can be coded in many ways, this is a basic implementation. Make sure you have the latest version of all the above packages for smooth work. To run the above code combine all the functions in same file. mitalibhola94 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2022" }, { "code": null, "e": 844, "s": 54, "text": "As we know Python is a suitable language for script writers and developers. Let’s write a script for Personal Voice Assistant using Python. The query for the assistant can be manipulated as per the user’s need. The implemented assistant can open up the application (if it’s installed in the system), search Google, Wikipedia and YouTube about the query, calculate any mathematical question, etc by just giving the voice command. We can process the data as per the need or can add the functionality, depends upon how we code things. We are using Google speech recognition API and google text to speech for voice input and output respectively. Also, for calculating mathematical expression WolframAlpha API can be used. Playsound Package is used to play the saved mp3 sound from the system. " }, { "code": null, "e": 882, "s": 844, "text": "Python external Package Requirements:" }, { "code": null, "e": 1221, "s": 882, "text": "-> gTTS – Google Text To Speech, for converting the given text to speech -> speech_recognition – for recognizing the voice command and converting to text -> selenium – for web based work from browser -> wolframalpha – for calculation given by user -> playsound – for playing the saved audio file. -> playaudio – for voice engine in python" }, { "code": null, "e": 1628, "s": 1221, "text": "Well, let’s get started with code. We will divide each function as a single code for easy understanding. Here’s the main function, with get_audio() and assistant_speaks function. get_audio() function is created to get the audio from user using microphone, the phrase limit is set to 5 seconds (you can change it). Assistant speaks function is created to provide the output according to the processed data. " }, { "code": null, "e": 1636, "s": 1628, "text": "Python3" }, { "code": "# importing speech recognition package from google apiimport speech_recognition as srimport playsound # to play saved mp3 filefrom gtts import gTTS # google text to speechimport os # to save/open filesimport wolframalpha # to calculate strings into formulafrom selenium import webdriver # to control browser operations num = 1def assistant_speaks(output): global num # num to rename every audio file # with different name to remove ambiguity num += 1 print(\"PerSon : \", output) toSpeak = gTTS(text = output, lang ='en', slow = False) # saving the audio file given by google text to speech file = str(num)+\".mp3 toSpeak.save(file) # playsound package is used to play the same file. playsound.playsound(file, True) os.remove(file) def get_audio(): rObject = sr.Recognizer() audio = '' with sr.Microphone() as source: print(\"Speak...\") # recording the audio using speech recognition audio = rObject.listen(source, phrase_time_limit = 5) print(\"Stop.\") # limit 5 secs try: text = rObject.recognize_google(audio, language ='en-US') print(\"You : \", text) return text except: assistant_speaks(\"Could not understand your audio, PLease try again !\") return 0 # Driver Codeif __name__ == \"__main__\": assistant_speaks(\"What's your name, Human?\") name ='Human' name = get_audio() assistant_speaks(\"Hello, \" + name + '.') while(1): assistant_speaks(\"What can i do for you?\") text = get_audio().lower() if text == 0: continue if \"exit\" in str(text) or \"bye\" in str(text) or \"sleep\" in str(text): assistant_speaks(\"Ok bye, \"+ name+'.') break # calling process text to process the query process_text(text)", "e": 3460, "s": 1636, "text": null }, { "code": null, "e": 3840, "s": 3460, "text": "So, we have got an idea here how we are giving voice to the machine and take input from user. The next step and the main step is how you want to process your input. This is just basic code, there is a lot of other algorithms(NLP) can be used to process the text in a proper manner. We have made it static. Also, Wolframalpha api has been used to calculate the calculations part. " }, { "code": null, "e": 3848, "s": 3840, "text": "Python3" }, { "code": "def process_text(input): try: if 'search' in input or 'play' in input: # a basic web crawler using selenium search_web(input) return elif \"who are you\" in input or \"define yourself\" in input: speak = '''Hello, I am Person. Your personal Assistant. I am here to make your life easier. You can command me to perform various tasks such as calculating sums or opening applications etcetra''' assistant_speaks(speak) return elif \"who made you\" in input or \"created you\" in input: speak = \"I have been created by Sheetansh Kumar.\" assistant_speaks(speak) return elif \"geeksforgeeks\" in input:# just speak = \"\"\"Geeks for Geeks is the Best Online Coding Platform for learning.\"\"\" assistant_speaks(speak) return elif \"calculate\" in input.lower(): # write your wolframalpha app_id here app_id = \"WOLFRAMALPHA_APP_ID\" client = wolframalpha.Client(app_id) indx = input.lower().split().index('calculate') query = input.split()[indx + 1:] res = client.query(' '.join(query)) answer = next(res.results).text assistant_speaks(\"The answer is \" + answer) return elif 'open' in input: # another function to open # different application available open_application(input.lower()) return else: assistant_speaks(\"I can search the web for you, Do you want to continue?\") ans = get_audio() if 'yes' in str(ans) or 'yeah' in str(ans): search_web(input) else: return except : assistant_speaks(\"I don't understand, I can search the web for you, Do you want to continue?\") ans = get_audio() if 'yes' in str(ans) or 'yeah' in str(ans): search_web(input)", "e": 5865, "s": 3848, "text": null }, { "code": null, "e": 6422, "s": 5865, "text": "Now we have processed the input, it’s time for action! There are two functions included that is search_web and open_application. search_web is just a web crawler which uses selenium package to process. It can search google, wikipedia and can open YouTube. You just have to say include the name and it will open it in the Firefox browser. For other browsers, you need to install a proper browser package in selenium. Here we are using webdriver for Firefox. open_application is just a function uses os package to open the application present in the system. " }, { "code": null, "e": 6430, "s": 6422, "text": "Python3" }, { "code": "def search_web(input): driver = webdriver.Firefox() driver.implicitly_wait(1) driver.maximize_window() if 'youtube' in input.lower(): assistant_speaks(\"Opening in youtube\") indx = input.lower().split().index('youtube') query = input.split()[indx + 1:] driver.get(\"http://www.youtube.com/results?search_query =\" + '+'.join(query)) return elif 'wikipedia' in input.lower(): assistant_speaks(\"Opening Wikipedia\") indx = input.lower().split().index('wikipedia') query = input.split()[indx + 1:] driver.get(\"https://en.wikipedia.org/wiki/\" + '_'.join(query)) return else: if 'google' in input: indx = input.lower().split().index('google') query = input.split()[indx + 1:] driver.get(\"https://www.google.com/search?q =\" + '+'.join(query)) elif 'search' in input: indx = input.lower().split().index('google') query = input.split()[indx + 1:] driver.get(\"https://www.google.com/search?q =\" + '+'.join(query)) else: driver.get(\"https://www.google.com/search?q =\" + '+'.join(input.split())) return # function used to open application# present inside the system.def open_application(input): if \"chrome\" in input: assistant_speaks(\"Google Chrome\") os.startfile('C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe') return elif \"firefox\" in input or \"mozilla\" in input: assistant_speaks(\"Opening Mozilla Firefox\") os.startfile('C:\\Program Files\\Mozilla Firefox\\\\firefox.exe') return elif \"word\" in input: assistant_speaks(\"Opening Microsoft Word\") os.startfile('C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Office 2013\\\\Word 2013.lnk') return elif \"excel\" in input: assistant_speaks(\"Opening Microsoft Excel\") os.startfile('C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Office 2013\\\\Excel 2013.lnk') return else: assistant_speaks(\"Application not available\") return", "e": 8553, "s": 6430, "text": null }, { "code": null, "e": 8657, "s": 8553, "text": "Here are some of the examples and output, which can help you understand how the above processing works." }, { "code": null, "e": 8829, "s": 8657, "text": "1. Say \"Search google Geeks for Geeks\"\n2. Say \"Play Youtube your favourite song\"\n3. Say \"Wikipedia Dhoni\"\n4. Say \"Open Microsoft Word\"\n5. Say \"Calculate anything you want\"" }, { "code": null, "e": 9355, "s": 8829, "text": "In all the above cases, it will give do what is told. If the assistant can’t understand what is told it will ask you to google search it. For the thing which assistant can’t do is handled by this assistant. Below are some screenshots for the talk between human and the assistant. Well, that’s it. The above functionality can be coded in many ways, this is a basic implementation. Make sure you have the latest version of all the above packages for smooth work. To run the above code combine all the functions in same file." }, { "code": null, "e": 9369, "s": 9355, "text": "mitalibhola94" }, { "code": null, "e": 9384, "s": 9369, "text": "python-utility" }, { "code": null, "e": 9391, "s": 9384, "text": "Python" } ]
std::sort() in C++ STL
06 Jul, 2022 We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access) It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The third parameter is optional and can be used in cases such as if we want to sort the elements lexicographically. By default, the sort() function sorts the elements in ascending order. Below is a simple program to show the working of sort(). CPP // C++ program to demonstrate default behaviour of// sort() in STL.#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); /*Here we take two parameters, the beginning of the array and the length n upto which we want the array to be sorted*/ sort(arr, arr + n); cout << "\nArray after sorting using " "default sort is : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0;} 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. Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9 How to sort in descending order? sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass the β€œgreater()” function to sort in descending order. This function does a comparison in a way that puts greater elements before. CPP // C++ program to demonstrate descending order sort using// greater<>().#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n, greater<int>()); cout << "Array after sorting : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0;} Array after sorting : 9 8 7 6 5 4 3 2 1 0 Sort the array only in the given range: To deal with such types of problems we just have to mention the range inside the sort function.Below is the implementation of above case: C++ // C++ program to demonstrate sort() #include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 0, 1, 5, 8, 9, 6, 7, 3, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Sort the elements which lies in the range of 2 to // (n-1) sort(arr + 2, arr + n); cout << "Array after sorting : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0;}// This code is contributed by Suruchi Kumari Array after sorting : 0 1 2 3 4 5 6 7 8 9 How to sort in a particular order? We can also write our own comparator function and pass it as a third parameter. This β€œcomparator” function returns a value; convertible to bool, which basically tells us whether the passed β€œfirst” argument should be placed before the passed β€œsecond” argument or not. For eg: In the code below, suppose intervals {6,8} and {1,9} are passed as arguments in the β€œcompareInterval” function(comparator function). Now as i1.first (=6) < i2.first (=1), so our function returns β€œfalse”, which tells us that β€œfirst” argument should not be placed before β€œsecond” argument and so sorting will be done in order like {1,9} first and then {6,8} as next. CPP // A C++ program to demonstrate// STL sort() using// our own comparator#include <bits/stdc++.h>using namespace std; // An interval has a start// time and end timestruct Interval { int start, end;}; // Compares two intervals// according to starting times.bool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start);} int main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); // sort the intervals in increasing order of // start time sort(arr, arr + n, compareInterval); cout << "Intervals sorted by start time : \n"; for (int i = 0; i < n; i++) cout << "[" << arr[i].start << "," << arr[i].end << "] "; return 0;} Intervals sorted by start time : [1,9] [2,4] [4,7] [6,8] The time complexity of std::sort() is: Best Case – O(N log N)Average Case – O(N log N)Worst-Case – O(N log N) Best Case – O(N log N) Average Case – O(N log N) Worst-Case – O(N log N) Space Complexity: It may use O( log N) auxiliary space. C++ #include <algorithm>#include <iostream>using namespace std; template <class T>class Comparator { // we pass an object of this class as // third arg to sort function...public: bool operator()(T x1, T x2) { return x1 < x2; }}; template <class T> bool funComparator(T x1, T x2){ // return type is bool return x1 <= x2;} void show(int a[], int array_size){ for (int i = 0; i < array_size; i++) { cout << a[i] << " "; }} int main(){ int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int asize = sizeof(a) / sizeof(int); cout << "The array before sorting is : "; show(a, asize); cout << endl << "The array after sorting is(asc) :"; sort(a, a + asize); show(a, asize); cout << endl << "The array after sorting is(desc) :"; sort(a, a + asize, greater<int>()); show(a, asize); cout << endl << "The array after sorting is(asc but our " "comparator class) :"; sort(a, a + asize, Comparator<int>()); show(a, asize); cout << endl << "The array after sorting is(asc but our " "comparator function) :"; sort(a, a + asize, funComparator<int>); show(a, asize); return 0;} The array before sorting is : 1 5 8 9 6 7 3 4 2 0 The array after sorting is(asc) :0 1 2 3 4 5 6 7 8 9 The array after sorting is(desc) :9 8 7 6 5 4 3 2 1 0 The array after sorting is(asc but our comparator class) :0 1 2 3 4 5 6 7 8 9 The array after sorting is(asc but our comparator function) :0 1 2 3 4 5 6 7 8 9 This article is contributed by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above rahuku AbhishekSharma5 praddyumn ankitsinghrajput varshagumber28 tanmaynikam2002 vi5hnu suruchikumarimfp4 Anshul_Aggarwal joydeephalder cpp-algorithm-library CPP-Library STL C Language C++ Sorting Sorting STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 181, "s": 52, "text": "We have discussed qsort() in C. C++ STL provides a similar function sort that sorts a vector or array (items with random access)" }, { "code": null, "e": 514, "s": 181, "text": "It generally takes two parameters, the first one being the point of the array/vector from where the sorting needs to begin and the second parameter being the length up to which we want the array/vector to get sorted. The third parameter is optional and can be used in cases such as if we want to sort the elements lexicographically." }, { "code": null, "e": 585, "s": 514, "text": "By default, the sort() function sorts the elements in ascending order." }, { "code": null, "e": 643, "s": 585, "text": "Below is a simple program to show the working of sort(). " }, { "code": null, "e": 647, "s": 643, "text": "CPP" }, { "code": "// C++ program to demonstrate default behaviour of// sort() in STL.#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); /*Here we take two parameters, the beginning of the array and the length n upto which we want the array to be sorted*/ sort(arr, arr + n); cout << \"\\nArray after sorting using \" \"default sort is : \\n\"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; return 0;}", "e": 1171, "s": 647, "text": null }, { "code": null, "e": 1180, "s": 1171, "text": "Chapters" }, { "code": null, "e": 1207, "s": 1180, "text": "descriptions off, selected" }, { "code": null, "e": 1257, "s": 1207, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1280, "s": 1257, "text": "captions off, selected" }, { "code": null, "e": 1288, "s": 1280, "text": "English" }, { "code": null, "e": 1312, "s": 1288, "text": "This is a modal window." }, { "code": null, "e": 1381, "s": 1312, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1403, "s": 1381, "text": "End of dialog window." }, { "code": null, "e": 1469, "s": 1403, "text": "Array after sorting using default sort is : \n0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 1746, "s": 1469, "text": "How to sort in descending order? sort() takes a third parameter that is used to specify the order in which elements are to be sorted. We can pass the β€œgreater()” function to sort in descending order. This function does a comparison in a way that puts greater elements before. " }, { "code": null, "e": 1750, "s": 1746, "text": "CPP" }, { "code": "// C++ program to demonstrate descending order sort using// greater<>().#include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n, greater<int>()); cout << \"Array after sorting : \\n\"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; return 0;}", "e": 2129, "s": 1750, "text": null }, { "code": null, "e": 2173, "s": 2129, "text": "Array after sorting : \n9 8 7 6 5 4 3 2 1 0 " }, { "code": null, "e": 2351, "s": 2173, "text": "Sort the array only in the given range: To deal with such types of problems we just have to mention the range inside the sort function.Below is the implementation of above case:" }, { "code": null, "e": 2355, "s": 2351, "text": "C++" }, { "code": "// C++ program to demonstrate sort() #include <bits/stdc++.h>using namespace std; int main(){ int arr[] = { 0, 1, 5, 8, 9, 6, 7, 3, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); // Sort the elements which lies in the range of 2 to // (n-1) sort(arr + 2, arr + n); cout << \"Array after sorting : \\n\"; for (int i = 0; i < n; ++i) cout << arr[i] << \" \"; return 0;}// This code is contributed by Suruchi Kumari", "e": 2801, "s": 2355, "text": null }, { "code": null, "e": 2845, "s": 2801, "text": "Array after sorting : \n0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 3521, "s": 2845, "text": "How to sort in a particular order? We can also write our own comparator function and pass it as a third parameter. This β€œcomparator” function returns a value; convertible to bool, which basically tells us whether the passed β€œfirst” argument should be placed before the passed β€œsecond” argument or not. For eg: In the code below, suppose intervals {6,8} and {1,9} are passed as arguments in the β€œcompareInterval” function(comparator function). Now as i1.first (=6) < i2.first (=1), so our function returns β€œfalse”, which tells us that β€œfirst” argument should not be placed before β€œsecond” argument and so sorting will be done in order like {1,9} first and then {6,8} as next. " }, { "code": null, "e": 3525, "s": 3521, "text": "CPP" }, { "code": "// A C++ program to demonstrate// STL sort() using// our own comparator#include <bits/stdc++.h>using namespace std; // An interval has a start// time and end timestruct Interval { int start, end;}; // Compares two intervals// according to starting times.bool compareInterval(Interval i1, Interval i2){ return (i1.start < i2.start);} int main(){ Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof(arr) / sizeof(arr[0]); // sort the intervals in increasing order of // start time sort(arr, arr + n, compareInterval); cout << \"Intervals sorted by start time : \\n\"; for (int i = 0; i < n; i++) cout << \"[\" << arr[i].start << \",\" << arr[i].end << \"] \"; return 0;}", "e": 4274, "s": 3525, "text": null }, { "code": null, "e": 4333, "s": 4274, "text": "Intervals sorted by start time : \n[1,9] [2,4] [4,7] [6,8] " }, { "code": null, "e": 4372, "s": 4333, "text": "The time complexity of std::sort() is:" }, { "code": null, "e": 4443, "s": 4372, "text": "Best Case – O(N log N)Average Case – O(N log N)Worst-Case – O(N log N)" }, { "code": null, "e": 4466, "s": 4443, "text": "Best Case – O(N log N)" }, { "code": null, "e": 4492, "s": 4466, "text": "Average Case – O(N log N)" }, { "code": null, "e": 4516, "s": 4492, "text": "Worst-Case – O(N log N)" }, { "code": null, "e": 4572, "s": 4516, "text": "Space Complexity: It may use O( log N) auxiliary space." }, { "code": null, "e": 4576, "s": 4572, "text": "C++" }, { "code": "#include <algorithm>#include <iostream>using namespace std; template <class T>class Comparator { // we pass an object of this class as // third arg to sort function...public: bool operator()(T x1, T x2) { return x1 < x2; }}; template <class T> bool funComparator(T x1, T x2){ // return type is bool return x1 <= x2;} void show(int a[], int array_size){ for (int i = 0; i < array_size; i++) { cout << a[i] << \" \"; }} int main(){ int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int asize = sizeof(a) / sizeof(int); cout << \"The array before sorting is : \"; show(a, asize); cout << endl << \"The array after sorting is(asc) :\"; sort(a, a + asize); show(a, asize); cout << endl << \"The array after sorting is(desc) :\"; sort(a, a + asize, greater<int>()); show(a, asize); cout << endl << \"The array after sorting is(asc but our \" \"comparator class) :\"; sort(a, a + asize, Comparator<int>()); show(a, asize); cout << endl << \"The array after sorting is(asc but our \" \"comparator function) :\"; sort(a, a + asize, funComparator<int>); show(a, asize); return 0;}", "e": 5770, "s": 4576, "text": null }, { "code": null, "e": 6091, "s": 5770, "text": "The array before sorting is : 1 5 8 9 6 7 3 4 2 0 \nThe array after sorting is(asc) :0 1 2 3 4 5 6 7 8 9 \nThe array after sorting is(desc) :9 8 7 6 5 4 3 2 1 0 \nThe array after sorting is(asc but our comparator class) :0 1 2 3 4 5 6 7 8 9 \nThe array after sorting is(asc but our comparator function) :0 1 2 3 4 5 6 7 8 9 " }, { "code": null, "e": 6264, "s": 6091, "text": "This article is contributed by Shubham Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 6271, "s": 6264, "text": "rahuku" }, { "code": null, "e": 6287, "s": 6271, "text": "AbhishekSharma5" }, { "code": null, "e": 6297, "s": 6287, "text": "praddyumn" }, { "code": null, "e": 6314, "s": 6297, "text": "ankitsinghrajput" }, { "code": null, "e": 6329, "s": 6314, "text": "varshagumber28" }, { "code": null, "e": 6345, "s": 6329, "text": "tanmaynikam2002" }, { "code": null, "e": 6352, "s": 6345, "text": "vi5hnu" }, { "code": null, "e": 6370, "s": 6352, "text": "suruchikumarimfp4" }, { "code": null, "e": 6386, "s": 6370, "text": "Anshul_Aggarwal" }, { "code": null, "e": 6400, "s": 6386, "text": "joydeephalder" }, { "code": null, "e": 6422, "s": 6400, "text": "cpp-algorithm-library" }, { "code": null, "e": 6434, "s": 6422, "text": "CPP-Library" }, { "code": null, "e": 6438, "s": 6434, "text": "STL" }, { "code": null, "e": 6449, "s": 6438, "text": "C Language" }, { "code": null, "e": 6453, "s": 6449, "text": "C++" }, { "code": null, "e": 6461, "s": 6453, "text": "Sorting" }, { "code": null, "e": 6469, "s": 6461, "text": "Sorting" }, { "code": null, "e": 6473, "s": 6469, "text": "STL" }, { "code": null, "e": 6477, "s": 6473, "text": "CPP" } ]
Types of HTML Lists
There are three types of lists in HTML βˆ’ unordered list <ul>This list has bullets list items with no specific order. This list has bullets list items with no specific order. ordered list <ol>This list is used for ordered list items This list is used for ordered list items definition list <dl>This list is used to display definitions for terms. This list is used to display definitions for terms. We can nest these lists and style them as desired. CSS property list-style helps us style the list items. The syntax of HTML lists is as follows βˆ’ <type of list> <li></li> </type of list> The following examples illustrate HTML lists βˆ’ Live Demo <!DOCTYPE html> <html> <head> <style> ul { background-color: papayawhip; list-style-type: square; font-style: italic; } ol { background-color: azure; } </style> </head> <body> <ol> <li>demo1</li> <li> demo 2 <ul> <li>demo a</li> <li>demo b</li> </ul> </li> <li>demo 3</li> </ol> </body> </html> This gives the following output βˆ’ Live Demo <!DOCTYPE html> <html> <head> <style> dt { font-weight: bold; font-style: italic; } dd { border: thin dotted; } </style> </head> <body> <h2>Programming Languages and Databases</h2> <dl> <dt>Java</dt> <dd>A programming language developed by James Gosling.</dd> <dt>C++</dt> <dd>A programming language developed by Bjarne Stroustrup.</dd> <dt>MySQL</dt> <dd>MySQL is an open-source relational database management system.</dd> </dl> </body> </html> This gives the following output βˆ’
[ { "code": null, "e": 1228, "s": 1187, "text": "There are three types of lists in HTML βˆ’" }, { "code": null, "e": 1304, "s": 1228, "text": "unordered list <ul>This list has bullets list items with no specific order." }, { "code": null, "e": 1361, "s": 1304, "text": "This list has bullets list items with no specific order." }, { "code": null, "e": 1419, "s": 1361, "text": "ordered list <ol>This list is used for ordered list items" }, { "code": null, "e": 1460, "s": 1419, "text": "This list is used for ordered list items" }, { "code": null, "e": 1532, "s": 1460, "text": "definition list <dl>This list is used to display definitions for terms." }, { "code": null, "e": 1584, "s": 1532, "text": "This list is used to display definitions for terms." }, { "code": null, "e": 1690, "s": 1584, "text": "We can nest these lists and style them as desired. CSS property list-style helps us style the list items." }, { "code": null, "e": 1731, "s": 1690, "text": "The syntax of HTML lists is as follows βˆ’" }, { "code": null, "e": 1772, "s": 1731, "text": "<type of list>\n<li></li>\n</type of list>" }, { "code": null, "e": 1819, "s": 1772, "text": "The following examples illustrate HTML lists βˆ’" }, { "code": null, "e": 1830, "s": 1819, "text": " Live Demo" }, { "code": null, "e": 2137, "s": 1830, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nul {\n background-color: papayawhip;\n list-style-type: square;\n font-style: italic;\n}\nol {\n background-color: azure;\n}\n</style>\n</head>\n<body>\n<ol>\n<li>demo1</li>\n<li>\ndemo 2\n<ul>\n<li>demo a</li>\n<li>demo b</li>\n</ul>\n</li>\n<li>demo 3</li>\n</ol>\n</body>\n</html>" }, { "code": null, "e": 2171, "s": 2137, "text": "This gives the following output βˆ’" }, { "code": null, "e": 2182, "s": 2171, "text": " Live Demo" }, { "code": null, "e": 2637, "s": 2182, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndt {\n font-weight: bold;\n font-style: italic;\n}\ndd {\n border: thin dotted;\n}\n</style>\n</head>\n<body>\n<h2>Programming Languages and Databases</h2>\n<dl>\n<dt>Java</dt>\n<dd>A programming language developed by James Gosling.</dd>\n<dt>C++</dt>\n<dd>A programming language developed by Bjarne Stroustrup.</dd>\n<dt>MySQL</dt>\n<dd>MySQL is an open-source relational database management system.</dd>\n</dl>\n</body>\n</html>" }, { "code": null, "e": 2671, "s": 2637, "text": "This gives the following output βˆ’" } ]
Find the hypotenuse of a right angled triangle with given two sides
21 Jun, 2022 Given the other two sides of a right angled triangle, the task is to find it’s hypotenuse.Examples: Input: side1 = 3, side2 = 4 Output: 5.00 32 + 42 = 52Input: side1 = 12, side2 = 15 Output: 19.21 Approach: Pythagoras theorem states that the square of hypotenuse of a right angled triangle is equal to the sum of squares of the other two sides.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include<bits/stdc++.h>#include <iostream>#include <iomanip>using namespace std; // Function to return the hypotenuse of the// right angled triangledouble findHypotenuse(double side1, double side2){ double h = sqrt((side1 * side1) + (side2 * side2)); return h;} // Driver codeint main(){ int side1 = 3, side2 = 4; cout << fixed << showpoint; cout << setprecision(2); cout << findHypotenuse(side1, side2);} // This code is contributed by// Surendra_Gangwar // Java implementation of the approachclass GFG { // Function to return the hypotenuse of the // right angled triangle static double findHypotenuse(double side1, double side2) { double h = Math.sqrt((side1 * side1) + (side2 * side2)); return h; } // Driver code public static void main(String s[]) { int side1 = 3, side2 = 4; System.out.printf("%.2f", findHypotenuse(side1, side2)); }} # Python implementation of the approach # Function to return the hypotenuse of the# right angled triangledef findHypotenuse(side1, side2): h = (((side1 * side1) + (side2 * side2))**(1/2)); return h; # Driver codeside1 = 3;side2 = 4; print(findHypotenuse(side1, side2)); # This code contributed by Rajput-Ji // C# implementation of the approachusing System; class GFG{ // Function to return the hypotenuse // of the right angled triangle static double findHypotenuse(double side1, double side2) { double h = Math.Sqrt((side1 * side1) + (side2 * side2)); return h; } // Driver code public static void Main() { int side1 = 3, side2 = 4; Console.Write("{0:F2}", findHypotenuse(side1, side2)); }} // This code is contributed// by Princi Singh <script>// java script implementation of the approach // Function to return the hypotenuse of the//right angled trianglefunction findHypotenuse(side1, side2){ let h = (((side1 * side1) + (side2 * side2))**(1/2)); return h;} // Driver codelet side1 = 3;let side2 = 4; document.write(findHypotenuse(side1, side2).toFixed(2)); // This code is contributed by Gottumukkala Bobby</script> 5.00 Time Complexity: O(log(2*(s2)) where s is the side of the rectangle. Auxiliary Space: O(1) SURENDRA_GANGWAR princi singh Rajput-Ji gottumukkalabobby krishnav4 triangle Java Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Iterate through List in Java Java program to count the occurrence of each character in a string using Hashmap How to Iterate HashMap in Java? Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 130, "s": 28, "text": "Given the other two sides of a right angled triangle, the task is to find it’s hypotenuse.Examples: " }, { "code": null, "e": 229, "s": 130, "text": "Input: side1 = 3, side2 = 4 Output: 5.00 32 + 42 = 52Input: side1 = 12, side2 = 15 Output: 19.21 " }, { "code": null, "e": 430, "s": 231, "text": "Approach: Pythagoras theorem states that the square of hypotenuse of a right angled triangle is equal to the sum of squares of the other two sides.Below is the implementation of the above approach: " }, { "code": null, "e": 434, "s": 430, "text": "C++" }, { "code": null, "e": 439, "s": 434, "text": "Java" }, { "code": null, "e": 447, "s": 439, "text": "Python3" }, { "code": null, "e": 450, "s": 447, "text": "C#" }, { "code": null, "e": 461, "s": 450, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>#include <iostream>#include <iomanip>using namespace std; // Function to return the hypotenuse of the// right angled triangledouble findHypotenuse(double side1, double side2){ double h = sqrt((side1 * side1) + (side2 * side2)); return h;} // Driver codeint main(){ int side1 = 3, side2 = 4; cout << fixed << showpoint; cout << setprecision(2); cout << findHypotenuse(side1, side2);} // This code is contributed by// Surendra_Gangwar", "e": 976, "s": 461, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the hypotenuse of the // right angled triangle static double findHypotenuse(double side1, double side2) { double h = Math.sqrt((side1 * side1) + (side2 * side2)); return h; } // Driver code public static void main(String s[]) { int side1 = 3, side2 = 4; System.out.printf(\"%.2f\", findHypotenuse(side1, side2)); }}", "e": 1419, "s": 976, "text": null }, { "code": "# Python implementation of the approach # Function to return the hypotenuse of the# right angled triangledef findHypotenuse(side1, side2): h = (((side1 * side1) + (side2 * side2))**(1/2)); return h; # Driver codeside1 = 3;side2 = 4; print(findHypotenuse(side1, side2)); # This code contributed by Rajput-Ji", "e": 1733, "s": 1419, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the hypotenuse // of the right angled triangle static double findHypotenuse(double side1, double side2) { double h = Math.Sqrt((side1 * side1) + (side2 * side2)); return h; } // Driver code public static void Main() { int side1 = 3, side2 = 4; Console.Write(\"{0:F2}\", findHypotenuse(side1, side2)); }} // This code is contributed// by Princi Singh", "e": 2331, "s": 1733, "text": null }, { "code": "<script>// java script implementation of the approach // Function to return the hypotenuse of the//right angled trianglefunction findHypotenuse(side1, side2){ let h = (((side1 * side1) + (side2 * side2))**(1/2)); return h;} // Driver codelet side1 = 3;let side2 = 4; document.write(findHypotenuse(side1, side2).toFixed(2)); // This code is contributed by Gottumukkala Bobby</script>", "e": 2722, "s": 2331, "text": null }, { "code": null, "e": 2727, "s": 2722, "text": "5.00" }, { "code": null, "e": 2798, "s": 2729, "text": "Time Complexity: O(log(2*(s2)) where s is the side of the rectangle." }, { "code": null, "e": 2820, "s": 2798, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 2837, "s": 2820, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 2850, "s": 2837, "text": "princi singh" }, { "code": null, "e": 2860, "s": 2850, "text": "Rajput-Ji" }, { "code": null, "e": 2878, "s": 2860, "text": "gottumukkalabobby" }, { "code": null, "e": 2888, "s": 2878, "text": "krishnav4" }, { "code": null, "e": 2897, "s": 2888, "text": "triangle" }, { "code": null, "e": 2911, "s": 2897, "text": "Java Programs" }, { "code": null, "e": 2930, "s": 2911, "text": "School Programming" }, { "code": null, "e": 3028, "s": 2930, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3066, "s": 3028, "text": "Factory method design pattern in Java" }, { "code": null, "e": 3123, "s": 3066, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 3152, "s": 3123, "text": "Iterate through List in Java" }, { "code": null, "e": 3233, "s": 3152, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 3265, "s": 3233, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 3283, "s": 3265, "text": "Python Dictionary" }, { "code": null, "e": 3308, "s": 3283, "text": "Reverse a string in Java" }, { "code": null, "e": 3324, "s": 3308, "text": "Arrays in C/C++" }, { "code": null, "e": 3347, "s": 3324, "text": "Introduction To PYTHON" } ]
HTML | <textarea> readonly Attribute - GeeksforGeeks
08 Jul, 2021 The <textarea> readonly attribute in HTML is used to specify that the textarea element is read-only. If the textarea is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute.Syntax: <textarea readonly> Contents... </textarea> Example 1: This example uses <textarea> readonly attribute to write content on input textarea which is readable only. html <!DOCTYPE html><html> <head> <title> HTML Textarea readonly Attribute </title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML Textarea readonly Attribute </h2> <p>A readonly Textarea.</p> <!--A readonly Textarea--> <textarea readonly>This textarea field is readonly. </textarea> </body></html> Output: Example 2: This example uses <textarea> readonly attribute to write content on input textarea which is readable only. html <!DOCTYPE html><html> <head> <title> HTML Textarea readonly Attribute </title> </head> <body style = "text-align:center"> <h1 style = "color: green;"> GeeksforGeeks </h1> <h2> HTML Textarea readonly Attribute </h2> <p>A readonly Textbox.</p> <textarea readonly="readonly" cols="15" rows="5"> This textarea can't be edited it is readonly only. </textarea> </body></html> Output: Supported Browsers: The browser supported by <textarea> readonly attribute are listed below: Apple Safari Google Chrome Firefox Opera Internet Explorer Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ruhelaa48 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24503, "s": 24475, "text": "\n08 Jul, 2021" }, { "code": null, "e": 24740, "s": 24503, "text": "The <textarea> readonly attribute in HTML is used to specify that the textarea element is read-only. If the textarea is readonly, then it’s content cannot be changed but can be copied and highlighted. It is a boolean attribute.Syntax: " }, { "code": null, "e": 24784, "s": 24740, "text": "<textarea readonly> Contents... </textarea>" }, { "code": null, "e": 24904, "s": 24784, "text": "Example 1: This example uses <textarea> readonly attribute to write content on input textarea which is readable only. " }, { "code": null, "e": 24909, "s": 24904, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Textarea readonly Attribute </title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML Textarea readonly Attribute </h2> <p>A readonly Textarea.</p> <!--A readonly Textarea--> <textarea readonly>This textarea field is readonly. </textarea> </body></html> ", "e": 25435, "s": 24909, "text": null }, { "code": null, "e": 25445, "s": 25435, "text": "Output: " }, { "code": null, "e": 25565, "s": 25445, "text": "Example 2: This example uses <textarea> readonly attribute to write content on input textarea which is readable only. " }, { "code": null, "e": 25570, "s": 25565, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML Textarea readonly Attribute </title> </head> <body style = \"text-align:center\"> <h1 style = \"color: green;\"> GeeksforGeeks </h1> <h2> HTML Textarea readonly Attribute </h2> <p>A readonly Textbox.</p> <textarea readonly=\"readonly\" cols=\"15\" rows=\"5\"> This textarea can't be edited it is readonly only. </textarea> </body></html> ", "e": 26130, "s": 25570, "text": null }, { "code": null, "e": 26140, "s": 26130, "text": "Output: " }, { "code": null, "e": 26235, "s": 26140, "text": "Supported Browsers: The browser supported by <textarea> readonly attribute are listed below: " }, { "code": null, "e": 26248, "s": 26235, "text": "Apple Safari" }, { "code": null, "e": 26262, "s": 26248, "text": "Google Chrome" }, { "code": null, "e": 26270, "s": 26262, "text": "Firefox" }, { "code": null, "e": 26276, "s": 26270, "text": "Opera" }, { "code": null, "e": 26294, "s": 26276, "text": "Internet Explorer" }, { "code": null, "e": 26433, "s": 26296, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26443, "s": 26433, "text": "ruhelaa48" }, { "code": null, "e": 26459, "s": 26443, "text": "HTML-Attributes" }, { "code": null, "e": 26464, "s": 26459, "text": "HTML" }, { "code": null, "e": 26481, "s": 26464, "text": "Web Technologies" }, { "code": null, "e": 26486, "s": 26481, "text": "HTML" }, { "code": null, "e": 26584, "s": 26486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26593, "s": 26584, "text": "Comments" }, { "code": null, "e": 26606, "s": 26593, "text": "Old Comments" }, { "code": null, "e": 26630, "s": 26606, "text": "REST API (Introduction)" }, { "code": null, "e": 26667, "s": 26630, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26696, "s": 26667, "text": "Form validation using jQuery" }, { "code": null, "e": 26743, "s": 26696, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 26805, "s": 26743, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 26861, "s": 26805, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26894, "s": 26861, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26937, "s": 26894, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26998, "s": 26937, "text": "Difference between var, let and const keywords in JavaScript" } ]
Angular 6 - Directives
Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below βˆ’ These form the main class having details of how the component should be processed, instantiated and used at runtime. A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor. Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below. In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard. Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is βˆ’ ng g directive nameofthedirective e.g ng g directive changeText This is how it appears in the command line C:\projectA6\Angular6App>ng g directive changeText CREATE src/app/change-text.directive.spec.ts (241 bytes) CREATE src/app/change-text.directive.ts (149 bytes) UPDATE src/app/app.module.ts (486 bytes) The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NewCmpComponent } from './new-cmp/new-cmp.component'; import { ChangeTextDirective } from './change-text.directive'; @NgModule({ declarations: [ AppComponent, NewCmpComponent, ChangeTextDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below. import { Directive } from '@angular/core'; @Directive({ selector: '[appChangeText]' }) export class ChangeTextDirective { constructor() { } } The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive. In the app.component.html view, let us add the directive as follows βˆ’ <div style = "text-align:center"> <span appChangeText >Welcome to {{title}}.</span> </div> We will write the changes in change-text.directive.ts file as follows βˆ’ import { Directive, ElementRef} from '@angular/core'; @Directive({ selector: '[appChangeText]' }) export class ChangeTextDirective { constructor(Element: ElementRef) { console.log(Element); Element.nativeElement.innerText = "Text is changed by changeText Directive. "; } } In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied. We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above. Now, the browser will show the following. 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": 2132, "s": 1995, "text": "Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below βˆ’" }, { "code": null, "e": 2249, "s": 2132, "text": "These form the main class having details of how the component should be processed, instantiated and used at runtime." }, { "code": null, "e": 2412, "s": 2249, "text": "A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor." }, { "code": null, "e": 2545, "s": 2412, "text": "Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below." }, { "code": null, "e": 2686, "s": 2545, "text": "In this section, we will discuss about Custom Directives to be used in components. Custom directives are created by us and are not standard." }, { "code": null, "e": 2850, "s": 2686, "text": "Let us see how to create the custom directive. We will create the directive using the command line. The command to create the directive using the command line is βˆ’" }, { "code": null, "e": 2915, "s": 2850, "text": "ng g directive nameofthedirective\ne.g\nng g directive changeText\n" }, { "code": null, "e": 2958, "s": 2915, "text": "This is how it appears in the command line" }, { "code": null, "e": 3160, "s": 2958, "text": "C:\\projectA6\\Angular6App>ng g directive changeText\nCREATE src/app/change-text.directive.spec.ts (241 bytes)\nCREATE src/app/change-text.directive.ts (149 bytes)\nUPDATE src/app/app.module.ts (486 bytes)\n" }, { "code": null, "e": 3293, "s": 3160, "text": "The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated." }, { "code": null, "e": 3791, "s": 3293, "text": "import { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport { NewCmpComponent } from './new-cmp/new-cmp.component';\nimport { ChangeTextDirective } from './change-text.directive';\n@NgModule({\n declarations: [\n AppComponent,\n NewCmpComponent,\n ChangeTextDirective\n ],\n imports: [\n BrowserModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" }, { "code": null, "e": 3926, "s": 3791, "text": "The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below." }, { "code": null, "e": 4074, "s": 3926, "text": "import { Directive } from '@angular/core';\n@Directive({\n selector: '[appChangeText]'\n})\nexport class ChangeTextDirective {\n constructor() { }\n}" }, { "code": null, "e": 4251, "s": 4074, "text": "The above file has a directive and it also has a selector property. Whatever we define in the selector, the same has to match in the view, where we assign the custom directive." }, { "code": null, "e": 4321, "s": 4251, "text": "In the app.component.html view, let us add the directive as follows βˆ’" }, { "code": null, "e": 4416, "s": 4321, "text": "<div style = \"text-align:center\">\n <span appChangeText >Welcome to {{title}}.</span>\n</div>\n" }, { "code": null, "e": 4488, "s": 4416, "text": "We will write the changes in change-text.directive.ts file as follows βˆ’" }, { "code": null, "e": 4782, "s": 4488, "text": "import { Directive, ElementRef} from '@angular/core';\n@Directive({\n selector: '[appChangeText]'\n})\nexport class ChangeTextDirective {\n constructor(Element: ElementRef) {\n console.log(Element);\n Element.nativeElement.innerText = \"Text is changed by changeText Directive. \";\n }\n}" }, { "code": null, "e": 5007, "s": 4782, "text": "In the above file, there is a class called ChangeTextDirective and a constructor, which takes the element of type ElementRef, which is mandatory. The element has all the details to which the Change Text directive is applied." }, { "code": null, "e": 5161, "s": 5007, "text": "We have added the console.log element. The output of the same can be seen in the browser console. The text of the element is also changed as shown above." }, { "code": null, "e": 5203, "s": 5161, "text": "Now, the browser will show the following." }, { "code": null, "e": 5238, "s": 5203, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5252, "s": 5238, "text": " Anadi Sharma" }, { "code": null, "e": 5287, "s": 5252, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5301, "s": 5287, "text": " Anadi Sharma" }, { "code": null, "e": 5336, "s": 5301, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5356, "s": 5336, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 5391, "s": 5356, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5408, "s": 5391, "text": " Frahaan Hussain" }, { "code": null, "e": 5441, "s": 5408, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 5453, "s": 5441, "text": " Senol Atac" }, { "code": null, "e": 5488, "s": 5453, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5500, "s": 5488, "text": " Senol Atac" }, { "code": null, "e": 5507, "s": 5500, "text": " Print" }, { "code": null, "e": 5518, "s": 5507, "text": " Add Notes" } ]
CSS | scrollbar-color Property - GeeksforGeeks
21 Nov, 2019 The scrollbar-color property is used to set the color of an element’s scrollbar. It can be used to control both the scrollbar track and scrollbar thumb colors separately.The track of a scrollbar is the background of the scrollbar which stays fixed and shows the area that can be scrolled. The thumb of the scrollbar refers to the moving part of the scrollbar that floats on top of the track and denotes the current position of the scroll. Syntax: scrollbar-color: auto | color | dark | light | initial | inherit Property Values: auto: It is used to set the scrollbar color to be automatically set by the browser. It is the default value and provides the browser default colors for rendering the scrollbar.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-auto { scrollbar-color: auto; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'auto'. </p> <div class="scrollbar-auto"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output: Example: <!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-auto { scrollbar-color: auto; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'auto'. </p> <div class="scrollbar-auto"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: color: It is used to set the scrollbar color to any custom color. It takes two values, the first is applied to the scrollbar thumb and the second color is applied to the scrollbar track.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: red green; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a red green scrollbar-color. </p> <div class="scrollbar-colored"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output: Example: <!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: red green; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a red green scrollbar-color. </p> <div class="scrollbar-colored"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: light: It is used to provide a lighter variant of the scrollbar which can be based on the default colors or a custom one. This property has been discontinued on all major browsers. dark: It is used to provide a darker variant of the scrollbar which can be based on the default colors or a custom one. This property has been discontinued on all major browsers. initial: It is used to set the color to its default value.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-initial { scrollbar-color: initial; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'initial'. </p> <div class="scrollbar-initial"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output: Example: <!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-initial { scrollbar-color: initial; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'initial'. </p> <div class="scrollbar-initial"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: inherit: It is used to inherit the color from its parent.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: green blue; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } .scrollbar-inherit { scrollbar-color: inherit; height: 75px; width: 100px; overflow-y: scroll; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a scrollable child element that inherits the parent's scrollbar color. </p> <div class="scrollbar-colored"> <div class="scrollbar-inherit"> This scrollbar color is inherited from the parent. </div> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output: inherit: It is used to inherit the color from its parent. Example: <!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: green blue; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } .scrollbar-inherit { scrollbar-color: inherit; height: 75px; width: 100px; overflow-y: scroll; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a scrollable child element that inherits the parent's scrollbar color. </p> <div class="scrollbar-colored"> <div class="scrollbar-inherit"> This scrollbar color is inherited from the parent. </div> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html> Output: Supported Browsers: The browsers supported by scrollbar-color property are listed below: Firefox 64 CSS-Properties CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript
[ { "code": null, "e": 24985, "s": 24957, "text": "\n21 Nov, 2019" }, { "code": null, "e": 25424, "s": 24985, "text": "The scrollbar-color property is used to set the color of an element’s scrollbar. It can be used to control both the scrollbar track and scrollbar thumb colors separately.The track of a scrollbar is the background of the scrollbar which stays fixed and shows the area that can be scrolled. The thumb of the scrollbar refers to the moving part of the scrollbar that floats on top of the track and denotes the current position of the scroll." }, { "code": null, "e": 25432, "s": 25424, "text": "Syntax:" }, { "code": null, "e": 25497, "s": 25432, "text": "scrollbar-color: auto | color | dark | light | initial | inherit" }, { "code": null, "e": 25514, "s": 25497, "text": "Property Values:" }, { "code": null, "e": 26454, "s": 25514, "text": "auto: It is used to set the scrollbar color to be automatically set by the browser. It is the default value and provides the browser default colors for rendering the scrollbar.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-auto { scrollbar-color: auto; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'auto'. </p> <div class=\"scrollbar-auto\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output:" }, { "code": null, "e": 26463, "s": 26454, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-auto { scrollbar-color: auto; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'auto'. </p> <div class=\"scrollbar-auto\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>", "e": 27212, "s": 26463, "text": null }, { "code": null, "e": 27220, "s": 27212, "text": "Output:" }, { "code": null, "e": 28182, "s": 27220, "text": "color: It is used to set the scrollbar color to any custom color. It takes two values, the first is applied to the scrollbar thumb and the second color is applied to the scrollbar track.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: red green; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a red green scrollbar-color. </p> <div class=\"scrollbar-colored\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output:" }, { "code": null, "e": 28191, "s": 28182, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: red green; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a red green scrollbar-color. </p> <div class=\"scrollbar-colored\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>", "e": 28952, "s": 28191, "text": null }, { "code": null, "e": 28960, "s": 28952, "text": "Output:" }, { "code": null, "e": 29141, "s": 28960, "text": "light: It is used to provide a lighter variant of the scrollbar which can be based on the default colors or a custom one. This property has been discontinued on all major browsers." }, { "code": null, "e": 29324, "s": 29141, "text": " dark: It is used to provide a darker variant of the scrollbar which can be based on the default colors or a custom one. This property has been discontinued on all major browsers. " }, { "code": null, "e": 30157, "s": 29327, "text": "initial: It is used to set the color to its default value.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-initial { scrollbar-color: initial; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'initial'. </p> <div class=\"scrollbar-initial\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output:" }, { "code": null, "e": 30166, "s": 30157, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-initial { scrollbar-color: initial; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has scrollbar-color set to 'initial'. </p> <div class=\"scrollbar-initial\"> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>", "e": 30923, "s": 30166, "text": null }, { "code": null, "e": 30931, "s": 30923, "text": "Output:" }, { "code": null, "e": 32039, "s": 30931, "text": "inherit: It is used to inherit the color from its parent.Example:<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: green blue; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } .scrollbar-inherit { scrollbar-color: inherit; height: 75px; width: 100px; overflow-y: scroll; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a scrollable child element that inherits the parent's scrollbar color. </p> <div class=\"scrollbar-colored\"> <div class=\"scrollbar-inherit\"> This scrollbar color is inherited from the parent. </div> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>Output:" }, { "code": null, "e": 32097, "s": 32039, "text": "inherit: It is used to inherit the color from its parent." }, { "code": null, "e": 32106, "s": 32097, "text": "Example:" }, { "code": "<!DOCTYPE html><html><head> <title> CSS | scrollbar-color </title> <style> .scrollbar-colored { scrollbar-color: green blue; height: 150px; width: 200px; overflow-y: scroll; background-color: lightgreen; } .scrollbar-inherit { scrollbar-color: inherit; height: 75px; width: 100px; overflow-y: scroll; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | scrollbar-color </b> <p> The container below has a scrollable child element that inherits the parent's scrollbar color. </p> <div class=\"scrollbar-colored\"> <div class=\"scrollbar-inherit\"> This scrollbar color is inherited from the parent. </div> GeeksforGeeks is a computer science portal with a huge variety of well written and explained computer science and programming articles, quizzes and interview questions. The portal also has dedicated GATE preparation and competitive programming sections. </div></body></html>", "e": 33142, "s": 32106, "text": null }, { "code": null, "e": 33150, "s": 33142, "text": "Output:" }, { "code": null, "e": 33239, "s": 33150, "text": "Supported Browsers: The browsers supported by scrollbar-color property are listed below:" }, { "code": null, "e": 33250, "s": 33239, "text": "Firefox 64" }, { "code": null, "e": 33265, "s": 33250, "text": "CSS-Properties" }, { "code": null, "e": 33269, "s": 33265, "text": "CSS" }, { "code": null, "e": 33286, "s": 33269, "text": "Web Technologies" }, { "code": null, "e": 33384, "s": 33286, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33393, "s": 33384, "text": "Comments" }, { "code": null, "e": 33406, "s": 33393, "text": "Old Comments" }, { "code": null, "e": 33443, "s": 33406, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 33472, "s": 33443, "text": "Form validation using jQuery" }, { "code": null, "e": 33511, "s": 33472, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 33553, "s": 33511, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 33588, "s": 33553, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 33644, "s": 33588, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 33677, "s": 33644, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33720, "s": 33677, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33781, "s": 33720, "text": "Difference between var, let and const keywords in JavaScript" } ]
MySQL temporary variable assignment?
You can use SET command for temporary variable assignment. The syntax is as follows SET @anyVariableName=(SELECT yourColumnName FROM yourTableName WHERE yourCondition); To understand the above syntax, let us create a table. The query to create a table is as follows mysql> create table tempVariableAssignment -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> Name varchar(20), -> Age int -> ); Query OK, 0 rows affected (0.59 sec) Now insert some records in the table using insert command mysql> insert into tempVariableAssignment(Name,Age) values('John',25); Query OK, 1 row affected (0.14 sec) mysql> insert into tempVariableAssignment(Name,Age) values('Carol',26); Query OK, 1 row affected (0.17 sec) mysql> insert into tempVariableAssignment(Name,Age) values('Sam',28); Query OK, 1 row affected (0.13 sec) mysql> insert into tempVariableAssignment(Name,Age) values('David',19); Query OK, 1 row affected (0.19 sec) mysql> insert into tempVariableAssignment(Name,Age) values('Bob',23); Query OK, 1 row affected (0.19 sec) Display all records from the table using select statement. The query is as follows mysql> select *from tempVariableAssignment; The following is the output +----+-------+------+ | Id | Name Age | +----+-------+------+ | 1 | John | 25 | | 2 | Carol | 26 | | 3 | Sam | 28 | | 4 | David | 19 | | 5 | Bob | 23 | +----+-------+------+ 5 rows in set (0.00 sec) Here is the query for MySQL temporary variable assignment mysql> set @findAge=(select Age from tempVariableAssignment where Id=4); Query OK, 0 rows affected (0.02 sec) Display the value of variable @findAge. The query is as follows mysql> select @findAge; The following is the output +----------+ | @findAge | +----------+ | 19 | +----------+ 1 row in set (0.01 sec) Here is an alternate query mysql> select Age INTO @anotherAge -> from tempVariableAssignment where Id=4; Query OK, 1 row affected (0.00 sec) Display the value of variable @anotherAge. The query is as follows mysql> select @anotherAge; The following is the output +-------------+ | @anotherAge | +-------------+ | 19 | +-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1121, "s": 1062, "text": "You can use SET command for temporary variable assignment." }, { "code": null, "e": 1146, "s": 1121, "text": "The syntax is as follows" }, { "code": null, "e": 1231, "s": 1146, "text": "SET @anyVariableName=(SELECT yourColumnName FROM yourTableName WHERE yourCondition);" }, { "code": null, "e": 1328, "s": 1231, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows" }, { "code": null, "e": 1513, "s": 1328, "text": "mysql> create table tempVariableAssignment\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> Name varchar(20),\n -> Age int\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1571, "s": 1513, "text": "Now insert some records in the table using insert command" }, { "code": null, "e": 2106, "s": 1571, "text": "mysql> insert into tempVariableAssignment(Name,Age) values('John',25);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into tempVariableAssignment(Name,Age) values('Carol',26);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into tempVariableAssignment(Name,Age) values('Sam',28);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into tempVariableAssignment(Name,Age) values('David',19);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into tempVariableAssignment(Name,Age) values('Bob',23);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 2165, "s": 2106, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2189, "s": 2165, "text": "The query is as follows" }, { "code": null, "e": 2233, "s": 2189, "text": "mysql> select *from tempVariableAssignment;" }, { "code": null, "e": 2261, "s": 2233, "text": "The following is the output" }, { "code": null, "e": 2484, "s": 2261, "text": "+----+-------+------+\n| Id | Name Age |\n+----+-------+------+\n| 1 | John | 25 |\n| 2 | Carol | 26 |\n| 3 | Sam | 28 |\n| 4 | David | 19 |\n| 5 | Bob | 23 |\n+----+-------+------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2542, "s": 2484, "text": "Here is the query for MySQL temporary variable assignment" }, { "code": null, "e": 2652, "s": 2542, "text": "mysql> set @findAge=(select Age from tempVariableAssignment where Id=4);\nQuery OK, 0 rows affected (0.02 sec)" }, { "code": null, "e": 2692, "s": 2652, "text": "Display the value of variable @findAge." }, { "code": null, "e": 2716, "s": 2692, "text": "The query is as follows" }, { "code": null, "e": 2740, "s": 2716, "text": "mysql> select @findAge;" }, { "code": null, "e": 2768, "s": 2740, "text": "The following is the output" }, { "code": null, "e": 2857, "s": 2768, "text": "+----------+\n| @findAge |\n+----------+\n| 19 |\n+----------+\n1 row in set (0.01 sec)" }, { "code": null, "e": 2884, "s": 2857, "text": "Here is an alternate query" }, { "code": null, "e": 2998, "s": 2884, "text": "mysql> select Age INTO @anotherAge\n-> from tempVariableAssignment where Id=4;\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 3041, "s": 2998, "text": "Display the value of variable @anotherAge." }, { "code": null, "e": 3065, "s": 3041, "text": "The query is as follows" }, { "code": null, "e": 3092, "s": 3065, "text": "mysql> select @anotherAge;" }, { "code": null, "e": 3120, "s": 3092, "text": "The following is the output" }, { "code": null, "e": 3224, "s": 3120, "text": "+-------------+\n| @anotherAge |\n+-------------+\n| 19 |\n+-------------+\n1 row in set (0.00 sec)" } ]
HTML rowspan Attribute
The HTML rowspan attribute define the number of rows a cell of a table should span in an HTML document. It can only be applied on td or th HTML element. Following is the syntax βˆ’ <tagname rowspan=”number”></tagname> Let us see an example of HTML rowspan Attribute βˆ’ Live Demo <!DOCTYPE html> <html> <style> body { color: #000; background: lightblue; height: 100vh; text-align: center; } table { margin: 2rem auto; width: 400px; } </style> <body> <h1>HTML rowspan Attribute Demo</h1> <table border="2"> <thead> <tr> <th>Name</th> <th>Language</th> </tr> <thead> <tbody> <tr> <td>John</td> <td>English</td> </tr> <tr> <td rowspan="2">Elon</td> <td>Germany</td> </tr> <tr> <td>French</td> </tr> </tbody> </table> </body> </html>
[ { "code": null, "e": 1215, "s": 1062, "text": "The HTML rowspan attribute define the number of rows a cell of a table should span in an HTML document. It can only be applied on td or th HTML element." }, { "code": null, "e": 1241, "s": 1215, "text": "Following is the syntax βˆ’" }, { "code": null, "e": 1278, "s": 1241, "text": "<tagname rowspan=”number”></tagname>" }, { "code": null, "e": 1328, "s": 1278, "text": "Let us see an example of HTML rowspan Attribute βˆ’" }, { "code": null, "e": 1338, "s": 1328, "text": "Live Demo" }, { "code": null, "e": 1836, "s": 1338, "text": "<!DOCTYPE html>\n<html>\n<style>\n body {\n color: #000;\n background: lightblue;\n height: 100vh;\n text-align: center;\n }\n table {\n margin: 2rem auto;\n width: 400px;\n }\n</style>\n<body>\n<h1>HTML rowspan Attribute Demo</h1>\n<table border=\"2\">\n<thead>\n<tr>\n<th>Name</th>\n<th>Language</th>\n</tr>\n<thead>\n<tbody>\n<tr>\n<td>John</td>\n<td>English</td>\n</tr>\n<tr>\n<td rowspan=\"2\">Elon</td>\n<td>Germany</td>\n</tr>\n<tr>\n<td>French</td>\n</tr>\n</tbody>\n</table>\n</body>\n</html>" } ]
How to link a submit button to another webpage using HTML?
Submit button automatically submits a form on click. Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc. To link a submit button to another webpage, use the form action attribute. Add the link in the attribute, for example βˆ’ <form action=”/new.php”> You can try to run the following code to link a submit button to another webpage βˆ’ <!DOCTYPE html> <html> <body> <form action="/new.php"> Student Name:<br> <input type="text" name="sname"> <br> Student Subject:<br> <input type="text" name="ssubject"> <br> <input type="submit" value="Submit"> </form> </body> </html>
[ { "code": null, "e": 1329, "s": 1062, "text": "Submit button automatically submits a form on click. Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc." }, { "code": null, "e": 1474, "s": 1329, "text": "To link a submit button to another webpage, use the form action attribute. Add the link in the attribute, for example βˆ’ <form action=”/new.php”>" }, { "code": null, "e": 1557, "s": 1474, "text": "You can try to run the following code to link a submit button to another webpage βˆ’" }, { "code": null, "e": 1854, "s": 1557, "text": "<!DOCTYPE html>\n<html>\n <body>\n <form action=\"/new.php\">\n Student Name:<br> <input type=\"text\" name=\"sname\">\n <br>\n Student Subject:<br> <input type=\"text\" name=\"ssubject\">\n <br>\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>" } ]
Implement Conditional MySQL Query in a stored procedure?
For conditional MySQL query, you can use IF ELSE concept in stored procedure. Let us first create a table βˆ’ mysql> create table DemoTable1 ( Id int ); Query OK, 0 rows affected (0.62 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable1 values(10); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1 values(20); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable1 values(30); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable1; This will produce the following output βˆ’ +------+ | Id | +------+ | 10 | | 20 | | 30 | +------+ 3 rows in set (0.00 sec) Following is the query to create second table. mysql> create table DemoTable2 ( Id int ); Query OK, 0 rows affected (1.07 sec) Insert some records in the table using insert command βˆ’ mysql> insert into DemoTable2 values(40); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable2 values(50); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2 values(60); Query OK, 1 row affected (0.11 sec) Display all records from the table using select statement βˆ’ mysql> select *from DemoTable2; This will produce the following output βˆ’ +------+ | Id | +------+ | 40 | | 50 | | 60 | +------+ 3 rows in set (0.00 sec) Following is the query to create a stored procedure for conditional MySQL query. mysql> DELIMITER // mysql> CREATE PROCEDURE Conditional_Query(id int) BEGIN IF id >=40 THEN Select * from DemoTable2; ELSE Select * from DemoTable1; END IF; END // Query OK, 0 rows affected (0.21 sec) mysql> DELIMITER ; Now you can call the stored procedure with the help of CALL command βˆ’ mysql> call Conditional_Query(100); This will produce the following output βˆ’ +------+ | Id | +------+ | 40 | | 50 | | 60 | +------+ 3 rows in set (0.00 sec) Query OK, 0 rows affected (0.03 sec) Call again and pass a different value βˆ’ mysql> call Conditional_Query(13); This will produce the following output βˆ’ +------+ | Id | +------+ | 10 | | 20 | | 30 | +------+ 3 rows in set (0.00 sec) Query OK, 0 rows affected (0.02 sec)
[ { "code": null, "e": 1170, "s": 1062, "text": "For conditional MySQL query, you can use IF ELSE concept in stored procedure. Let us first create a table βˆ’" }, { "code": null, "e": 1259, "s": 1170, "text": "mysql> create table DemoTable1\n (\n Id int\n );\nQuery OK, 0 rows affected (0.62 sec)" }, { "code": null, "e": 1315, "s": 1259, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 1551, "s": 1315, "text": "mysql> insert into DemoTable1 values(10);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable1 values(20);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into DemoTable1 values(30);\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1611, "s": 1551, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 1643, "s": 1611, "text": "mysql> select *from DemoTable1;" }, { "code": null, "e": 1684, "s": 1643, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 1772, "s": 1684, "text": "+------+\n| Id |\n+------+\n| 10 |\n| 20 |\n| 30 |\n+------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1819, "s": 1772, "text": "Following is the query to create second table." }, { "code": null, "e": 1908, "s": 1819, "text": "mysql> create table DemoTable2\n (\n Id int\n );\nQuery OK, 0 rows affected (1.07 sec)" }, { "code": null, "e": 1964, "s": 1908, "text": "Insert some records in the table using insert command βˆ’" }, { "code": null, "e": 2200, "s": 1964, "text": "mysql> insert into DemoTable2 values(40);\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DemoTable2 values(50);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable2 values(60);\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 2260, "s": 2200, "text": "Display all records from the table using select statement βˆ’" }, { "code": null, "e": 2292, "s": 2260, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2333, "s": 2292, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2421, "s": 2333, "text": "+------+\n| Id |\n+------+\n| 40 |\n| 50 |\n| 60 |\n+------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2502, "s": 2421, "text": "Following is the query to create a stored procedure for conditional MySQL query." }, { "code": null, "e": 2770, "s": 2502, "text": "mysql> DELIMITER //\n mysql> CREATE PROCEDURE Conditional_Query(id int)\n BEGIN\n IF id >=40 THEN\n Select * from DemoTable2;\n ELSE\n Select * from DemoTable1;\n END IF;\n END\n //\n Query OK, 0 rows affected (0.21 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 2840, "s": 2770, "text": "Now you can call the stored procedure with the help of CALL command βˆ’" }, { "code": null, "e": 2876, "s": 2840, "text": "mysql> call Conditional_Query(100);" }, { "code": null, "e": 2917, "s": 2876, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 3043, "s": 2917, "text": "+------+\n| Id |\n+------+\n| 40 |\n| 50 |\n| 60 |\n+------+\n3 rows in set (0.00 sec)\n\nQuery OK, 0 rows affected (0.03 sec)" }, { "code": null, "e": 3083, "s": 3043, "text": "Call again and pass a different value βˆ’" }, { "code": null, "e": 3118, "s": 3083, "text": "mysql> call Conditional_Query(13);" }, { "code": null, "e": 3159, "s": 3118, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 3285, "s": 3159, "text": "+------+\n| Id |\n+------+\n| 10 |\n| 20 |\n| 30 |\n+------+\n3 rows in set (0.00 sec)\n\nQuery OK, 0 rows affected (0.02 sec)" } ]
Web Scraping β€” Make your Own Dataset | by Suraj Gurav | Towards Data Science
Even though numerous resources available to get the required dataset, it is good to have a self-created dataset. In the current scenario of COVID-19, I found interesting data on worldometers.com. It shows a table containing total number of cases, total number of tests performed, total number of closed cases and so on. This table is updated daily. Just out of curiosity, I wanted this COVID-19 data in my own dataset. With the help of basic python libraries, pandas, numpy and BeautifulSoup I decided to scrape this entire data into my own data set. As I successfully created the dataset, I would like to share my story with you all. Hence, I will walk you through my Jupyter-Notebook. Web scraping is the process of collecting information from the web pages. When large amount of data is to be collected manually, huge amount of time and efforts is required. This is intense if the data to be collected is from regularly updated web pages. Hence, it is always better to have a script, which automatically extracts the data from web page and stores the it in required format. All you needed is a python package to parse HTML data from the website, arrange it in a tabular form and do some data cleaning. There are dozens of packages available to do this job, but my story continues with BeautifulSoup. BeautifulSoup It is a python library, which enables us to scrape all the content from a web page. Suppose there is a web page which contains some interesting information but provides no way to download the data directly. BeautifulSoup provides a set of tools to pull this data from the web page and locate the content which is hidden within the HTML structure. Let us jump into the process of creating own dataset... Step 1: Install the required packages You need requests package which allows you to send HTTP requests using Python. If you have it pre-installed, you need to just import it. Otherwise you need to install it using pip installer. pip install requestspip install beautifulsoup4 I used Python built-in HTML parser to transform the input text data from website into complex parse tree, which can be further processed to get the required data. If you want to use different parser, here you can find a assistance. Once you install all the packages, import them in your script. import pandas as pdimport numpy as npimport requestsfrom bs4 import BeautifulSoup Step 2: BeautifulSoup Constructor BeautifulSoup constructor takes 2 input arguments string β€” it is the markup that you want to parse. This markup is obtained using get () method of python requests package. This get() method returns the requests.Response()object which contains server’s response to the HTTP request. Additionally, text method of this response object gets the content of the response. This entire string is passed as first argument of BeautifulSoup constructor. parser β€” it is the method with which you want to parse the markup. You are expected to provide the name of the parser. I used python built-in HTML parser. website='https://www.worldometers.info/coronavirus/#countries'website_url=requests.get(website).textsoup = BeautifulSoup(website_url,'html.parser') That’s it.. In 3 lines of code you got all the content from required web page into your notebook. All the HTML text from Elements tab (marked in red), in developer tools will be stored in BeautifulSoup objectsoup. As seen in Picture 1 above, when you scroll over specific row in Elements tab , it will highlight corresponding cell in actual table on the website. Step 3: Pandas DataFrame In order to make a Pandas DataFrame, we need to transform all the text data in object soup in tabular format. In Picture 1 above, I also marked 3 green rectangles. These are the terms which you need to find in soup. Let us understand briefly, what does these terms mean β€” <tbody> : It specifies the table on the web page. <tr> : It points to the specific row in this table. <td> : It points to the particular cell in this row. In python script, you will use methods of object soup to find these term in the parsed text. my_table = soup.find('tbody') variable my_table will contain the table on the web page but still in HTML format. It contains the other two terms <tr> and <td> which points to individual rows and cells respectively. In below code, you will transform this my_table into actual table containing the columns and values. Please note that, below piece of code is written in April 2020. On later date, kindly check the order of the columns on the website and modify the code accordingly. table_data = []for row in my_table.findAll('tr'): row_data = [] for cell in row.findAll('td'): row_data.append(cell.text) if(len(row_data) > 0): data_item = {"Country": row_data[0], "TotalCases": row_data[1], "NewCases": row_data[2], "TotalDeaths": row_data[3], "NewDeaths": row_data[4], "TotalRecovered": row_data[5], "ActiveCases": row_data[6], "CriticalCases": row_data[7], "Totcase1M": row_data[8], "Totdeath1M": row_data[9], "TotalTests": row_data[10], "Tottest1M": row_data[11], } table_data.append(data_item) Now you get the table_data which is actually a table with columns and values. This table will be now transformed into a pandas DataFrame df. df = pd.DataFrame(table_data) Note that, all the columns are of object type in this DataFrame. Also, there are some unwanted characters such as /, \n, |, + in these objects. All the commonly used data cleaning processes can now be used on it. As per the individual requirement, you can extract different columns and rows from the original DataFrame, clean it and transform it as per requirement. Such collection of data, its assessment, cleaning and transformation is called as Data Wrangling process. Here is a quick read with interesting visualizations about Data Wrangling process. towardsdatascience.com Step 4: Export to Excel The cleaned, transformed final DataFrame can be then exported to excel using pandas. df.to_excel('Covid19_data.xlsx', index=True) Summing up, you created your own dataset for COVID-19. You can also create multiple data sets by scraping different web pages and finally combine all datasets together. Want to know more about combining different datasets ?? Here I have a simple 4-minute read about merging options in Python Pandas. All you need to remember is the last picture in the article below, which explains all types of data sets join operations. towardsdatascience.com And such self-created data set can be easily visualized using Matplotlib Python library and visualizations can be customized easily as given in the article below. medium.com Through my story... I walked you through 4 simple steps to scrape a web page into a excel sheet. I demonstrated how a web page can be scraped using easy to use BeautifulSoup package and transform this data into a pandas DataFrame. The complete notebook is available on my Github profile. Here are few resources, which can help you with this topic BeautifulSoup Requests Pandas Web scraping You are always welcome for a feedback with a comment and connect with me on LinkedIn!!!
[ { "code": null, "e": 521, "s": 172, "text": "Even though numerous resources available to get the required dataset, it is good to have a self-created dataset. In the current scenario of COVID-19, I found interesting data on worldometers.com. It shows a table containing total number of cases, total number of tests performed, total number of closed cases and so on. This table is updated daily." }, { "code": null, "e": 859, "s": 521, "text": "Just out of curiosity, I wanted this COVID-19 data in my own dataset. With the help of basic python libraries, pandas, numpy and BeautifulSoup I decided to scrape this entire data into my own data set. As I successfully created the dataset, I would like to share my story with you all. Hence, I will walk you through my Jupyter-Notebook." }, { "code": null, "e": 933, "s": 859, "text": "Web scraping is the process of collecting information from the web pages." }, { "code": null, "e": 1249, "s": 933, "text": "When large amount of data is to be collected manually, huge amount of time and efforts is required. This is intense if the data to be collected is from regularly updated web pages. Hence, it is always better to have a script, which automatically extracts the data from web page and stores the it in required format." }, { "code": null, "e": 1475, "s": 1249, "text": "All you needed is a python package to parse HTML data from the website, arrange it in a tabular form and do some data cleaning. There are dozens of packages available to do this job, but my story continues with BeautifulSoup." }, { "code": null, "e": 1489, "s": 1475, "text": "BeautifulSoup" }, { "code": null, "e": 1836, "s": 1489, "text": "It is a python library, which enables us to scrape all the content from a web page. Suppose there is a web page which contains some interesting information but provides no way to download the data directly. BeautifulSoup provides a set of tools to pull this data from the web page and locate the content which is hidden within the HTML structure." }, { "code": null, "e": 1892, "s": 1836, "text": "Let us jump into the process of creating own dataset..." }, { "code": null, "e": 1930, "s": 1892, "text": "Step 1: Install the required packages" }, { "code": null, "e": 2121, "s": 1930, "text": "You need requests package which allows you to send HTTP requests using Python. If you have it pre-installed, you need to just import it. Otherwise you need to install it using pip installer." }, { "code": null, "e": 2168, "s": 2121, "text": "pip install requestspip install beautifulsoup4" }, { "code": null, "e": 2400, "s": 2168, "text": "I used Python built-in HTML parser to transform the input text data from website into complex parse tree, which can be further processed to get the required data. If you want to use different parser, here you can find a assistance." }, { "code": null, "e": 2463, "s": 2400, "text": "Once you install all the packages, import them in your script." }, { "code": null, "e": 2545, "s": 2463, "text": "import pandas as pdimport numpy as npimport requestsfrom bs4 import BeautifulSoup" }, { "code": null, "e": 2579, "s": 2545, "text": "Step 2: BeautifulSoup Constructor" }, { "code": null, "e": 2629, "s": 2579, "text": "BeautifulSoup constructor takes 2 input arguments" }, { "code": null, "e": 3022, "s": 2629, "text": "string β€” it is the markup that you want to parse. This markup is obtained using get () method of python requests package. This get() method returns the requests.Response()object which contains server’s response to the HTTP request. Additionally, text method of this response object gets the content of the response. This entire string is passed as first argument of BeautifulSoup constructor." }, { "code": null, "e": 3177, "s": 3022, "text": "parser β€” it is the method with which you want to parse the markup. You are expected to provide the name of the parser. I used python built-in HTML parser." }, { "code": null, "e": 3325, "s": 3177, "text": "website='https://www.worldometers.info/coronavirus/#countries'website_url=requests.get(website).textsoup = BeautifulSoup(website_url,'html.parser')" }, { "code": null, "e": 3423, "s": 3325, "text": "That’s it.. In 3 lines of code you got all the content from required web page into your notebook." }, { "code": null, "e": 3688, "s": 3423, "text": "All the HTML text from Elements tab (marked in red), in developer tools will be stored in BeautifulSoup objectsoup. As seen in Picture 1 above, when you scroll over specific row in Elements tab , it will highlight corresponding cell in actual table on the website." }, { "code": null, "e": 3713, "s": 3688, "text": "Step 3: Pandas DataFrame" }, { "code": null, "e": 3929, "s": 3713, "text": "In order to make a Pandas DataFrame, we need to transform all the text data in object soup in tabular format. In Picture 1 above, I also marked 3 green rectangles. These are the terms which you need to find in soup." }, { "code": null, "e": 3985, "s": 3929, "text": "Let us understand briefly, what does these terms mean β€”" }, { "code": null, "e": 4035, "s": 3985, "text": "<tbody> : It specifies the table on the web page." }, { "code": null, "e": 4087, "s": 4035, "text": "<tr> : It points to the specific row in this table." }, { "code": null, "e": 4140, "s": 4087, "text": "<td> : It points to the particular cell in this row." }, { "code": null, "e": 4233, "s": 4140, "text": "In python script, you will use methods of object soup to find these term in the parsed text." }, { "code": null, "e": 4263, "s": 4233, "text": "my_table = soup.find('tbody')" }, { "code": null, "e": 4549, "s": 4263, "text": "variable my_table will contain the table on the web page but still in HTML format. It contains the other two terms <tr> and <td> which points to individual rows and cells respectively. In below code, you will transform this my_table into actual table containing the columns and values." }, { "code": null, "e": 4714, "s": 4549, "text": "Please note that, below piece of code is written in April 2020. On later date, kindly check the order of the columns on the website and modify the code accordingly." }, { "code": null, "e": 5487, "s": 4714, "text": "table_data = []for row in my_table.findAll('tr'): row_data = [] for cell in row.findAll('td'): row_data.append(cell.text) if(len(row_data) > 0): data_item = {\"Country\": row_data[0], \"TotalCases\": row_data[1], \"NewCases\": row_data[2], \"TotalDeaths\": row_data[3], \"NewDeaths\": row_data[4], \"TotalRecovered\": row_data[5], \"ActiveCases\": row_data[6], \"CriticalCases\": row_data[7], \"Totcase1M\": row_data[8], \"Totdeath1M\": row_data[9], \"TotalTests\": row_data[10], \"Tottest1M\": row_data[11], } table_data.append(data_item)" }, { "code": null, "e": 5628, "s": 5487, "text": "Now you get the table_data which is actually a table with columns and values. This table will be now transformed into a pandas DataFrame df." }, { "code": null, "e": 5658, "s": 5628, "text": "df = pd.DataFrame(table_data)" }, { "code": null, "e": 5871, "s": 5658, "text": "Note that, all the columns are of object type in this DataFrame. Also, there are some unwanted characters such as /, \\n, |, + in these objects. All the commonly used data cleaning processes can now be used on it." }, { "code": null, "e": 6024, "s": 5871, "text": "As per the individual requirement, you can extract different columns and rows from the original DataFrame, clean it and transform it as per requirement." }, { "code": null, "e": 6213, "s": 6024, "text": "Such collection of data, its assessment, cleaning and transformation is called as Data Wrangling process. Here is a quick read with interesting visualizations about Data Wrangling process." }, { "code": null, "e": 6236, "s": 6213, "text": "towardsdatascience.com" }, { "code": null, "e": 6260, "s": 6236, "text": "Step 4: Export to Excel" }, { "code": null, "e": 6345, "s": 6260, "text": "The cleaned, transformed final DataFrame can be then exported to excel using pandas." }, { "code": null, "e": 6390, "s": 6345, "text": "df.to_excel('Covid19_data.xlsx', index=True)" }, { "code": null, "e": 6445, "s": 6390, "text": "Summing up, you created your own dataset for COVID-19." }, { "code": null, "e": 6615, "s": 6445, "text": "You can also create multiple data sets by scraping different web pages and finally combine all datasets together. Want to know more about combining different datasets ??" }, { "code": null, "e": 6812, "s": 6615, "text": "Here I have a simple 4-minute read about merging options in Python Pandas. All you need to remember is the last picture in the article below, which explains all types of data sets join operations." }, { "code": null, "e": 6835, "s": 6812, "text": "towardsdatascience.com" }, { "code": null, "e": 6998, "s": 6835, "text": "And such self-created data set can be easily visualized using Matplotlib Python library and visualizations can be customized easily as given in the article below." }, { "code": null, "e": 7009, "s": 6998, "text": "medium.com" }, { "code": null, "e": 7029, "s": 7009, "text": "Through my story..." }, { "code": null, "e": 7297, "s": 7029, "text": "I walked you through 4 simple steps to scrape a web page into a excel sheet. I demonstrated how a web page can be scraped using easy to use BeautifulSoup package and transform this data into a pandas DataFrame. The complete notebook is available on my Github profile." }, { "code": null, "e": 7356, "s": 7297, "text": "Here are few resources, which can help you with this topic" }, { "code": null, "e": 7370, "s": 7356, "text": "BeautifulSoup" }, { "code": null, "e": 7379, "s": 7370, "text": "Requests" }, { "code": null, "e": 7386, "s": 7379, "text": "Pandas" }, { "code": null, "e": 7399, "s": 7386, "text": "Web scraping" } ]
How to add a legend on Seaborn facetgrid bar plot using Matplotlib?
Set the figure size and adjust the padding between and around the subplots. Create a dataframe with col1 columns. Multi-plot grid for plotting conditional relationships. Use map_dataframe(). This method is suitable for plotting with functions that accept a long-form DataFrame as a 'data' keyword argument and access the data in that DataFrame using string variable names. Add a legend to the plot(). To display the figure, use show() method. import pandas as pd import seaborn as sns from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True df = pd.DataFrame({'col1': [3, 7, 8]}) g = sns.FacetGrid(df, col="col1", hue="col1") g.map_dataframe(sns.scatterplot) g.set_axis_labels("X", "Y") g.add_legend() plt.show()
[ { "code": null, "e": 1138, "s": 1062, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1176, "s": 1138, "text": "Create a dataframe with col1 columns." }, { "code": null, "e": 1232, "s": 1176, "text": "Multi-plot grid for plotting conditional relationships." }, { "code": null, "e": 1435, "s": 1232, "text": "Use map_dataframe(). This method is suitable for plotting with functions that accept a long-form DataFrame as a 'data' keyword argument and access the data in that DataFrame using string variable names." }, { "code": null, "e": 1463, "s": 1435, "text": "Add a legend to the plot()." }, { "code": null, "e": 1505, "s": 1463, "text": "To display the figure, use show() method." }, { "code": null, "e": 1847, "s": 1505, "text": "import pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndf = pd.DataFrame({'col1': [3, 7, 8]})\n\ng = sns.FacetGrid(df, col=\"col1\", hue=\"col1\")\ng.map_dataframe(sns.scatterplot)\ng.set_axis_labels(\"X\", \"Y\")\ng.add_legend()\n\nplt.show()" } ]