code-rag-bench/online-tutorials huggingface dataset:
How to Make Grouped Boxplot with Jittered Data Points in ggplot2 in R

05 Nov, 2021
In this article, we will see how to make use of ggplot2 package in R Programming Language to plot grouped boxplots with jittered data points.
Grouped Boxplots help us visualize two or more features/variables in a single plot using the grouping variable in ggplot2. The jittered points are data points that belong to another variable and are plotted on top of the grouped boxplot for a better comparison of the spread of data points of the considered variables. 
Here we can use any in-built datasets in R (the list of datasets can be viewed using data( ) command) or even create one. Let’s create a data frame and visualize it.
R
# Creating a data frame  # variables for columnsgame = rep(c('Footsal', 'Slamdunk', 'VolleyBall'), each=50)level = rep(c('low', 'high'), each=25)score = runif(150, min=1, max=500)year = rep(c(1992,1993,1994),each=50)  data = data.frame(game, level, score,year)head(data)
Output:
Here we are going to plot boxplots using geom_boxplot() methods.
Syntax of geom_boxplot(): geom_boxplot(mapping = NULL, data = NULL, outlier.shape = 19, na.rm = FALSE ... )
Arguments:
mapping: Set of aesthetic mappings
data: data to be displayed in this layer
outlier.shape: Displaying the outliers, NA – hides the outliers
na.rm: dealing with missing values, TRUE – removes any missing values in data
Using ggplot2 let’s plot a grouped box plot using the data frame created. Let’s visualize a boxplot between score and game, filled by level. Here we can compare each level with respect to games.
R
# plotting a grouped boxplotlibrary(ggplot2)  ggplot(data, aes(x = game, y = score, fill = level)) + geom_boxplot()
Output:
Let’s visualize another boxplot between game and score, filled by level. This is the same as the above plot but with a changed axis which gives a clear comparison between each game with respect to the levels.
R
# another grouped boxplot  ggplot(data, aes(x = level, y = score, fill = game)) + geom_boxplot()
Output:
Here we are adding jitter data points into the grouped boxplot using geom_point() method.
Syntax of geom_point(): geom_point(mapping = NULL, data = NULL,  position = “identity”, ... )
Arguments:
mapping – Set of aesthetic mappings
data = dataset
position – Position adjustment of points
Let’s add jittered data points on the boxplot to visualize the spread of the data with respect to each game.
R
# Adding jittered data points on the boxplot  ggplot(data, aes(x = game, y = score, fill = level)) + geom_boxplot(outlier.shape = NA)+geom_point(position = position_jitterdodge(), alpha=0.3)
Output:
Let’s add jittered data points on the boxplot using geom_point( ) and facet_wrap( ) functions to compare the performance of scores in each game per year in different facets.
R
# jittered points on boxplots in 3 facets by year  ggplot(data, aes(x = level, y = score, fill = game)) + geom_boxplot()+geom_jitter(width = 0.1,alpha = 0.3) +facet_wrap(~year)
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Numeric floor() function

06 Jan, 2020
The floor() is an inbuilt method in Ruby returns a number less than or equal to the given number with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.
Syntax: num.floor(ndigits)
Parameters: The function needs a number and ndigits which specifies the number of digits to be round off. If ndigits is not given then, default value is taken to be zero.
Return Value: It returns returns a boolean value.
Example 1:
# Ruby program for floor()# method in Numeric  # Initialize a number num1 = -16.7834num2 = -16.78324num3 = 16.873  # Prints floorputs num1.floor(1)puts num2.floor()puts num3.floor()
Output:
-16.8
-17
16

Example 2:
# Ruby program for floor()# method in Numeric  # Initialize a number num1 = 12.32num2 = -1321.998321num3 = -12.2321  # Prints floorputs num1.floor(1)puts num2.floor(2)puts num3.floor(3)
Output:
12.3
-1322.0
-12.233
Ruby Numeric-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.ontimer() function in Python

26 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 install a timer, which calls fun after t milliseconds.
Syntax :
turtle.ontimer(fun, t=0)

Parameters:
    
Below is the implementation of the above method with an example :
Python3
# import packagesimport turtleimport random  # global colorscol = ['red', 'yellow', 'green', 'blue',       'white', 'black', 'orange', 'pink']  # method to call on timerdef fxn():    global col    ind = random.randint(0, 7)      # set background color of the    # turtle screen randomly    sc.bgcolor(col[ind])    # set screensc = turtle.Screen()sc.setup(400, 300)  # loop for timerfor i in range(10):    turtle.ontimer(fxn, t=400*(i+1))
Output :
Here we can find that after some time (set by timer) it automatically changes the background color of the turtle graphics window randomly.
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between LL and LR parser

