code-rag-bench/online-tutorials huggingface dataset:
Left pad a String in Java with zeros

The following is our string −
String str = "Tim";
Now take a StringBuilder object −
StringBuilder strBuilder = new StringBuilder();
Perform left padding and extend the string length. We have set it till 20, that would include the current string as well. The zeros that will be padded comes on the left. Append the zeros here −
while (strBuilder.length() + str.length() < 10) {
strBuilder.append('0');
}
The following is an example −
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str = "Tim";
      StringBuilder strBuilder = new StringBuilder();
      while (strBuilder.length() + str.length() < 20) {
         strBuilder.append('0');
      }
      // append
      strBuilder.append(str);
      String res = strBuilder.toString();
      System.out.println(res);
   }
}
0000000000000000Tim
Function pointers in Java

From Java 8 onwards, the lambda expression is introduced which acts as function pointers.
Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies the development a lot.
A lambda expression is characterized by the following syntax.
parameter -> expression body
Following are the important characteristics of a lambda expression.
Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.
Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.
Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
Live Demo
public class Java8Tester {
   public static void main(String args[]) {
      Java8Tester tester = new Java8Tester();
      //with type declaration MathOperation addition = (int a, int b) -> a + b;
      //with out type declaration MathOperation subtraction = (a, b) -> a - b;
      //with return statement along with curly braces MathOperation multiplication =
         (int a, int b) -> { return a * b; };
      //without return statement and without curly braces MathOperation division =
         (int a, int b) -> a / b;
         System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
         System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
         System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
         System.out.println("10 / 5 = " + tester.operate(10, 5, division));
      //without parenthesis GreetingService greetService1 = message ->
         System.out.println("Hello " + message);
      //with parenthesis GreetingService greetService2 = (message) ->
         System.out.println("Hello " + message);
         greetService1.sayMessage("Mahesh");
         greetService2.sayMessage("Suresh");
   }

   interface MathOperation {
      int operation(int a, int b);
   }

   interface GreetingService {
      void sayMessage(String message);
   }

   private int operate(int a, int b, MathOperation mathOperation) {
      return mathOperation.operation(a, b);
   }
}
Compile the class using javac compiler as follows − 
C:\JAVA>javac Java8Tester.java
Now run the Java8Tester as follows − 
C:\JAVA>java Java8Tester
It should produce the following output − 
10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh
How to Add Markers to a Graph Plot in Matplotlib with Python?

16 Nov, 2020
Prerequisite: Matplotlib 
In this article we will learn how to add markers to a Graph Plot in Matplotlib with Python. For that just see some concepts that we will use in our work.
Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002.
Graph Plot : A plot is a graphical technique for representing a data set, usually as a graph showing the relationship between two or more variables.
Markers : The markers are shown in graph with different shapes and color to modify the meaning of graph.
To generate a graph with a modified marker style, following steps need to be followed:
Import packagesImport or create some dataDraw a graph plot.Set the marker by using marker feature.
Import packages
Import or create some data
Draw a graph plot.
Set the marker by using marker feature.
Example 1:
Python3
# importing packagesimport matplotlib.pyplot as plt  # plot with markerplt.plot([2, 8, 7, 4, 7, 6, 2, 5, 9], marker='D')plt.show()
Output :
Example 2 :
Python3
# importing packagesimport matplotlib.pyplot as plt  # create datat = np.arange(0., 5., 0.2)  # plot with markerplt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')plt.show()
Output :
Example 3 :
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # create datax_values = np.linspace(0, 10, 20)y_values = np.sin(x_values)markers = ['>', '+', '.', ',', 'o', 'v', 'x', 'X', 'D', '|']  # apply markersfor i in range(20):    plt.plot(x_values, y_values + i*0.2, markers[i % 10])plt.show()
Output :
Python-matplotlib
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
turtle.ycor() function in Python

21 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return the turtle’s y coordinate of the current position of turtle. It doesn’t require any argument.
Syntax :
turtle.ycor()

Below is the implementation of the above method with an example :
Example :
Python3
# import packageimport turtle    # check y coordinateprint(turtle.ycor())turtle.forward(100)  # check y coordinateprint(turtle.ycor())turtle.right(45)turtle.forward(100)  # check y coordinateprint(turtle.ycor())turtle.right(90)turtle.forward(100)  # check y coordinateprint(turtle.ycor())turtle.right(45)turtle.forward(100)  # check y coordinateprint(turtle.ycor())
Output :
0.0
0.0
-70.7106781187
-141.421356237
-141.421356237

Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | String hex Method

09 Dec, 2019
hex is a String class method in Ruby which is used to treats the leading characters from the given string as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error.
Syntax: str.hex
Parameters: Here, str is the given string.
Returns: A corresponding number.
Example 1:
# Ruby program to demonstrate # the hex method        # Taking a string and # using the methodputs "123678".hex                puts "Ruby".hex
Output:
1193592
0

Example 2:
# Ruby program to demonstrate # the hex method        # Taking a string and # using the methodputs "-87673".hex                puts "0x876adc".hex
Output:
-554611
8874716

Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Height Checker in Python

Suppose a set of students have to be arranged in non-decreasing order of their heights for a photograph. If we have an array of students, we have to return the minimum number of students that are not present in correct position. So if the array is like [1, 1, 4, 2, 1, 3], then output will be 3. So students with height 4, 3 and the last 1 are not standing in the correct position.
To solve this, we will follow these steps −
answer := 0
let x := Array in sorted form
ley y := Array
for i := 0 to size of Array – 1 −if x[i] is not same as y[i], then increase answer by 1
if x[i] is not same as y[i], then increase answer by 1
return answer
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def heightChecker(self, heights):
      ans = 0
      x = sorted(heights)
      y = heights
      for i in range(len(x)):
         if x[i]!=y[i]:
            ans+=1
      return ans
ob1 = Solution()
print(ob1.heightChecker([1,2,4,2,1,3]))
[1,1,4,2,1,3]
4
Bootstrap table-striped class

To implement the table-striped class in Bootstrap, you can try to run the following code:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Table</title>
      <meta name ="viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <table class = "table table-striped">
         <caption>Footballer Rank</caption>
         <thead>
            <tr>
               <th>Footballer</th>
               <th>Rank</th>
               <th>Country</th>
            </tr>
         </thead>
      </table>
   </body>
</html>
C# | Finding the index of last element in the array - GeeksforGeeks

01 Feb, 2019
GetUpperBound() Method is used to find the index of the last element of the specified dimension in the array.
Syntax:
public int GetUpperBound (int dimension);
Here, dimension is a zero-based dimension of the array whose upper bound needs to be determined.
Return Value:The return type of this method is System.Int32. This method returns the index of the last element of the specified dimension in the array Or -1 if the specified dimension is empty.
Exception: This method will give IndexOutOfRangeException if the value of dimension is less than zero, or equal or greater than Rank.
Note: GetUpperBound(0) returns the last index in the first dimension of the array, and GetUpperBound(Rank – 1) returns the last index of the last dimension of the array. This method is an O(1) operation.
Below programs illustrate the use of GetUpperBound() Method:
Example 1:
// C# program to illustrate the GetUpperBound(Int32)// method in 1-D arrayusing System;  public class GFG {          // Main method    static public void Main()    {          // 1-D Array        int[] value = {1, 2, 3, 4, 5, 6, 7};          // Get the index of the last element        // in the given Array by using         // GetUpperBound(Int32) method        int myvalue = value.GetUpperBound(0);                  Console.WriteLine("Index: {0}", myvalue);    }}
Index: 6

Example 2:
// C# program to find last index // value and rank of 2-D arrayusing System;  public class GFG {          // Main method    static public void Main()    {          // 2-D char Array        char[, ] value = { { 'a', 'b' }, { 'c', 'd' },                            { 'e', 'f' }, { 'g', 'h' },                                       { 'i', 'j' } };          // Get the index of the last element        // and the rank of the given Array        int myvalue = value.GetUpperBound(0);        Console.WriteLine("Dimension: {0}", value.Rank);        Console.WriteLine("Index: {0}", myvalue);    }}
Dimension: 2
Index: 4

Reference: https://docs.microsoft.com/en-us/dotnet/api/system.array.getupperbound?view=netcore-2.1
CSharp-Arrays
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
Design Patterns - Bridge Pattern

Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.
This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.
We are demonstrating use of Bridge pattern via following example in which a circle can be drawn in different colors using same abstract class method but different bridge implementer classes. 
We have a DrawAPI interface which is acting as a bridge implementer and concrete classes RedCircle, GreenCircle implementing the DrawAPI interface. Shape is an abstract class and will use object of DrawAPI. BridgePatternDemo, our demo class will use Shape class to draw different colored circle.
Create bridge implementer interface.
DrawAPI.java
public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}
Create concrete bridge implementer classes implementing the DrawAPI interface.
RedCircle.java
public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
   }
}
GreenCircle.java
public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]");
   }
}
Create an abstract class Shape using the DrawAPI interface.
Shape.java
public abstract class Shape {
   protected DrawAPI drawAPI;
   
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();	
}
Create concrete class implementing the Shape interface.
Circle.java
public class Circle extends Shape {
   private int x, y, radius;

   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }

   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}
Use the Shape and DrawAPI classes to draw different colored circles.
BridgePatternDemo.java
public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

      redCircle.draw();
      greenCircle.draw();
   }
}
Verify the output.
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
How to retrieve the Azure VM Subscription Name using PowerShell?

Once you are connected to the Azure Account, there are possibilities that the Get-AzVM will display the VMs from all the Azure Subscriptions.
To find the specific Azure VM Subscription name, we will first retrieve the details of the VM using the Get-AzVM and it has an ID property that contains the Subscription ID and from the subscription ID property, we can retrieve the name of the Azure Subscription Name.
PS C:\> $azvm = Get-AzVM -Name TestMachine2k16
PS C:\> $subid = ($azvm.Id -split '/')[2]
PS C:\> (Get-AzSubscription -SubscriptionId $subid).Name
The above will retrieve the name of the subscription.
HTML | Window createPopup() Method

11 Oct, 2019
The createPopup() method in html window is used to create a pop-up window.
Syntax:
window.createPopup()
Example:
<html>  <head>    <title>      DOM createPopup() Method  </title>    <style>        h1 {            color: green;        }    </style></head>  <head>    <script type="text/javascript">        function show_popup() {            var pop = window.createPopup()            var popbody = pop.document.body            popbody.style.backgroundColor = "lime"            popbody.style.border = "solid black 1px"            popbody.innerHTML =               "I am the pop-up, Click outside to close."            pop.show(150, 150, 200, 50, document.body)        }    </script></head>  <body>    <center>        <h1>          GeeksforGeeks      </h1>        <button onclick="show_popup()">          pop-up!      </button>    </center></body>  </html>
Output:
Note: The Window createPopup() Method works before Internet Explorer 11.
Supported browser:
Google Chrome: NO
Mozilla Firefox: NO
Edge: NO
Opera: NO
Safari: NO
shubham_singh
HTML-Methods
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
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
Python | Get the substring from given string using list slicing

05 Jul, 2022
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples.
A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more.
Syntax: myString[start:stop:step]
Parameter:
start: It is the index of the list where slicing starts.
stop: It is the index of the list where slicing ends.
step: It allows you to select nth item within the range start to stop.
Example 1: In this example, we will see how to take a substring from the end or from starting of the string. 
Python3
# Python3 code to demonstrate# to create a substring from a string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint("initial_strings : ", ini_string) # creating substring from start of string# define length upto which substring requiredsstring_strt = ini_string[:2]sstring_end = ini_string[3:] # printing resultprint("print resultant substring from start", sstring_strt)print("print resultant substring from end", sstring_end)
Output:
initial_strings :  xbzefdgstb
print resultant substring from start xb
print resultant substring from end efdgstb
Example 2: In this example, we will see how to create a string by taking characters from a certain positional gap. 
Python3
# Python3 code to demonstrate# to create a substring from string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint("initial_strings : ", ini_string) # creating substring by taking element# after certain position gap# define length upto which substring requiredsstring_alt = ini_string[::2]sstring_gap2 = ini_string[::3] # printing resultprint("print resultant substring from start", sstring_alt)print("print resultant substring from end", sstring_gap2)
Output:
initial_strings :  xbzefdgstb
print resultant substring from start xzfgt
print resultant substring from end xegb
Example 3: In this example, we are considering both cases of taking strings from the middle with some positional gap between characters. 
Python3
# Python3 code to demonstrate# to create a substring from string # Initialising stringini_string = 'xbzefdgstb' # printing initial string and characterprint ("initial_strings : ", ini_string) # creating substring by taking element# after certain position gap# in defined lengthsstring = ini_string[2:7:2] # printing resultprint ("print resultant substring", sstring)
Output:
initial_strings :  xbzefdgstb
print resultant substring zfg
surajkumarguptaintern
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | IsNullOrWhiteSpace() Method

31 Jan, 2019
In C#, IsNullOrWhiteSpace() is a string method. It is used to check whether the specified string is null or contains only white-space characters. A string will be null if it has not been assigned a value or has explicitly been assigned a value of null.
Syntax:
public static bool IsNullOrWhiteSpace(String str)  

Explanation: This method will take a parameter which is of type System.String and this method will return a boolean value. If the method’s parameter list is null or String.Empty, or only contains white-space characters then return True otherwise return False.
Example:
Input : str  = null         // initialize by null value
        String.IsNullOrWhiteSpace(str)
Output: True

Input : str  = " "  // initialize by whitespace
        String.IsNullOrWhiteSpace(str)
Output: True

Program: To demonstrate the working of the IsNullOrWhiteSpace() Method :
// C# program to illustrate // IsNullOrWhiteSpace() Methodusing System;class Geeks {        // Main Method    public static void Main(string[] args)    {        string s1 = null;          // for null value always return true        bool b1 = String.IsNullOrWhiteSpace(s1);        Console.WriteLine(b1);          string s2 = " ";          // for whitespace value always return true        bool b2 = String.IsNullOrWhiteSpace(s2);        Console.WriteLine(b2);          string s4 = " \n ";          // for new line value return true        bool b4 = String.IsNullOrWhiteSpace(s4);        Console.WriteLine(b4);          string s5 = "\t";          // for tab value return true        bool b5 = String.IsNullOrWhiteSpace(s5);        Console.WriteLine(b5);          string s6 = "\r";          // for carriage Return value return true        bool b6 = String.IsNullOrWhiteSpace(s6);        Console.WriteLine(b6);          string s7 = "GFG";          // for s7 it return False        bool b7 = String.IsNullOrWhiteSpace(s7);        Console.WriteLine(b7);    }}
True
True
True
True
True
False

Note: There is a alternative code of IsNullOrWhiteSpace() method as follows:
return String.IsNullOrEmpty(str) || str.Trim().Length == 0;

Program: To demonstrate IsNullOrEmpty() method’s alternative
// C# program to illustrate the // similar code for IsNullOrWhiteSpace()using System;class Geeks {      // similar code to     // IsNullOrWhiteSpace()    public static bool check(string str)    {        return(String.IsNullOrEmpty(str) ||               str.Trim().Length == 0) ? true : false;    }      // Main Method    public static void Main(string[] args)    {        string s1 = "GeeksforGeeks";        string s2 = " ";         string s3 = null;        string s4 = " \n ";          bool b1 = check(s1);        bool b2 = check(s2);        bool b3 = check(s3);        bool b4 = check(s4);          // To display result        Console.WriteLine(b1);        Console.WriteLine(b2);        Console.WriteLine(b3);        Console.WriteLine(b4);    }}
False
True
True
True

Reference: https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace
CSharp-method
CSharp-string
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to XPath

11 May, 2022
XPath(XML Path) is an expression which is used to find the element or say node in the XML document. In Selenium it is commonly used to find the web elements. Example:
//input[@id = 'fakebox-input']
In this example, We are locating the ‘input’ element whose ‘id’ is equal to ‘fakebox-input’  XML Code: 
html
<?xml version="1.0" encoding="UTF-8"?><bookstore>    <book category = "Math">    <title lang="en">IIT Mathematics</title>    <author>A Das Gupta</author>  </book>    <book category = "Chemistry">    <title lang="en"> Inorganic chemistry for JEE</title>    <author>V K Jaiswal</author>  </book>  </bookstore>
The XML Code is a tree like structure as we can see in the above XML, the code starts with the bookstore node that has a child node book and it is followed by an attribute category whose value is ‘Math’. The book node has 2 child node i.e. title and author. To select the author element of the chemistry book, the following XPath will be used:
/bookstore/book[@category='Chemistry']/author
Syntax of XPath:
//tagname[@attribute = ‘value’]
XPath Expressions:
Types of XPath:
Absolute XPath
Relative Xpath
Absolute XPath: Absolute XPath uses the root element of the HTML/XML code and followed by all the elements which are necessary to reach the desired element. It starts with the forward slash ‘/’ . Generally, Absolute XPath is not recommended because in future any of the web element when added or removed then Absolute XPath changes.
Example:
/html[1]/body[1]/div[6]/div[1]/div[3]/div[1]/div[1]/div[1]/div[3]/ul[1]/li[2]/a[1]
Relative XPath; In this, XPath begins with the double forward slash ‘//’ which means it can search the element anywhere in the Webpage. Generally Relative Xpath is preferred as they are not complete path from Root node.
Example:
//input[@id = 'fakebox-input']
If you want to learn how to make XPath identify webelements, Then open the webpage in chrome browser and inspect the element by right click on the webpage and after that press ‘ctrl+f’ to find the webelements using XPath. You can also use the chrome extension like ‘chropath’ to find the xpath for a webelement. Commonly Used XPath Functions:
contains()
Start-With()
Text()
contains(): This Function is used to select the node whose specified attribute value contains the specified string provided in the function argument. Example:
//input[contains(@id, 'fakebox')]
 starts-with(): This function is used to select the node whose specified attribute value starts with the specified string value provided in the function arguments. Example:
//input[starts-with(@id, 'fakebox')]
 text(): This function is used to find the node having the exact match with the specified string value in the function. Example:
//div
 Uses of AND and OR in XPath AND and OR are used to combine two or more conditions to find the node. Example:
//input[@value = 'Log In' or @type = 'submit']
 Similarly, We can apply AND operator in XPath.
mitalibhola94
HTML and XML
selenium
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GCD and LCM of two numbers in Java

Following is an example which computes find LCM and GCD of two given numbers.
import java.util.Scanner;
public class LCM_GCD {
   public static void lcm(int a, int b){
      int max, step, lcm = 0;
      if(a > b){
         max = step = a;
      } else{
         max = step = b;
      }
      while(a!= 0) {
         if(max%a == 0 && max%b == 0) {
            lcm = max;
            break;
         }
         max += step;
      }
      System.out.println("LCM of given numbers is :: "+lcm);
   }
   public static void gcd(int a,int b){
      int i, hcf = 0;
         for(i = 1; i <= a || i <= b; i++) {
            if( a%i == 0 && b%i == 0 )
            hcf = i;
         }
         System.out.println("gcd of given two numbers is ::"+hcf);
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number ::");
      int a = sc.nextInt();
      System.out.println("Enter second number ::");
      int b = sc.nextInt();
      lcm(a, b);
      gcd(a,b);
   }
}
Enter first number ::
125
Enter second number ::
25
LCM of given numbers is :: 125
GCD of given two numbers is ::25
Ensemble models for Classification | by Gaurika Tyagi | Towards Data Science

You have cleaned your data and removed all correlating features. You have also visualized your dataset and know the class labels are separable. You have also tuned your hyper-parameters. That's great, but why isn’t your model performing well?
Did you try stacking your models? Traditionally, we have modeled our data with a single algorithm. That might be a Logistic Regression, Gaussian Naive Bayes, or XGBoost.
Here’s what an ensemble stacking model does:
An algorithm that is used to combine the base estimators is called the meta learner. We can determine how we want this algorithm to respond to different predictions from other models(classifiers in this case). It can be:
Predictions of estimatorsPredictions as well as the original training data
Predictions of estimators
Predictions as well as the original training data
But is it the final class predictions only? No, you can choose what metric drives that decision:
It could be 'predict_proba', or 'predict' or bothYou can also use other 'decision_function' in sklearn
It could be 'predict_proba', or 'predict' or both
You can also use other 'decision_function' in sklearn
The final meta learner can then be any of the estimators (by default sklearn has logistic regression)
We take a baseline Gaussian Naive Bayes estimator and compare all future results to its prediction accuracy:
rf = OneVsRestClassifier(estimator = GaussianNB())cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=3, random_state=20)n_scores = cross_val_score(rf, X, y, scoring='f1_weighted', cv=cv, error_score='raise')print(n_scores)print('Baseline scores \n mean f1 weighted: %.3f with a %.3f standard deviation in scores ' % (np.mean(n_scores), np.std(n_scores)))
In the end, we wanted a classifier with an F1 score higher than 81.1% and we ended up getting an F1 score of 96.7% with a stacking model.
In the healthcare setup, I will take that 0.1% improvement over SVC models and not trade-off the stacked model’s complexity!
You can find the full code here: https://github.com/gaurikatyagi/Machine-Learning/blob/master/Classification/Ensemble%20Model-%20Stacked%20Classification.ipynb
Go stack now...
IDE | GeeksforGeeks | A computer science portal for geeks

Please enter your email address or userHandle.
Python Strings decode() method - GeeksforGeeks

19 Nov, 2020
decode() is a method specified in Strings in Python 2.This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.
Syntax : decode(encoding, error)
Parameters :encoding : Specifies the encoding on the basis of which decoding has to be performed.error : Decides how to handle the errors if they occur, e.g ‘strict’ raises Unicode error in case of exception and ‘ignore’ ignores the errors occurred.
Returns : Returns the original string from the encoded string.
 Code #1 : Code to decode the string
# Python code to demonstrate # decode()     # initializing string  str = "geeksforgeeks"    # encoding string  str_enc = str.encode(encodeing='utf8')     # printing the encoded string print ("The encoded string in base64 format is : ",) print (str_enc )    # printing the original decoded string  print ("The decoded string is : ",) print (str_enc.decode('utf8', 'strict'))
Output:
The encoded string in base64 format is :  Z2Vla3Nmb3JnZWVrcw==

The decoded string is :  geeksforgeeks

Application :Encoding and decoding together can be used in the simple applications of storing passwords in the back end and many other applications like cryptography which deals with keeping the information confidential.A small demonstration of the password application is depicted below.
 Code #2 : Code to demonstrate application of encode-decode
# Python code to demonstrate # application of encode-decode   # input from user # user = input() # pass = input()   user = "geeksforgeeks"passw = "i_lv_coding"  # converting password to base64 encoding passw = passw.encode('base64', 'strict')   # input from user # user_login = input() # pass_login = input()   user_login = "geeksforgeeks"  # wrongly entered password pass_wrong = "geeksforgeeks"  print ("Password entered : " + pass_wrong )  if(pass_wrong == passw.decode('base64', 'strict')):     print ("You are logged in !!")else : print ("Wrong Password !!")  print( '\r')  # correctly entered password pass_right = "i_lv_coding"  print ("Password entered : " + pass_right )  if(pass_right == passw.decode('base64', 'strict')):     print ("You are logged in !!")else :     print ("Wrong Password !!")
Output:
Password entered : geeksforgeeks
Wrong Password!!

Password entered : i_lv_coding
You are logged in!!

Python-Built-in-functions
Python-Functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
How to create a Popup Menu in Tkinter?

We need menubars in applications where user interaction is required. Menus can be created by initializing the Menu(parent) object along with the menu items. A popup Menu can be created by initializing tk_popup(x_root,y_root, False) which ensures that the menu is visible on the screen. Now, we will add an event which can be triggered through the Mouse Button (Right Click). The grab_release() method sets the mouse button release to unset the popup menu.
#Import the required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter frame
win = Tk()

#Set the geometry of the Tkinter library
win.geometry("700x350")

label = Label(win, text="Right-click anywhere to display a menu", font= ('Helvetica 18'))
label.pack(pady= 40)

#Add Menu
popup = Menu(win, tearoff=0)

#Adding Menu Items
popup.add_command(label="New")
popup.add_command(label="Edit")
popup.add_separator()
popup.add_command(label="Save")

def menu_popup(event):
   # display the popup menu
   try:
      popup.tk_popup(event.x_root, event.y_root, 0)
   finally:
      #Release the grab
      popup.grab_release()

win.bind("<Button-3>", menu_popup)

button = ttk.Button(win, text="Quit", command=win.destroy)
button.pack()

mainloop()
Running the above code will display a window with a Label and a button. When we right click with the Mouse, a popup menu will appear in the window.
What is arguments object in JavaScript?

Arguments object in JavaScript is an object, which represents the arguments to the function executing. Its syntax has two arguments:
[function.]arguments[p]
You can try to run the following code to learn what are arguments object in JavaScript
Live Demo
<html>
   <body>
      <script>
         function functionArgument(val1, val2, val3) {
            var res = "";
            res += "Expected Arguments: " + functionArgument.length;
            res += "<br />";
            res += "Current Arguments : " + arguments.length;

            res += "<br />";
            res += "Each argument = "

            for (p = 0; p < arguments.length; p++) {
               res += "<br />";
               res += functionArgument.arguments[p];
               res += " ";
            }
            document.write(res);
         }
         functionArgument(20, 50, 80, "Demo Text!","Hello World", new Date())
      </script>
   </body>
</html>
Difference between BIGINT and BIGINT(20) in MySQL?

The only difference between BIGINT and BIGINT(20) is for displaying width. The 20 can be used for displaying width.
Let us see an example and create a table. Here, we have set BIGINT(20) −
mysql> create table DemoTable
(
   Number bigint(20) zerofill
);
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values(12);
Query OK, 1 row affected (0.15 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.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output. The width is now 20, therefore the number expands and visible like below −
+----------------------+
| Number               |
+----------------------+
| 00000000000000000001 |
| 00000000000000000012 |
| 00000000000000000123 |
| 00000000000000001234 |
+----------------------+
4 rows in set (0.00 sec)
What is Bitwise OR Assignment Operator (|=) in JavaScript?

It performs OR operation on the right operand with the left operand and assigns the result to the left operand.
You can try to run the following code to learn how to work with Bitwise OR Assignment Operator −
<html>
   <body>
      <script>
         var a = 2; // Bit presentation 10
         var b = 3; // Bit presentation 11

         document.write("(a |= b) => ");
         document.write(a |= b);
      </script>
   </body>
</html>
How to center a Tkinter widget in a sticky frame?

Tkinter has lots of inbuilt functions and methods that can be used configure the properties of Tkinter widgets. These properties vary with different geometry managers. The grid geometry manager is one of them which deals with many complex layout problems in any application. Grid geometry manager adds all the widgets in the given space (if applicable) without overlapping each other.
Let us suppose that we have created a sticky frame using Grid geometry manager and we want to center the Label text widget inside the frame. In this case, we have to first make the main window sticky by configuring the row and column property. Once the main window gets sticky with the frame, it can make any widget rationally resizable. The label widget must be sticky in this case. Now, to center the widget, specify the value of the row, column and weight.
# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win= Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Add a frame to set the size of the window
frame= Frame(win, relief= 'sunken')
frame.grid(sticky= "we")

# Make the frame sticky for every case
frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)

# Make the window sticky for every case
win.grid_rowconfigure(0, weight=1)
win.grid_columnconfigure(0, weight=1)

# Add a label widget
label= Label(frame, text= "Hey Folks! Welcome to Tutorialspoint",
font=('Helvetica 15 bold'), bg= "white")
label.grid(row=3,column=0)
label.grid_rowconfigure(1, weight=1)
label.grid_columnconfigure(1, weight=1)

win.mainloop()
Executing the above code will display a centered Label Text lying inside the sticky frame.
How to execute zombie and orphan process in a single C program?

In this section we will see how to execute zombie process and orphan process in a single program in C/C++. Before going to the main discussion, let us see what are the zombie process and orphan process.
A zombie process is a process whose execution is completed but it still has an entry in the process table. Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit status. Once this is done using the wait system call, the zombie process is eliminated from the process table. This is known as reaping the zombie process.
Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally.
An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention.
An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism.
Now in the following code we will execute zombie and orphan process simultaneously. Here we have a parent process, it has a child, and this child has another child. If our control inserts into child process, then we will stop the execution for 5 seconds so it can finish up the parent process. Thus the child process become orphan process. After that the grandchild process will be converted into Zombie process. The grandchild finishes execution when its parent (the child of the main process) sleeps for 1 second. Hence the grandchild process does not call terminate, and its entry will be there in the process table.
#include <stdio.h>
#include <unistd.h>
int main() {
   int x = fork(); //create child process
   if (x > 0) //if x is non zero, then it is parent process
      printf("Inside Parent---- PID is : %d\n", getpid());
   else if (x == 0) { //for chile process x will be 0
      sleep(5); //wait for some times
      x = fork();
      if (x > 0) {
         printf("Inside Child---- PID :%d and PID of parent : %d\n", getpid(), getppid());
         while(1)
            sleep(1);
         printf("Inside Child---- PID of parent : %d\n", getppid());
      }else if (x == 0)
      printf("Inside grandchild process---- PID of parent : %d\n", getppid());
   }
   return 0;
}
soumyadeep@soumyadeep-VirtualBox:~$ ./a.out
Inside Parent---- PID is : 3821
soumyadeep@soumyadeep-VirtualBox:~$ Inside Child---- PID :3822 and PID of parent : 686
Inside grandchild process---- PID of parent : 3822
soumyadeep@soumyadeep-VirtualBox:~$
jQuery Effect - Slide Effect

The Slide effect can be used with show/hide/toggle. This slides the element out of the viewport.
Here is the simple syntax to use this effect −
selector.hide|show|toggle( "slide", {arguments}, speed );

Here is the description of all the arguments −
direction − The direction of the effect. Can be "left", "right", "up", "down". Default is left.
direction − The direction of the effect. Can be "left", "right", "up", "down". Default is left.
distance − The distance of the effect. Is set to either the height or width of the element depending on the direction option.
distance − The distance of the effect. Is set to either the height or width of the element depending on the direction option.
mode − The mode of the effect. Can be "show" or "hide". Default is show.
mode − The mode of the effect. Can be "show" or "hide". Default is show.
Following is a simple example a simple showing the usage of this effect −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
   
         $(document).ready(function() {

            $("#hide").click(function(){
               $(".target").hide( "slide", { direction: "down"  }, 2000 );
            });

            $("#show").click(function(){
               $(".target").show( "slide", {direction: "up" }, 2000 );
            });
				
         });
			
      </script>
		
      <style>
         p {background-color:#bca; width:200px; border:1px solid green;}
         div{ width:100px; height:100px; background:red;}
      </style>
   </head>
	
   <body>
      <p>Click on any of the buttons</p>
		
      <button id = "hide"> Hide </button>
      <button id = "show"> Show</button> 
  
      <div class = "target">
      </div>
   </body>
</html>
This will produce following result −
Click on any of the buttons

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
How to add a class on click of anchor tag using jQuery?

To add a class on click of anchor tag using jQuery, use the addClass() method. You can try to run the following code to learn how to implement adding a class on click of anchor tag using jQuery −
Live Demo
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
      $(document).ready(function() {
        $("a").click(function() {
          $("a.active").removeClass("active");
          $(this).addClass("active");
        });
      });
      </script>
      <style>
      .active {
         font-size: 22px;  
      }
      </style>
   </head>
   <body>
      <a href="#" class="">One</a>
      <a href="#" class="">Two</a>
      <p>Click any of the link above and you can see the changes.</p>
   </body>
</html>
Remember and copy passwords to clipboard using Pyperclip module in Python - GeeksforGeeks

19 Feb, 2020
It is always a difficult job to remember all our passwords for different accounts. So this is a really simple Python program which uses sys module to obtain account name as argument form the command terminal and pyperclip module to paste the respective account’s password to the clipboard.
Pyperclip module does not come pre-installed with Python. To install it type the below command in the terminal.
pip install pyperclip
Examples :
Command terminal Input : name_of_program.py facebookCommand terminal Output : Password : shubham456, for facebook account has been copied to the clipboard
Command terminal Input : name_of_program.py AyushiCommand terminal Output : No such account record exists
Approach : We initialize a dictionary with keys as account names and passwords as their values. Here sys.argv is the list of command-line arguments passed to the Python program, sys.argv[0] is the name of the Python program and sys.argv[1] corresponds to the first argument written by the user.
Then the program checks whether such an account (key) exists in the dictionary or not if such an account exists then it copies the password to the clipboard and displays a corresponding message. If no such account exists then the program displays a message that “No such account record exits”.
Below is the implementation of above approach :
import sys, pyperclip  # function to copy account passwords# to clipboarddef manager(account):         # dictionary in which keys are account     # name and values are their passwords    passwords ={ "email" : "Ayushi123",                 "facebook" : "shubham456",                "instagram" : "Ayushi789",                "geeksforgeeks" : "Ninja1"                }      if account in passwords:                  # copies password to clipboard        pyperclip.copy(passwords[account])          print("Password :", passwords[account],              ", for", account,             "account",               "has been copied to the clipboard")    else :        print("No such account record exits")            # Driver functionif __name__ == "__main__":      # command line argument that is name of     # account passed to program through cmd    account = sys.argv[1]      # calling manager function    manager(account)  # This article has been contributed by# Shubham Singh Chauhan
Output :
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists