code-rag-bench/online-tutorials huggingface dataset:
RANDOM Shell Variable in Linux with Examples

10 Nov, 2020
RANDOM is a shell variable that is used to generate random integers in Linux. It is an internal bash command that returns a pseudo-random 16-bit integer in the range 0 – 32767. It returns a different integer at each invocation. To enhance the randomization process, the random variable can be seeded with an initial value which can be the time in epoch, the process ID of the current shell, etc.
Syntax to use time in epoch to initialize the generator:
RANDOM=$(date +%s)

Syntax to use process ID of the current shell to initialize the generator:
RANDOM=$$ #PID of shell is stored in $$ variable

Generating  random integer
Random integer can be generated by directly reading from the random variable by using the echo command. It will display a random integer in range 0 to 32767.
echo $RANDOM

Generating ‘n’ random integers
You may use loops to generate more than one random number using the RANDOM shell variable. The following code will generate 5 random values in the range from 0 to 32767.
RANDOM=$$
for i in `seq 5`
do
        echo $RANDOM
done

Note: Replace 5 with the number of random values of your choice.
Generating random integer when the upper limit is given
Consider that you want to generate a random integer within Y (where Y is not included). Format to achieve this is:
R=$(($RANDOM%Y))

To include the upper limit Y, the divisor of the modulo operation will be Y+1. The format is:
R=$(($RANDOM%Y+1))

Example:
echo $(($RANDOM%10)) #This will display a random integer between 0 and 9.
echo $(($RANDOM%11)) #This will display a random integer between 0 and 10.

When the input is taken from the user in a shell script from the command line to generate the integer, then the following code can be used:
Y=$1
div=$((Y+1))
RANDOM=$$
R=$(($RANDOM%$div))
echo $R

Y stores the upper limit and echo $R displays the random integer. The output is:
Generating random integer when both upper and lower limit is given
Consider that you want to generate a random integer between X and Y where X is the lower limit (X≠0) and Y is the upper limit. Format to achieve this is:
RANGE=$((Y-X+1))
R=$(($(($RANDOM%$RANGE))+X))

Example:
echo "lower limit:"
read X
echo "upper limit:"
read Y
RANGE=$((Y-X+1))
RANDOM=$$
R=$(($(($RANDOM%$RANGE))+X))
echo "The random integer is $R"

The output is:
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery - hover( over, out ) Method

The hover( over, out ) method simulates hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.
Here is the simple syntax to use this method −
selector.hover( over, out )

Here is the description of all the parameters used by this method −
over − The callback function to fire when the mouse is moved over a matched element.
over − The callback function to fire when the mouse is moved over a matched element.
out − The callback function to fire when the mouse is moved off of a matched element.
out − The callback function to fire when the mouse is moved off of a matched element.
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {

            $('div').hover(
				
               function () {
                  $(this).css({"background-color":"red"});
               }, 
				
               function () {
                  $(this).css({"background-color":"blue"});
               }
            );
				
         });
      </script>
		
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
	
   <body>
      <p>Move mouse on any square below to see the result:</p>
		
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:blue;"></div>
   </body>
</html>
This will produce following result −
Move mouse on any square below to see the result −
Add to Array-Form of Integer in Python

Suppose we have a number in array form. So if the number is say 534, then it is stored like [5, 3, 4]. We have to add another value k with the array form of the number. So the final number will be another array of digits.
To solve this, we will follow these steps −
Take each number and make them string, then concatenate the string
convert the string into integer, then add the number
Then convert it into string again, and make an array by taking each digit form the string.
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def addToArrayForm(self, A, K):
      num_A = int(''.join(str(i) for i in A))
      res = list(str(num_A+K))
      res = list(map(int,res))
      return res
ob1 = Solution()
print(ob1.addToArrayForm([5,3,4], 78))
[5,3,4]
78
[6,1,2]
Groovy - Lists contains()

Returns true if this List contains the specified value.
boolean contains(Object value)

Value − The value to find in the list.
True or false depending on if the value is present in the list.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      def lst = [11, 12, 13, 14]; 
		
      println(lst.contains(12)); 
      println(lst.contains(18));
   }
}
When we run the above program, we will get the following result −
true 
false


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
LocalDate plusWeeks() method in Java with Examples - GeeksforGeeks

19 Jun, 2019
The plusWeeks() method of LocalDate class in Java is used to add the number of specified week in this LocalDate and return a copy of LocalDate.For example, 2018-12-24 plus one week would result in 2018-12-31. This instance is immutable and unaffected by this method call.
Syntax:
public LocalDate plusWeeks(long weeksToAdd)

Parameters: This method accepts a single parameter weeksToAdd which represents the weeks to add, may be negative.
Return value: This method returns a LocalDate based on this date with the weeks added, not null.
Exception: This method throws DateTimeException if the result exceeds the supported date range.
Below programs illustrate the plusWeeks() method:
Program 1:
// Java program to demonstrate// LocalDate.plusWeeks() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDate object        LocalDate date            = LocalDate.parse("2018-12-26");          // print instance        System.out.println("LocalDate before"                           + " adding weeks: " + date);          // add 5 weeks        LocalDate returnvalue            = date.plusWeeks(5);          // print result        System.out.println("LocalDate after "                           + " adding weeks: " + returnvalue);    }}
Output:
LocalDate before adding weeks: 2018-12-26
LocalDate after  adding weeks: 2019-01-30

Program 2:
// Java program to demonstrate// LocalDate.plusWeeks() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalDate object        LocalDate date            = LocalDate.parse("2018-12-24");          // print instance        System.out.println("LocalDate before"                           + " adding weeks: " + date);          // add -3 weeks        LocalDate returnvalue            = date.plusWeeks(-3);          // print result        System.out.println("LocalDate after "                           + " adding weeks: " + returnvalue);    }}
LocalDate before adding weeks: 2018-12-24
LocalDate after  adding weeks: 2018-12-03

Reference :https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#plusWeeks(long)
nidhi_biet
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Different ways of Reading a text file in Java
Constructors in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Introduction to Java
How to remove an element from ArrayList in Java?
TuriCreate library in Python - GeeksforGeeks

16 Jul, 2020
TuriCreate(Machine Learning Python Library):Custom Machine Learning models can be made using Turi create very easily. You don’t have to be an expert in Machine Learning to use Turi create and it helps in building an add recommendations, object detection, image classification, image similarity or activity classification systems easily.
Advantages of TuriCreate:
It is easy to use.
Flexible to use.
Ready to deploy model to ios, MacOs, watchOs and tvOs apps.
It one of the crazy features is that it can read the .csv(Comma Separated Values) and use the Machine Learning Model.
Supported Platform for TuriCreate:
macOS 10.12+
Linux (with glibc 2.12+)
Windows 10 (via WSL)=It is little tricky to install it on windows but you can install via WSL(Windows Subsystem Linux) and if does have the same error then you have to upgrade pip by using this command:pip3 install –upgrade pipSystem RequirementsPython 2.7, 3.5 or above (ex. 3.7, 3.8)Python 3.7 macOS only+x86_64 architectureUsing a Conda Environment or virtualenv is highly recommended so that we can have different Python Interpreter on the same Machine.
pip3 install –upgrade pip
System Requirements
Python 2.7, 3.5 or above (ex. 3.7, 3.8)
Python 3.7 macOS only+
x86_64 architecture
Using a Conda Environment or virtualenv is highly recommended so that we can have different Python Interpreter on the same Machine.
Turicreate uses SFrames for data handling:SFrames means scalable data frame. It is a tabular, column-mutable data frame object that can scale to big data. It’s one of the advantages is that is mutable.
Code: How to use SFrame for Loading the data:
import turicreate as tcfrom turicreate import SFrame  # Let's declare a variable for loading the datadata = tc.SFrame("data.csv")  # Here data.csv is a file stored in your system# with name = data
Data Structure of TuriCreate:
SFrame
SGraph
SArray
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree Introduction with example
Python | Decision tree implementation
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Evaluating a string as a mathematical expression in JavaScript

We are required to write a JavaScript function that takes in a stringified mathematical equation. The function should return the result of the equation provided to the function.
For example: If the equation is −
const str = '1+23+4+5-30';
Then the output should be 3
The code for this will be −
const str = '1+23+4+5-30';
const compute = (str = '') => {
   let total = 0;
   str = str.match(/[+\−]*(\.\d+|\d+(\.\d+)?)/g) || [];
   while (str.length) {
      total += parseFloat(str.shift());
   };
   return total;
};
console.log(compute(str));
And the output in the console will be −
3
DateTime.ToShortTimeString() Method in C#

The DateTime.ToShortTimeString() method in C# is used to convert the value of the current DateTime object to its equivalent short time string representation.
Following is the syntax −
public string ToShortTimeString ();
Let us now see an example to implement the DateTime.ToShortTimeString() method −
using System;
using System.Globalization;
public class Demo {
   public static void Main() {
      DateTime d = DateTime.Now;
      Console.WriteLine("Date = {0}", d);
      Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name);
      var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
      string str = d.ToShortTimeString();
      Console.WriteLine("Short time string = {0}", pattern.ShortTimePattern);
      Console.WriteLine("Short time string representation = {0}", str);
   }
}
This will produce the following output −
Date = 10/16/2019 8:59:23 AM
Current culture = en-US
Short time string = h:mm tt
Short time string representation = 8:59 AM
Let us now see another example to implement the DateTime.ToShortTimeString() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
      Console.WriteLine("Date = {0}", d);
      string str = d.ToShortTimeString();
      Console.WriteLine("Short time string representation = {0}", str);
   }
}
This will produce the following output −
Date = 11/11/2019 7:11:25 AM
Short time string representation = 7:11 AM
Java program to merge two files into a third file

Following is the Java program to merge two files into a third file −
import java.io.*;
public class Demo {
   public static void main(String[] args) throws IOException {
      PrintWriter my_pw = new PrintWriter("path to third .txt file");
      BufferedReader my_br = new BufferedReader(new FileReader("path to first .txt file"));
      String my_line = my_br.readLine();
      while (my_line != null) {
         my_pw.println(my_line);
         my_line = my_br.readLine();
      }
      my_br = new BufferedReader(new FileReader("path to second .txt file"));
      my_line = my_br.readLine();
      while(my_line != null) {
         my_pw.println(my_line);
         my_line = my_br.readLine();
      }
      my_pw.flush();
      my_br.close();
      my_pw.close();
      System.out.println("The first two files have been merged into the third file successfully.");
   }
}
The first two files have been merged into the third file successfully.
A class named Demo contains the main function. Here an instance of the PrintWriter class and BufferedReader is generated. Every line in the two files is read, until it reaches null. It is then added to the third file, and the class instances are flushed and closed.
The mutable storage class in C++

The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const. You cannot use the mutable specifier with names declared as static or const, or reference members.
In the following example −
class A
{
   public:
   A() : x(4), y(5) { };
   mutable int x;
   int y;
};

int main()
{
   const A var2;
   var2.x = 345;
   // var2.y = 2345;
}
the compiler would not allow the assignment var2.y = 2345 because var2 has been declared as const. The compiler will allow the assignment var2.x = 345 because A::x has been declared as mutable.
Arduino - Trigonometric Functions

You need to use Trigonometry practically like calculating the distance for moving object or angular speed. Arduino provides traditional trigonometric functions (sin, cos, tan, asin, acos, atan) that can be summarized by writing their prototypes. Math.h contains the trigonometry function's prototype.
double sin(double x); //returns sine of x radians
double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x

double sine = sin(2); // approximately 0.90929737091
double cosine = cos(2); // approximately -0.41614685058
double tangent = tan(2); // approximately -2.18503975868

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Relational Operators in C

The following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20 then −
Try the following example to understand all the relational operators available in C −
#include <stdio.h>

main() {

   int a = 21;
   int b = 10;
   int c ;

   if( a == b ) {
      printf("Line 1 - a is equal to b\n" );
   } else {
      printf("Line 1 - a is not equal to b\n" );
   }
	
   if ( a < b ) {
      printf("Line 2 - a is less than b\n" );
   } else {
      printf("Line 2 - a is not less than b\n" );
   }
	
   if ( a > b ) {
      printf("Line 3 - a is greater than b\n" );
   } else {
      printf("Line 3 - a is not greater than b\n" );
   }
   
   /* Lets change value of a and b */
   a = 5;
   b = 20;
	
   if ( a <= b ) {
      printf("Line 4 - a is either less than or equal to  b\n" );
   }
	
   if ( b >= a ) {
      printf("Line 5 - b is either greater than  or equal to b\n" );
   }
}
When you compile and execute the above program, it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to  b
Line 5 - b is either greater than  or equal to b

 Print
 Add Notes
 Bookmark this page
C++ Program to Implement Expression Tree Algorithm

An expression tree is basically a binary which is used to represent expressions. In expression tree, internal nodes correspond to operators and each leaf node corresponds to an operand. Here is a C++ Program to implement the Expression Tree Algorithm which takes the postfix expression as an input and generates the corresponding expression tree traversed in inorder.
Begin
   function construct_expression_tree():
      Flag = 1 when it is operand.
      Flag = -1 when it is operator.
      S = suffix[0] means read the first operand from the expression.
   For i = 0 and until s != 0
      Check symbol is operand or operator.
      Call function void inorder() for inorder traversal.
      Print the results.
      Increment i
End.
#include <iostream>
using namespace std;

struct n//node declaration {
   char d;
   n *l;
   n *r;
};
char pf[50];
int top = -1;
n *a[50];
int r(char inputch)//check the symbol whether it is an operator or an operand. {
   if (inputch == '+' || inputch == '-' || inputch == '*' || inputch == '/')
      return (-1);
   else if (inputch >= 'A' || inputch <= 'Z')
      return (1);
   else if (inputch >= 'a' || inputch <= 'z')
      return (1);
   else
      return (-100);
}
void push(n *tree)//push elements in stack {
   top++;
   a[top] = tree;
}
n *pop() {
   top--;
   return (a[top + 1]);
}
void construct_expression_tree(char *suffix) {
   char s;
   n *newl, *p1, *p2;
   int flag;
   s = suffix[0];
   for (int i = 1; s!= 0; i++) {
      flag = r(s);
      if (flag == 1) {
         newl = new n;
         newl->d = s;
         newl->l = NULL;
         newl->r = NULL;
         push(newl);
      } else {
         p1 = pop();
         p2 = pop();
         newl = new n;
         newl->d = s;
         newl->l = p2;
         newl->r = p1;
         push(newl);
      }
      s = suffix[i];
   }
}

void inOrder(n *tree)//perform inorder traversal {
   if (tree != NULL) {
      inOrder(tree->l);
      cout << tree->d;
      inOrder(tree->r);
   }
}

int main(int argc, char **argv) {
   cout << "Enter Postfix Expression : ";
   cin >>pf;
   construct_expression_tree(pf);
   cout << "\nInfix Expression : ";
   inOrder(a[0]);
   return 0;
}
Enter Postfix Expression : 762*+6+
Infix Expression : 7+6*2+6
How to replace characters except last with the specified mask character in JavaScript ? - GeeksforGeeks

17 Jun, 2021
In this article, we have given a number and the task is to replace the characters except for the last character with a specified mask character in JavaScript.
Example: Let’s take a number 12345678 and the masking character is * and the number of the last element that we have to skip is 2 In the below image shows that we skip the last two-element, and we mask another character with ‘*’. 
Approach: We will make one function that can mask the character of the string except for the last element we will give our number as a string.
In this function we take three-argument, first one is a string which we want to mask, the second argument will specify mask character, and third is number of character that you want to skip
We use some inbuilt JavaScript function slice to slice our given string here we write slice(0,-n) where -n will skip the last n character of the string.
Then we use replace function to replace the character with a specified mask. Replace all characters we use regex /./g where ‘.’ will match any character and g is tens for globally.
Now we have to add the remaining character into the masking string, so we again use the slice function to get the remaining n character and add it into the masking string.
 
Example:
Javascript
<script>    // Function for masking the character     function MaskCharacter(str, mask, n = 1) {          // Slice the string and replace with        // mask then add remaining string        return ('' + str).slice(0, -n)            .replace(/./g, mask)            + ('' + str).slice(-n);    }      // Number that we want to mask     var num = 12345678;      // Convert number into string    var str = num.toString();      // Call function without giving value of n    console.log(MaskCharacter(str, '#'));      // Call function with value of n    console.log(MaskCharacter(str, '#', 2));</script>
Output:
javascript-functions
JavaScript-Questions
JavaScript-RegExp
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to generate large random numbers in Java?

For large random numbers, use BigInteger type in Java. At first, create a Random object −
Random randNum = new Random();
Now, declare a byte array and generate random bytes −
byte[] b = new byte[max];
randNum.nextBytes(b);
Now, generate a large random number with BigInteger type −
BigInteger bigInt = new BigInteger(b);
 Live Demo
import java.math.BigInteger;
import java.util.Random;
public class Demo {
   public static void main(String... a) {
      int max = 10;
      Random randNum = new Random();
      byte[] b = new byte[max];
      randNum.nextBytes(b);
      // BigInteger type
      BigInteger bigInt = new BigInteger(b);
      System.out.println("Very large random number = "+bigInt);
   }
}
Very large random number = 283258678185163472552410
Remove all duplicates from a given string in Python

To remove all duplicates from a string in python, we need to first split the string by spaces so that we have each word in an array. Then there are multiple ways to remove duplicates.
We can remove duplicates by first converting all words to lowercase, then sorting them and finally picking only the unique ones. For example,
sent = "Hi my name is John Doe John Doe is my name"

# Seperate out each word
words = sent.split(" ")

# Convert all words to lowercase
words = map(lambda x:x.lower(), words)

# Sort the words in order
words.sort()
unique = []
total_words = len(words)
i = 0

while i < (total_words - 1):
while i < total_words and words[i] == words[i + 1]:
i += 1
unique.append(words[i])
i += 1

print(unique)
This will give the output −
['doe', 'hi', 'john', 'is', 'my']
is_enabled() element method - Selenium Python - GeeksforGeeks

27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use is_enabled method in Selenium. is_enabled method is used to check if element is enabled or not. It returns a boolean value True or False.
element.is_enabled()
Example –
<a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a>
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_id("link")
Now one can check if this element is being displayed with
text_length = element.is_enabled()
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we gcheck visibility of courses tab in navigation bar at geeksforgeeks.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # print valueprint(element.is_enabled())
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Fortran - Stop Statement

If you wish execution of your program to cease, you can insert a stop statement.
program stop_example     
implicit none

   integer :: i     
   do i = 1, 20          
   
      if (i == 5) then 
         stop          
      end if         
      
      print*, i      
   end do  
   
end program stop_example
When the above code is compiled and executed, it produces the following result −
1
2
3
4

 Print
 Add Notes
 Bookmark this page
C# program to display the next day

To display the next day, use the AddDays() method and a value +1 to get the next day.
Firstly, use the following to get the current day −
DateTime.Today
Now, add 1 to the AddDays() method to get the next day −
DateTime.Today.AddDays(1)
The following is the code −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
   public static void Main() {
      Console.WriteLine("Today = {0}", DateTime.Today);
      Console.WriteLine("Previous Day = {0}", DateTime.Today.AddDays(-1));
      Console.WriteLine("Next Day (Tomorrow) = {0}", DateTime.Today.AddDays(1));
   }
}
Today = 9/4/2018 12:00:00 AM
Previous Day = 9/3/2018 12:00:00 AM
Next Day (Tomorrow) = 9/5/2018 12:00:00 AM
Statistics - Reliability Coefficient

A measure of the accuracy of a test or measuring instrument obtained by measuring the same individuals twice and computing the correlation of the two sets of measures.
Reliability Coefficient is defined and given by the following function:
Reliability Coefficient, RC=(N(N−1))×((Total Variance −Sum of Variance)TotalVariance)
Where − 
N = Number of Tasks
N = Number of Tasks
Problem Statement:
An undertaking was experienced with three Persons (P) and they are assigned with three distinct Tasks (T). Discover the Reliability Coefficient?
P0-T0 = 10 
P1-T0 = 20 
P0-T1 = 30 
P1-T1 = 40 
P0-T2 = 50 
P1-T2 = 60 

Solution:
Given, Number of Students (P) = 3 Number of Tasks (N) = 3. To Find, Reliability Coefficient, follow the steps as following:
Give us a chance to first figure the average score of the persons and their tasks
The average score of Task (T0) = 10 + 20/2 = 15 
The average score of Task (T1) = 30 + 40/2 = 35 
The average score of Task (T2) = 50 + 60/2 = 55 

Next, figure the variance for:
Variance of P0-T0 and P1-T0: 
Variance = square (10-15) + square (20-15)/2 = 25
Variance of P0-T1 and P1-T1: 
Variance = square (30-35) + square (40-35)/2 = 25
Variance of P0-T2 and P1-T2: 
Variance = square (50-55) + square (50-55)/2 = 25 

Presently, figure the individual variance of P0-T0 and P1-T0, P0-T1 and P1-T1, P0-T2 and P1-T2. To ascertain the individual variance value, we ought to include all the above computed change values.
Total of Individual Variance = 25+25+25=75 
Compute the Total change
Variance= square ((P0-T0) 
 - normal score of Person 0) 
 = square (10-15) = 25
Variance= square ((P1-T0) 
 - normal score of Person 0) 
 = square (20-15) = 25 
Variance= square ((P0-T1) 
 - normal score of Person 1) 
 = square (30-35) = 25 
Variance= square ((P1-T1) 
 - normal score of Person 1) 
 = square (40-35) = 25
Variance= square ((P0-T2) 
 - normal score of Person 2) 
 = square (50-55) = 25 
Variance= square ((P1-T2) 
- normal score of Person 2) 
 = square (60-55) = 25 

Now, include every one of the qualities and figure the aggregate change
Total Variance= 25+25+25+25+25+25 = 150  
At last, substitute the qualities in the underneath offered equation to discover

    40 Lectures 
     3.5 hours 

 Madhu Bhatia

    40 Lectures 
     2 hours 

 Megha Aggarwal

    66 Lectures 
     1.5 hours 

 Mike West

    22 Lectures 
     1 hours 

 Mike West

    60 Lectures 
     12 hours 

 Michael Miller

    65 Lectures 
     5 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Ruby | Hash each_pair() function - GeeksforGeeks

07 Jan, 2020
Hash#each_pair() is a Hash class method which finds the nested value which calls block once for each pair in hash by passing the key_value pair as parameters.
Syntax: Hash.each_pair()
Parameter: Hash values
Return: calls block once for key_value pair in hash with key_value pair as parameter otherwise Enumerator if no argument is passed.
Example #1 :
# Ruby code for Hash.each_pair() method   # declaring Hash valuea = {a:100, b:200}   # declaring Hash valueb = {a:100, c:300, b:200}   # declaring Hash valuec = {a:100}   # each Valueputs "Hash a each_pair form : #{a.each_pair()}\n\n"   puts "Hash b each_pair form : #{b.each_pair {|key| puts "#{key}"}}\n\n"   puts "Hash c each_pair form : #{c.each_pair {|value| puts "#{value}"}}\n\n"
Output :
Hash a each_pair form : #

[:a, 100]
[:c, 300]
[:b, 200]
Hash b each_pair form : {:a=>100, :c=>300, :b=>200}

[:a, 100]
Hash c each_pair form : {:a=>100}


Example #2 :
# Ruby code for Hash.each_pair() method   # declaring Hash valuea = { "a" => 100, "b" => 200 }   # declaring Hash valueb = {"a" => 100}   # declaring Hash valuec = {"a" => 100, "c" => 300, "b" => 200}   # each Valueputs "Hash a each_pair form : #{a.each_pair()}\n\n"   puts "Hash b each_pair form : #{b.each_pair {|key| puts "#{key}"}}\n\n"   puts "Hash c each_pair form : #{c.each_pair {|value| puts "#{value}"}}\n\n"
Output :
Hash a each_pair form : #

["a", 100]
Hash b each_pair form : {"a"=>100}

["a", 100]
["c", 300]
["b", 200]
Hash c each_pair form : {"a"=>100, "c"=>300, "b"=>200}


Ruby Hash-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array reverse() function
Method Overloading In Ruby
Instance Variables in Ruby
Global Variable in Ruby
Ruby | Array transpose() function
Ruby | Array replace() function
Ruby | Hash select() method
Ruby | Array unshift() function
Hello World in Ruby
Ruby Static Members
HTML - <img> Tag

The HTML <img> tag is used to put an image in an HTML document.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML  Tag</title>
   </head>

   <body>
      <img src = "https://www.tutorialspoint.com/images/html.gif"
         alt = "HTML Tutorial" height = "150" width = "140" />
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <img> tag also supports the following additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Infinite Steps CartPole Problem With Variable Reward | by Suraj Regmi | Towards Data Science

In the last blog post, we wrote our first reinforcement learning application — CartPole problem. We used Deep -Q-Network to train the algorithm. As we can see in the blog, the fixed reward of +1 was used for all the stable states and when the CartPole loses its balance, a reward of 0 was given. We saw at the end: when the CartPole approaches 200 steps, it tends to lose balance. We ended the blog suggesting a remark: the maximum number of steps (which we defined 200) and the fixed reward may have led to such behavior. Today, let’s not limit the number of steps and modify the reward and see how the CartPole behaves.
The CartPole problem is considered to be solved when the average reward is greater than or equal to 195.0 over 100 consecutive trials. This is considering the fixed reward of 1.0. Thanks to its definition, it makes sense to keep a fixed reward of 1.0 for every balance state and limit the maximum number of steps to 200. It delights to know that the problem was solved in the previous blog.
The CartPole problem has the following conditions for episode termination:
Pole angle is more than 12 degrees.Cart position is more than 2.4 — center of the cart reaches the edge of the display.
Pole angle is more than 12 degrees.
Cart position is more than 2.4 — center of the cart reaches the edge of the display.
Our goal here is to remove the number of steps limitation and give a variable reward to each state.
If x and θ represents cart position and pole angle respectively, we define the reward as:
reward = (1 - (x ** 2) / 11.52 - (θ ** 2) / 288)
Here, both the cart position and pole angle components are normalized to [0, 1] interval to give equal weightage to them. Let’s see the screenshot of the 2D view of the 3D graph.
We see in the graph that when the CartPole is perfectly balanced (i.e. x = 0 and θ = 0), the maximum reward is achieved (i.e. 1). With increase in the absolute values of x and θ, the reward decreases and reaches 0 when |x| = 2.4 and |θ| = 12.
Let’s inherit the CartPole environment gym class (CartPoleEnv) to our custom class, CustomCartPoleEnv, and overwrite the step method. In the step method, we write the variable reward instead of the fixed reward.
By using the above block of code, the components of TF-Agents are made and the Deep Q-Network is trained. We see that the CartPole is even more balanced and stable over a large number of steps.
Let’s see the video of how our CartPole behaves after using the variable reward.
One episode lasts 35.4 seconds on an average. Impressive, isn’t it?
Here, the reward becomes zero only when both of the expressions (pole angle and cart position) reach the extreme values. We can employ different reward function that returns zero when one of the extreme conditions is reached. I expect such a reward function to do even better. Therefore, readers are encouraged to try such a reward function and comment how the CartPole behaved. Happy RLing!
Page Rank Algorithm and Implementation using Python

The PageRank algorithm is applicable in web pages. Web page is a directed graph, we know that the two components of Directed graphsare -nodes and connections. The pages are nodes and hyperlinks are the connections, the connection between two nodes.
We can find out the importance of each page by the PageRank and it is accurate. The value of the PageRank is the probability will be between 0 and 1.
The PageRank value of individual node in a graph depends on the PageRank value of all the nodes which connect to it and those nodes are cyclically connected to the nodes whose ranking we want, we use converging iterative method for assigning values to PageRank.
import numpy as np
import scipy as sc
import pandas as pd
from fractions import Fraction
   def display_format(my_vector, my_decimal):
      return np.round((my_vector).astype(np.float), decimals=my_decimal)
      my_dp = Fraction(1,3)
      Mat = np.matrix([[0,0,1],
      [Fraction(1,2),0,0],
      [Fraction(1,2),1,0]])
      Ex = np.zeros((3,3))
      Ex[:] = my_dp
      beta = 0.7
      Al = beta * Mat + ((1-beta) * Ex)
      r = np.matrix([my_dp, my_dp, my_dp])
      r = np.transpose(r)
      previous_r = r
   for i in range(1,100):
      r = Al * r
      print (display_format(r,3))
if (previous_r==r).all():
   break
previous_r = r
print ("Final:\n", display_format(r,3))
print ("sum", np.sum(r))
[[0.333]
[0.217]
[0.45 ]]
[[0.415]
[0.217]
[0.368]]
[[0.358]
[0.245]
[0.397]]
[[0.378]
[0.225]
[0.397]]
[[0.378]
[0.232]
[0.39 ]]
[[0.373]
[0.232]
[0.395]]
[[0.376]
[0.231]
[0.393]]
[[0.375]
[0.232]
[0.393]]
[[0.375]
[0.231]
[0.394]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
[[0.375]
[0.231]
[0.393]]
Final:
[[0.375]
[0.231]
[0.393]]
sum 0.9999999999999951
What are generic methods in C#?

Generics allow you to write a class or method that can work with any data type. Declare a generic method with a type parameter −
static void Swap(ref T lhs, ref T rhs) {}
To call the above shown generic method, here is an example −
Swap(ref a, ref b);
Let us see how to create a generic method in C# −
 Live Demo
using System;
using System.Collections.Generic;

namespace Demo {
   class Program {
      static void Swap(ref T lhs, ref T rhs) {
         T temp;
         temp = lhs;
         lhs = rhs;
         rhs = temp;
      }

      static void Main(string[] args) {
         int a, b;
         char c, d;
         a = 45;
         b = 60;
         c = 'K';
         d = 'P';
         Console.WriteLine("Int values before calling swap:");
         Console.WriteLine("a = {0}, b = {1}", a, b);
         Console.WriteLine("Char values before calling swap:");
         Console.WriteLine("c = {0}, d = {1}", c, d);
         Swap(ref a, ref b);
         Swap(ref c, ref d);
         Console.WriteLine("Int values after calling swap:");
         Console.WriteLine("a = {0}, b = {1}", a, b);
         Console.WriteLine("Char values after calling swap:");
         Console.WriteLine("c = {0}, d = {1}", c, d);
         Console.ReadKey();
      }
   }
}
Int values before calling swap:
a = 45, b = 60
Char values before calling swap:
c = K, d = P
Int values after calling swap:
a = 60, b = 45
Char values after calling swap:
c = P, d = K
GETUTCDATE() Function in SQL Server - GeeksforGeeks

21 Jan, 2021
GETUTCDATE() :
This function in SQL Server is used to return the UTC date and time of the present database system in a ‘YYYY-MM-DD hh:mm:ss.mmm’ pattern.
Features :
This function is used to find the UTC date and time of the current database system.
This function comes under Date Functions.
This function doesn’t accept any parameter.
This function returns the output in ‘YYYY-MM-DD hh:mm:ss.mmm’ format.
Syntax :
GETUTCDATE()
Parameter :
This method doesn’t accept any parameter.
Returns :
It returns the UTC date and time of the current database system in a ‘YYYY-MM-DD hh:mm:ss.mmm’ format.
Example-1 :
Using the GETUTCDATE() function and getting the output.
SELECT GETUTCDATE();
Output :
2021-01-03 15:34:14.403
Here, the output will vary each time the code is compiled as this method returns the current UTC date and time.
Example-2 :
Using GETUTCDATE() as a default value in the below example and getting the output.
CREATE TABLE get_utc_date
(
   id_num        INT IDENTITY,
   message        VARCHAR(150) NOT NULL,
   generated_at DATETIME NOT NULL
   DEFAULT GETUTCDATE(),
   PRIMARY KEY(id_num)
);
INSERT INTO get_utc_date(message)
VALUES('Its the first message.');

INSERT INTO get_utc_date(message)
VALUES('get_utc_date');

SELECT
     id_num,
     message,
     generated_at
FROM
     get_utc_date;
Output :
  |id_num |  message              |   generated_at
-------------------------------------------------------------  
1 | 1     | Its the first message.| 03.01.2021 17:32:16
-------------------------------------------------------------
2 | 2     | get_utc_date          | 03.01.2021 17:32:16
Here, firstly you need to create a table then insert values into it then generate the required output using the GETUTCDATE() function as a default value.
Note: For running the above code use SQL server compiler, you can also use an online compiler.
Example-3 :
Using CONVERT() function in order to translate the output of the GETUTCDATE() function into the current date only.
SELECT CONVERT(DATE, GETUTCDATE());
Output :
2021-01-07
Here, the output may vary every time the code is compiled as it returns current date.
Example-4 :
Using CONVERT() function in order to translate the output of the GETUTCDATE() function into the current time only.
SELECT CONVERT(TIME, GETUTCDATE());
Output :
06:40:14.4700000
Here, the output may vary every time the code is compiled as it returns current time.
Application :
This function is used to return the current UTC date and time of the database system.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
How to Select Data Between Two Dates and Times in SQL Server?
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Delete Duplicate Rows
URL getPath() method in Java with Examples

31 Dec, 2018
The getPath() function is a part of URL class. The function getPath() returns the Path name of a specified URL.
Function Signature:
public String getPath()
Syntax:
url.getPath()
Parameter: This function does not require any parameterReturn Type: The function returns String Type
Below programs illustrates the use of getPath() function:
Example 1: Given a URL we will get the Path using the getPath() function.
// Java program to show the// use of the function getPath()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {            // create a URL            url = new URL(                "https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples/");              // get the  Path            String _Path = url.getPath();              // display the URL            System.out.println("URL = " + url);              // display the  Path            System.out.println(" Path= " + _Path);        }        // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples/
 Path= /url-getprotocol-method-in-java-with-examples/

Example 2: Now see how getPath() is different from getFile(). getPath() will exclude the query but getFile() will include the query
// Java program to show the// use of the function getPath()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {            // create a URL            url = new URL(                "https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol");              // get the  Path            String _Path = url.getPath();              // display the URL            System.out.println("URL = " + url);              // display the  Path            System.out.println(" Path= " + _Path);        }        // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol
 Path= /url-getprotocol-method-in-java-with-examples

Java-Functions
Java-net-package
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java