29 Jul, 2019
LL Parser includes both the recursive descent parser and non-recursive descent parser. Its one type uses backtracking while another one uses parsing table. Theses are top down parser.Example: Given grammar is
S -> Ac
A -> ab 
where S is start symbol, A is non-terminal and a, b, c are terminals.
Input string: abcParse tree generated by LL parser:
LR Parser is one of the bottom up parser which uses parsing table (dynamic programming) to obtain the parse tree form given string using grammar productions.
Example: In the above example, parse tree generated by LR parser:
Difference between LL and LR parser:
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy matrix.transpose()

29 May, 2019
With the help of Numpy matrix.transpose() method, we can find the transpose of the matrix by using the matrix.transpose() method.
Syntax : matrix.transpose()Return : Return transposed matrix
Example #1 :In this example we can see that by using matrix.transpose() method we are able to find the transpose of the given matrix.
# import the important module in pythonimport numpy as np              # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]')              # applying matrix.transpose() methodgeek = gfg.transpose()    print(geek)
[[ 4 12]
 [ 1  3]]

Example #2 :
# import the important module in pythonimport numpy as np              # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')              # applying matrix.transpose() methodgeek = gfg.transpose()    print(geek)
[[ 4 12  4]
 [ 1  3  5]
 [ 9  1  6]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TimeSpan.Compare() Method in C#

25 Jan, 2022
This method is used to compare two TimeSpan values and returns an integer value which indicates whether the first value is shorter than, equal to, or longer than the second value. 
Syntax: public static int Compare (TimeSpan t1, TimeSpan t2);Parameters: t1: Specifies the first time interval that will be compared. t2: Specifies the second time interval that will be compared.Return Value: -1: If t1 is shorter than t2. 0: If t1 is equal to t2. 1: If t1 is longer than t2.  
Below programs illustrate the use of TimeSpan.Compare(TimeSpan, TimeSpan) Method:Example 1: 
csharp
// C# program to demonstrate the// TimeSpan.Compare(TimeSpan,// TimeSpan) Methodusing System; class GFG {     // Main Method    public static void Main()    {         // creating the TimeSpans        TimeSpan t1 = new TimeSpan(3, 22, 35, 33);        TimeSpan t2 = new TimeSpan(1, 11, 15, 16);         if (TimeSpan.Compare(t1, t2) == 1)            Console.Write("t1 is greater than t2");         else if (TimeSpan.Compare(t1, t2) == 0)            Console.Write("t1 is equal to t2");         else            Console.Write("t2 is greater than t1");    }}
t1 is greater than t2
 
Example 2:  
csharp
// C# program to demonstrate the// TimeSpan.Compare(TimeSpan,// TimeSpan) Methodusing System; class GFG {     // Main Method    public static void Main()    {         // creating the TimeSpans        TimeSpan t1 = new TimeSpan(3, 22, 35, 33);        TimeSpan t2 = new TimeSpan(4, 31, 15, 10);         if (TimeSpan.Compare(t1, t2) == 1)            Console.Write("t1 is greater than t2");         else if (TimeSpan.Compare(t1, t2) == 0)            Console.Write("t1 is equal to t2");         else            Console.Write("t2 is greater than t1");    }}
t2 is greater than t1
 
Example 3: 
csharp
// C# program to demonstrate the// TimeSpan.Compare(TimeSpan,// TimeSpan) Methodusing System; class GFG {     // Main Method    public static void Main()    {         // creating the TimeSpans        TimeSpan t1 = new TimeSpan(3, 22, 35, 33);        TimeSpan t2 = new TimeSpan(3, 22, 35, 33);         if (TimeSpan.Compare(t1, t2) == 1)            Console.Write("t1 is greater than t2");         else if (TimeSpan.Compare(t1, t2) == 0)            Console.Write("t1 is equal to t2");         else            Console.Write("t2 is greater than t1");    }}
t1 is equal to t2
 
Reference:  
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.compare?view=netframework-4.7.2
 
saurabh1990aror
CSharp-method
CSharp-TimeSpan-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Data Types
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
How to validate an Email using PHP?

13 Feb, 2019
This article contains different methods to validate an email address in PHP. It uses regular expressions and inbuilt email validation function. The input string is taken from the user and matches it with the predefined regular expressions and if the regular expression and input string found to be matched than it returns true and proceed further.
Method 1: Email validation using regular expression.
<?php// PHP program to validate email  // Function to validate email using regular expressionfunction email_validation($str) {    return (!preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $str))        ? FALSE : TRUE;}  // Function callif(!email_validation("author@geeksforgeeks.com")) {    echo "Invalid email address.";}else {    echo "Valid email address.";}  ?>
Valid email address.

Explanation: In the above example, passing the email to the user defined function email_validation( $email ), which use this example and matches with the regular expression by using the predefined function preg_match(). This predefined function match the whole input with regular expression and returns True if match found otherwise returns False.
Method 2: Email validation using filter_var() method.
<?php  // Declare variable and initialize// it to email$email = "author@geeksforgeeks.com";  // Validate emailif (filter_var($email, FILTER_VALIDATE_EMAIL)) {    echo("$email is a valid email address");} else {    echo("$email is not a valid email address");}  ?>
author@geeksforgeeks.com is a valid email address

Explanation: In the above example, passing the input email address to the predefined function filter_var(), which takes two parameters as input email and second is type of email filter. This function filters the email and returns true or false.
Method 3: Email validation using FILTER_SANITIZE_EMAIL filter.
<?php  // Declare variable and store it to email$email = "author.gfg@GeeksforGeeks.com";  // Remove all illegal characters from email$email = filter_var($email, FILTER_SANITIZE_EMAIL);  // Validate Emailif (filter_var($email, FILTER_VALIDATE_EMAIL)) {    echo("$email is a valid email address");} else {    echo("$email is not a valid email address");}  ?> 
author.gfg@GeeksforGeeks.com is a valid email address

Explanation: In the above example, use FILTER_SANITIZE_EMAIL filter to remove all unsupported characters and then use FILTER_VALIDATE_EMAIL filter to validate email.
Picked
Web-Programs
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
How to get parameters from a URL string in PHP?
Find common values between two NumPy arrays

29 Aug, 2020
In this article, we are going to discuss how to find out the common values between 2 arrays. To find the common values, we can use the numpy.intersect1d(), which will do the intersection operation and return the common values between the 2 arrays in sorted order.
Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False)
Parameters :arr1, arr2 : [array_like] Input arrays.assume_unique : [bool] If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.return_indices : [bool] If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.
Return : [ndarray] Sorted 1D array of common and unique elements.
Example #1: Finding common values between 1d arrays
Python3
import numpy as np    # create 2 arraysa = np.array([2, 4, 7, 1, 4])b = np.array([7, 2, 9, 0, 5])  # Display the arraysprint("Original arrays", a, ' ', b)  # use the np.intersect1d methodc = np.intersect1d(a, b)  # Display resultprint("Common values", c)
Output:
Original arrays [2 4 7 1 4]   [7 2 9 0 5]
Common values [2 7]

Example #2: Finding common values between n-dimensional arrays
Python3
import numpy as np    # create 2 arraysa = np.array([2,4,7,1,4,9]).reshape(3,2)b = np.array([7,2,9,0,5,3]).reshape(2,3)  # Display the arraysprint("Original arrays")print(a)print(b)  # use the np.intersect1d methodc = np.intersect1d(a,b)  # Display resultprint("Common values",c)
Output:
Original arrays
[[2 4]
 [7 1]
 [4 9]]
[[7 2 9]
 [0 5 3]]
Common values [2 7 9]

Note: No matter what dimension arrays are passed, the common values will be returned in a 1d flattened manner
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optional ofNullable() method in Java with examples

30 Jul, 2019
The ofNullable() method of java.util.Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. If the specified value is null, then this method returns an empty instance of the Optional class.
Syntax:
public static <T>
  Optional<T> ofNullable(T value)

Parameters: This method accepts value as parameter of type T to create an Optional instance with this value. It can be null.
Return value: This method returns an instance of this Optional class with the specified value of the specified type. If the specified value is null, then this method returns an empty instance of the Optional class.
Below programs illustrate ofNullable() method:Program 1:
// Java program to demonstrate// Optional.ofNullable() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op1            = Optional.ofNullable(9455);          // print value        System.out.println("Optional 1: "                           + op1);    }}
Optional 1: Optional[9455]

Program 2:
// Java program to demonstrate// Optional.ofNullable() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {        // create a Optional        Optional<String> op2            = Optional.ofNullable(null);          // print value        System.out.println("Optional 2: "                           + op2);    }}
Optional 2: Optional.empty

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ofNullable-T-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program to convert complex numbers to Polar coordinates

01 Oct, 2020
Before starting with the program, let’s see the basics of Polar Coordinates and then use Python’s cmath and abs module to convert it. Polar coordinates are just a different way of representing Cartesian coordinates or Complex Numbers. A complex number  z is defined as :
It is completely determined by its real part x and imaginary part y. Here, j is the imaginary unit.
The polar coordinates (r , φ) is completely determined by modulus r and phase angle φ.
Where,
r: Distance from z to origin, i.e., 
  φ: Counterclockwise angle measured from the positive x-axis to the line segment that joins z to the origin.
The conversion of complex numbers to polar co-ordinates are explained below with examples.
Python’s cmath module provides access to the mathematical functions for complex numbers. It contains several functions that are used for converting coordinates from one domain to another. 
Out of them, some are explained as-
1. cmath.polar(x):
Return the representation of x in polar coordinates. cmath.polar() function is used to convert a complex number to polar coordinates. 
Python3
# Python code to implement # the polar()function           # importing "cmath" # for mathematical operations import cmath       # using cmath.polar() method num = cmath.polar(1) print(num)
(1.0, 0.0)

2. cmath.phase (z): This method returns the phase of complex number z(also known as the argument of z).
Python3
import cmath    x = -1.0y = 0.0z = complex(x,y);   # printing phase of a complex number using phase() print ("The phase of complex number is : ",end="") print (cmath.phase(z)) 
The phase of complex number is : 3.141592653589793

abs(): This method returns the modulus (absolute value) of complex number z.
Python3
num1 = 3 + 4jprint('Absolute value of 3 + 4j is:', abs(num1))
Absolute value of 3 + 4j is: 5.0

You are given a complex number z and your task is to convert it to polar coordinates.
Let us consider a complex number as 1+5j, and we need to convert it to Polar coordinates. 
Python3
import cmath    c = complex(1+5j)print(abs(c))
5.0990195135927845

Python Cmath-library
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Replace Green Screen using OpenCV- Python

29 Aug, 2021
Prerequisites: OpenCV Python TutorialOpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. This library is cross-platform that is it is available on multiple programming languages such as Python, C++, etc.Green Screen removal is used in the VFX industry for changing the scenes. Here, we will use OpenCV – Python to do the same.  
Import all necessary librariesLoad the images or videosResize the images and the videos to the same sizeLoad the upper and lower BGR values of the green colorApply the mask and then use bitwise_andSubtract bitwise_and from the original green screen imageCheck for matrix value 0 after subtraction and replace it by the second imageYou get the desired results.
Import all necessary libraries
Load the images or videos
Resize the images and the videos to the same size
Load the upper and lower BGR values of the green color
Apply the mask and then use bitwise_and
Subtract bitwise_and from the original green screen image
Check for matrix value 0 after subtraction and replace it by the second image
You get the desired results.
Below is the implementation. 
Python3
import cv2import numpy as np video = cv2.VideoCapture("green.mp4")image = cv2.imread("bg.jpeg") while True:     ret, frame = video.read()     frame = cv2.resize(frame, (640, 480))    image = cv2.resize(image, (640, 480))      u_green = np.array([104, 153, 70])    l_green = np.array([30, 30, 0])     mask = cv2.inRange(frame, l_green, u_green)    res = cv2.bitwise_and(frame, frame, mask = mask)     f = frame - res    f = np.where(f == 0, image, f)     cv2.imshow("video", frame)    cv2.imshow("mask", f)     if cv2.waitKey(25) == 27:        break video.release()cv2.destroyAllWindows()
Output:  
 
sweetyty
Python-OpenCV
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
How do you give a C# Auto-Property a default value?

In C# 5.0 and before to give an value to the Auto Property we have to do in the constructor
The constructor will be automatically called when class is instantiated and the value will be set
After C#5.0 a new way to give a value to auto property has come which is similar in assigning a value to the variable
Set Value in Constructor
class Demo{
   public Demo(){
      FirstName = "DemoName";
   }
   public string FirstName { get; set; }
}
class Program{
   static void Main(){
      Demo obj = new Demo();
      System.Console.WriteLine(obj.FirstName);
      Console.ReadLine();
   }
}
DemoName
class Demo{
   public string FirstName { get; set; } = "DemoName";
}
class Program{
   static void Main(){
      Demo obj = new Demo();
      System.Console.WriteLine(obj.FirstName);
      Console.ReadLine();
   }
}
DemoName
How can we maintain session between Web Client and Web Server?

Following are the few options to maintain the session between the Web Client and the Web Server −
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not recommended to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used to keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
You can append some extra data at the end of each URL. This data identifies the session; the server can associate that session identifier with the data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid = 12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies. The drawback here is that you will have to generate every URL dynamically to assign a session ID though page is a simple static HTML page.
How can I cycle through line styles in Matplotlib?

To plot multiple lines in a diagram, we can use the cycler that could help to set a new color from the given list of colors. (Here, ‘r’ => ‘red’, ‘g’ => ‘green’, ‘y’ => ‘yellow’, ‘b’ => ‘blue’).
Use a cycler to set the color for the group of lines. The color list consists of ‘r’ for red, ‘g’ for green, ‘b’ for blue, and ‘y’ for yellow.
Use a cycler to set the color for the group of lines. The color list consists of ‘r’ for red, ‘g’ for green, ‘b’ for blue, and ‘y’ for yellow.
The cycler class helps to create a new Cycler object from a single positional argument, a pair of positional arguments, or the combination of keyword arguments.
The cycler class helps to create a new Cycler object from a single positional argument, a pair of positional arguments, or the combination of keyword arguments.
Plot the number of lines with different colors.
Plot the number of lines with different colors.
Use plt.show() to show the figure.
Use plt.show() to show the figure.
import matplotlib.pyplot as plt
from cycler import cycler

plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y'])))

plt.plot([0, 5])
plt.plot([2, 6])
plt.plot([3, 8])
plt.plot([4, 9])
plt.show()
What is string constant pool in Java?

When you store a String as
String str1 = "Hello";
directly, then JVM creates a String object with the given value in a separate block of memory known as String constant pool.
And whenever we try to create another String as
String str2 = "Hello";
JVM verifies whether any String object with the same value exists in the String constant pool, if so, instead of creating a new object JVM assigns the reference of the existing object to the new variable.
And when we store String as
String str = new String("Hello");
using the new keyword, a new object with the given value is created irrespective of the contents of the String constant pool.
Declare dynamically in SAP ABAP

I think for your implementation, you can declare an internal table in a dynamic manner.
DATA:  tbl_TEST TYPE REF TO DATA.
FIELD-SYMBOLS: < tbl_TEST > TYPE STANDARD TABLE
CREATE DATA tbl_TEST TYPE (Received_Type)
ASSIGN tbl_TEST TYPE ->* to < tbl_TEST TYPE >
Change Thread Priority in Java

A thread can be created by implementing the Runnable interface and overriding the run() method. Then a Thread object can be created and the start() method called.
The thread priority determines when the processor is provided to the thread as well as other resources. It can be changed using the method setPriority() of class Thread.
A program that demonstrates changing the thread priorities using the method setPriority() in Java is given as follows:
 Live Demo
public class ThreadDemo extends Thread {
   public void run() {
      System.out.println("Running...");
   }
   public static void main(String[] args) {
      ThreadDemo thread1 = new ThreadDemo();
      ThreadDemo thread2 = new ThreadDemo();
      ThreadDemo thread3 = new ThreadDemo();
      ThreadDemo thread4 = new ThreadDemo();
      ThreadDemo thread5 = new ThreadDemo();
      System.out.println("Default thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Default thread priority of Thread 2: " + thread2.getPriority());
      System.out.println("Default thread priority of Thread 3: " + thread3.getPriority());
      System.out.println("Default thread priority of Thread 4: " + thread4.getPriority());
      System.out.println("Default thread priority of Thread 5: " + thread5.getPriority());
      System.out.println("\nChanging the default thread priority using the setPriority() method");
      thread1.setPriority(7);
      thread2.setPriority(3);
      thread3.setPriority(9);
      thread4.setPriority(2);
      thread5.setPriority(8);
      System.out.println("\nChanged thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Changed thread priority of Thread 2: " + thread2.getPriority());
      System.out.println("Changed thread priority of Thread 3: " + thread3.getPriority());
      System.out.println("Changed thread priority of Thread 4: " + thread4.getPriority());
      System.out.println("Changed thread priority of Thread 5: " + thread5.getPriority());
      System.out.println("\n" + Thread.currentThread().getName());
      System.out.println("\nDefault thread priority of Main Thread: " + Thread.currentThread().getPriority());
      Thread.currentThread().setPriority(10);
      System.out.println("Changed thread priority of Main Thread: " + Thread.currentThread().getPriority());
   }
}
Default thread priority of Thread 1: 5
Default thread priority of Thread 2: 5
Default thread priority of Thread 3: 5
Default thread priority of Thread 4: 5
Default thread priority of Thread 5: 5
Changing the default thread priority using the setPriority() method
Changed thread priority of Thread 1: 7
Changed thread priority of Thread 2: 3
Changed thread priority of Thread 3: 9
Changed thread priority of Thread 4: 2
Changed thread priority of Thread 5: 8
main
Default thread priority of Main Thread: 5
Changed thread priority of Main Thread: 10
Java private Keyword

❮ Java Keywords

A class with private attributes:
public class Main {
  private String fname = "John";
  private String lname = "Doe";
  private String email = "john@doe.com";
  private int age = 24;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);
    System.out.println("Email: " + myObj.email);
    System.out.println("Age: " + myObj.age);
  }
}


Try it Yourself »

The private keyword is an access modifier used for attributes, methods and constructors, making them only accessible within the declared class.
Read more about modifiers in our Java Modifiers Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to find the sixth cell (second row and third column ) of a 3x3 table in jQuery ? - GeeksforGeeks

18 Apr, 2021
In this article, we will see how to get the sixth cell of a 3×3 table in jQuery. To find the nth-child of an element, we can use the nth-child selector of jQuery. 
Approach: Sixth cell of a 3×3 table can be found using the following jQuery call:
$('#table1 tr:nth-child(2) td:nth-child(3)').text();
If the table has column headers, the sixth cell can be found using the following call.
$('#table1 tr:nth-child(3) td:nth-child(3)').text();
HTML code: Please note that the nth-child selector’s index is 1 based.
HTML
<!DOCTYPE html><html>  <head>    <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js">    </script>      <script type="text/javascript">        $(document).ready(function () {            $('#btnGetValue').click(function () {                $('#value').text($('#table1 tr:nth-child(3) td:nth-child(3)').text());            });        });    </script></head>  <body style="text-align:center">    <table id="table1" style=        "width:100%" border="1">        <tr>            <th>                Header1            </th>            <th>                Header2            </th>            <th>                Header3            </th>        </tr>        <tr>            <td>Cell 1</td>            <td>Cell 2</td>            <td>Cell 3</td>        </tr>        <tr>            <td>Cell 4</td>            <td>Cell 5</td>            <td>Cell 6</td>        </tr>    </table>    <br>      <input type="button"         value="Get 6th Cell's value"         id="btnGetValue" />              <span id="value"></span></body>  </html>
Output: We see the following web page.
Before Click:
After Click:
You see the sixth cell’s value next to the button (highlighted in red rectangle)
After click output
HTML-Tags
jQuery-Methods
jQuery-Questions
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
How to get the value in an input text box using jQuery ?
Difference Between JavaScript and jQuery
QR Code Generator using HTML, CSS and jQuery
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
POSIX Thread Libraries

Pthreads refers to the POSIX standard (IEEE 1003.1c) defining an API for thread creation and synchronization. This defines specification for thread behavior, not an implementation. The specification can be implemented by OS designers in any way they wish. So many systems implement the Pthreads specification; most are UNIX-type systems, including Linux, Mac OS X, and Solaris. Although Windows doesn’t support Pthreads natively, some third-party implementations for Windows are available. The C program shown in Figure 4.9 demonstrates the basic Pthreads API for constructing a multithreaded program that calculates the summation of a nonnegative integer in a separate thread. Separate threads begin execution in a specified function in a Pthreads program. In below program, this is the runner() function. At the time when this program begins, a single thread of control begins in main().Then main() creates a second thread that begins control in the runner() function, after some initialization,. Both threads share the global data sum.
#include<pthread.h>
#include<stdio.h>
int sum;
/* this sum data is shared by the thread(s) */
/* threads call this function */
void *runner(void *param);
int main(int argc, char *argv[]){
   pthread t tid; /* the thread identifier */
   /* set of thread attributes */
   pthread attr t attr;
   if (argc != 2){
      fprintf(stderr,"usage: a.out \n");
      return -1;
   }
   if (atoi(argv[1]) < 0){
      fprintf(stderr,"%d must be >= 0\n",atoi(argv[1]));
      return -1;
   }
   /* get the default attributes */
   pthread attr init(&attr); /* create the thread */
   pthread create(&tid,&attr,runner,argv[1]);
   /* wait for the thread to exit */
   pthread join(tid,NULL);
   printf("sum = %d\n",sum);
}
/* The thread will now begin control in this function */
void *runner(void *param){
   int i, upper = atoi(param);
   sum = 0;
   for (i = 1; i <= upper; i++)
      sum += i;
   pthread exit(0);
}
Multithreaded C program using the Pthreads API.
Python – Merge two Pandas DataFrame

To merge two Pandas DataFrame, use the merge() function. Just set both the DataFrames as a parameter of the merge() function.
At first, let us import the required library with alias “pd” −
import pandas as pd
Create the 1st DataFrame −
# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)
Next, create the 2nd DataFrame −
# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)
Now, merge both the DataFrames using the merge() function −
mergedRes = pd.merge(dataFrame1, dataFrame2)

Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],"Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Mercedes', 'Jaguar'],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print"\nDataFrame2 ...\n",dataFrame2

# merge DataFrames
mergedRes = pd.merge(dataFrame1, dataFrame2)
print"\nMerged data frame...\n", mergedRes
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW     100
1    Lexus     150
2     Audi     110
3  Mustang      80
4  Bentley     110
5   Jaguar      90

DataFrame2 ...
        Car   Reg_Price
0       BMW        7000
1     Lexus        1500
2      Audi        5000
3   Mustang        8000
4  Mercedes        9000
5    Jaguar        6000

Merged data frame...
       Car   Units   Reg_Price
0      BMW     100        7000
1    Lexus     150        1500
2     Audi     110        5000
3  Mustang      80        8000
4   Jaguar      90        6000
Node.js Buffer.readInt32BE() Method

13 Oct, 2021
The Buffer.readInt32BE() method is used to read 32 bit integer from a buffer object at a given offset and returns the result in Big endian.
Syntax:
buffer.readInt32BE( offset )
Parameters: This method accepts a single parameter offset which specifies the position of buffer object. It represents the number of bytes to skip before starting to read. The value of offset lies within the range 0 to buffer.length – 4. The default value is 0.
Return value: This method reads an signed 32-bit integer at the specified offset in Big endian.
Example 1:
// Node.js program to demonstrate the// buffer.readInt32BE() method const buff = Buffer.from([1, 2, 3, 4, 5]);  console.log(buff.readInt32BE(0));  console.log(buff.readInt32BE(1));
Output:
16909060
33752069

Example 2:
// Node.js program to demonstrate the// buffer.readInt32BE() method const buff = Buffer.from([1, 2, 3, 4, 5]);  console.log(buff.readInt32BE(4))
Output:
buffer.js:831
    throw new RangeError('Index out of range');
    ^

RangeError: Index out of range
    at checkOffset (buffer.js:831:11)
    at Buffer.readInt32BE (buffer.js:996:5)
    at Object. (/home/cg/root/8545664/main.js:8:18)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)

The above example shows the error because its parameters are not in the valid range.
Note:
To get the values in Little endian format you can use Buffer.readInt32LE() method.
The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_readint32be_offset
Node.js-Buffer-module
Picked
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Database Operations in HIVE Using CLOUDERA – VMWARE Work Station

17 Jan, 2021
We are going to create a database and create a table in our database. And will cover Database operations in HIVE Using CLOUDERA – VMWARE Work Station. Let’s discuss one by one.
Introduction:
Hive is an ETL tool that provides an SQL-like interface between the user and the Hadoop distributed file system which integrates Hadoop.
It is built on top of Hadoop.
It facilitates reading, writing, and handling wide datasets that stored in distributed storage and queried by Structure Query Language (SQL) syntax.
Requirements:
Need to install Cloudera – vmware workstation.
Link to download for windows –https://www.cloudera.com/downloads/cdh.html
Cloudera:
Cloudera enables you to deploy and manage Apache Hadoop, manipulate and analyze your data, and keep that data secure and protected.
Step 1: On your desktop VMware workstation is available. Open that.
Step 2: Now you will get an interface. Click on open a virtual device.
Step 3: Select path – In this step, you have to select the path and file where you have downloaded the file.
Step 4: Now your virtual environment is creating.
Step 5: You can view your virtual machine details in this path.
Step 6: Now open the terminal to get started with hive commands.
Step 7: Now type hive in the terminal. It will give output as follows.
[cloudera@quickstart ~]$ hive
2020-12-09 20:59:24,314 WARN  [main] mapreduce.TableMapReduceUtil: 
The hbase-prefix-tree module jar containing PrefixTreeCodec is not present.  Continuing without it.
Logging initialized using configuration in file:/etc/hive/conf.dist/hive-log4j.properties
WARNING: Hive CLI is deprecated and migration to Beeline is recommended.
hive>  
Step 8: Now, you are all set and ready to start typing your hive commands.
1. Create a database
Syntax:
create database database_name;
Example:
create database geeksportal;
Output:
2. Creating a table
Syntax:
create database.tablename(columns);
Example:
create table geeksportal.geekdata(id int,name string);
Here id and string are the two columns.
Output :
3. Display Database
Syntax:
show databases;
Output: Display the databases created.
4. Describe Database
Syntax:
describe database database_name;
Example:
describe  database geeksportal;
Output: Display the HDFS path of a particular database.
Apache-Hive
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Table in Hive?
What is Schema On Read and Schema On Write in Hadoop?
What is Hadoop Streaming?
MapReduce - Understanding With Real-Life Example
Apache Hive
Hadoop - HDFS (Hadoop Distributed File System)
Hive - Alter Table
Import and Export Data using SQOOP
Difference Between Hadoop and Apache Spark
Difference Between Hadoop 2.x vs Hadoop 3.x
Extracting email addresses using regular expressions in Python

29 Dec, 2020
Let suppose a situation in which you have to read some specific data like phone numbers, email addresses, dates, a collection of words etc. How can you do this in a very efficient manner?The Best way to do this by Regular Expression.
Let take an example in which we have to find out only email from the given input by Regular Expression.Examples:
Input  : Hello shubhamg199630@gmail.com Rohit neeraj@gmail.com
Output : shubhamg199630@gmail.com neeraj@gmail.com
Here we have only selected email from the given input string.

Input : My 2 favourite numbers are 7 and 10
Output :2 7 10
Here we have selected only digits.

Regular Expression–Regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.So we can say that the task of searching and extracting is so common that Python has a very powerful library called regular expressions that handles many of these tasks quite elegantly.
# Python program to extract numeric digit # from A string by regular expression...  # Importing module required for regular# expressionsimport re    # Example String s = 'My 2 favourite numbers are 7 and 10'  # find all function to select all digit from 0   # to 9 [0-9] for numeric Letter in the String# + for repeats a character one or more timeslst = re.findall('[0-9]+', s)      # Printing of Listprint(lst)
['2', '7', '10']

# Python program to extract emails From # the String By Regular Expression.   # Importing module required for regular # expressions import re   # Example string s = """Hello from shubhamg199630@gmail.com        to priya@yahoo.com about the meeting @2PM"""  # \S matches any non-whitespace character # @ for as in the Email # + for Repeats a character one or more times lst = re.findall('\S+@\S+', s)       # Printing of List print(lst) 
['shubhamg199630@gmail.com', 'priya@yahoo.com']

For more details:
Regular Expression in Python with Examples | Set 1
Regular Expressions in Python | Set 2 (Search, Match and Find All)
Python Docs for Regular Expression
Python Regex-programs
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Deque in Python
Defaultdict in Python
Stack in Python
Queue in Python
sum() function in Python
Different ways to create Pandas Dataframe
Python | Sort alternate numeric and alphabet list

11 May, 2020
Sometimes, while performing sorting in list, we have a problem in which we need to perform particular type of sorting in which we need to sort in alternate ways in which we have numerics and alphabets sorted in order. Lets discuss certain ways in which this task can be performed.
Method #1 : Using isalpha() + isnumeric() + zip_longest()The combination of above methods can be used to perform this task. In this, we separate the numeric and alphabets and then perform a sort on them separately and join using zip_longest().
# Python3 code to demonstrate # Sort alternate numeric and alphabet list# using isalpha() + isnumeric() + zip_longest()from itertools import zip_longest  # Initializing listtest_list = ['3', 'B', '2', 'A', 'C', '1']  # printing original listprint("The original list is : " + str(test_list))  # Sort alternate numeric and alphabet list# using isalpha() + isnumeric() + zip_longest()num_list = sorted(filter(str.isnumeric, test_list),                        key = lambda sub: int(sub))  chr_list = sorted(filter(str.isalpha, test_list))res = [ele for sub in zip_longest(num_list, chr_list)                              for ele in sub if ele]      # printing result print ("List after performing sorting : " + str(res))
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']

 
Method #2 : Using sorted() + key + lambda + isnumeric()The combination of above methods can be used to perform this task. In this, we perform the sorting in alternate manner using ord() and lambda function, testing using isnumeric().
# Python3 code to demonstrate # Sort alternate numeric and alphabet list# using sorted() + key + lambda + isnumeric()from itertools import zip_longest  # Initializing listtest_list = ['3', 'B', '2', 'A', 'C', '1']  # printing original listprint("The original list is : " + str(test_list))  # Sort alternate numeric and alphabet list# using sorted() + key + lambda + isnumeric()res = sorted(test_list, key = lambda ele : (int(ele), 0)      if ele.isnumeric()      else ((ord(ele) - 64) % 26, 1))  # printing result print ("List after performing sorting : " + str(res))
The original list is : ['3', 'B', '2', 'A', 'C', '1']
List after performing sorting : ['1', 'A', '2', 'B', '3', 'C']

Python list-programs
Python-sort
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers