code-rag-bench/online-tutorials huggingface dataset:
How to access and convert time using the time library in Python

The time library in Python is used to obtain time in the real world and perform various tasks related to it. You can even manipulate execution time using this module.
The time module comes packaged with Python. This means you do not have to install it separately using the PIP package manager.
In order to use its various functions and methods, you must first import it.
import time
In order to print the current local time, we will be using the ctime() function.
But firstly, we must obtain the number of seconds since epoch. That is, the number of seconds since January 1st of 1970, 00:00:00.
import time
seconds = time.time()
local_time = time.ctime(seconds)
print("Local time:", local_time)
Local time: Sun Jan 31 23:50:16 2021
In the above program, we first obtain the time since epoch and then provide that as an argument to the ctime function which returns the current local time.
Sometimes you might want to slow down or delay the execution of the Python script. For example, you might want to print the numbers slowly while iterating through a for loop.
You can do this using the sleep function in the time module.
import time
for i in range (1,6):
   print(i)
   time.sleep(1)
The above program prints from 1 to 5 and waits 1 second before printing the next number.
This way, you can avoid printing the entire content at once on the output screen.
While working on the time module you will notice that you come across the sturct_time object a lot.
In order to create your own object, follow the syntax below −
time.struct_time(tm_year=2021, tm_mon=1, tm_mday=31,
   tm_hour=9, tm_min=28, tm_sec=56,
   tm_wday=6, tm_yday=31, tm_isdst=0)
Now that you know what the struct_time object is, let us start working on printing the local time.
import time
seconds = time.time()
curr_time = time.localtime(seconds)
print(curr_time)
print(“Current year −> “, curr_time.tm_year)
In the above example, we obtained the object and accessed its various arguments. You can access all the different arguments following the syntax of struct_time mentioned above to get a better idea of how things work.
Sometimes you might want to convert time in strings into a struct_time object.
import time
example = “17 July 2001”
ans = time.strptime(example, “%d %B %Y”)
print(ans)
time.struct_time(tm_year=2001, tm_mon=7, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=198, tm_isdst=−1)
You now understand the different uses and functionalities of the time module present in Python.
You’ve learnt about the struct_time object and how to use and manipulate it. And also to convert string data into struct_time object.
For more information on the time module and about its various other features, read through its official documentation at − https://docs.python.org/3/library/time.html.
Comparing float value in PHP

11 May, 2021
In PHP, the size of a floating values is platform-dependent. Due to internal representation of floating point numbers, there might be unexpected output while performing or testing floating point values for equality. For example, see the following program.
PHP
<?php // Declare valuable and initialize it$value1 = 8 - 6.4;$value2 = 1.6; // Compare the valuesif($value1 == $value2) {    echo 'True';}else {    echo 'False';} ?>
False
 
Explanation: The output of this code is False which is very unpredictable but in PHP the value1 is not exactly 1.6 i.e it is coming from the difference between 8 and 6.4 which actually turned out to be 1.599999 that is why this statement turned out to be false.
How to resolve above problem? Method 1 : For equality testing in floating point values, use the machine epsilon or we can call it smallest difference in calculation in computer systems.
Program 1:  
PHP
<?php// PHP program to compare floating values // Declare variable and initializing// it by floating value$value1 = 1.23456789;$value2 = 1.23456780;$epsilon = 0.00001; // Use absolute difference and compare valuesif(abs($value1 - $value2) < $epsilon) {    echo "True";}else {    echo "False";} ?>
True
 
Explanation: In this code use two floating point numbers value1 and value2 along with epsilon. Now take the absolute difference of values (value1 and value2) by using the predefined function named as abs(). This code will give the absolute value but the question is why we are taking the absolute values. You can see that both the values having same digits after decimal upto precision value 7. Which is very difficult for the system to analyze the comparison. 
Method 2 : We can use round function in PHP.  
PHP
<?php// PHP program to compare floating values // Declare valuable and initialize it$value1 = 8 - 6.4;$value2 = 1.6; // Use round function to round off the// floating value upto two decimal place// and then compare it.var_dump(round($value1, 2) == round($value2, 2)); ?>
bool(true)
 
surinderdawra388
PHP-basics
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Check if count of divisors is even or odd

30 Nov, 2018
Given a number “n”, find its total number of divisors are even or odd.
Examples :
Input  : n = 10      
Output : Even

Input:  n = 100
Output: Odd

Input:  n = 125
Output: Even
A naive approach would be to find all the divisors and then see if the total number of divisors is even or odd.
Time complexity for such a solution would be O(sqrt(n))
# Naive Solution to # find if count of # divisors is even# or oddimport math  # Function to count # the divisorsdef countDivisors(n) :          # Initialize count     # of divisors    count = 0      # Note that this loop     # runs till square     # root    for i in range(1, (int)(math.sqrt(n)) + 2) :        if (n % i == 0) :                          # If divisors are            # equal,increment            # count by one            # Otherwise increment            # count by 2            if( n // i == i) :                count = count + 1            else :                count = count + 2      if (count % 2 == 0) :        print("Even")    else :        print("Odd")    # Driver program to test above function */print("The count of divisor: ")countDivisors(10)  #This code is contributed by Nikita Tiwari.*/
Output :
The count of divisor: Even 
Efficient Solution:We can observe that the number of divisors is odd only in case of perfect squares. Hence the best solution would be to check if the given number is perfect square or not. If it\’s a perfect square, then the number of divisors would be odd, else it\’d be even.
# Python program for# Efficient Solution to find# find if count of divisors# is even or odd  # Python program for# Efficient Solution to find# find if count of divisors# is even or odd  def NumOfDivisor(n):    if n < 1:        return    root_n = n**0.5          # If n is a perfect square,    # then it has odd divisors    if root_n**2 == n:        print("Odd")    else:        print("Even")          # Driver code     if __name__ == '__main__':    print("The count of divisor"+        "of 10 is: ")    NumOfDivisor(10)      # This code is contributed by Yt R    
Output :
The count of divisorof 10 is: 
Even 
Please refer complete article on Check if count of divisors is even or odd for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pre-increment (or pre-decrement) With Reference to L-value in C++

22 Jun, 2022
Prerequisite: Pre-increment and post-increment in C/C++
In C++, pre-increment (or pre-decrement) can be used as l-value, but post-increment (or post-decrement) can not be used as l-value.  For example, following program prints a = 20 (++a is used as l-value) 
l-value is simply nothing but the memory location, which has an address.
CPP
// CPP program to illustrate// Pre-increment (or pre-decrement)#include <cstdio> int main(){    int a = 10;     ++a = 20; // works    printf("a = %d", a);    printf("\n");    --a = 10;    printf("a = %d", a);    return 0;}
Output:
a = 20
a = 10
Time Complexity: O(1)
The above program works whereas the following program fails in compilation with error “non-lvalue in assignment” (a++ is used as l-value) 
CPP
// CPP program to illustrate// Post-increment (or post-decrement)#include <cstdio> int main(){    int a = 10;    a++ = 20; // error    printf("a = %d", a);    return 0;}
Error:
prog.cpp: In function 'int main()':
prog.cpp:6:5: error: lvalue required as left operand of assignment
 a++ = 20; // error 
     ^
It is because ++a returns an lvalue, which is basically a reference to the variable to which we can further assign — just like an ordinary variable. It could also be assigned to a reference as follows:
int &ref = ++a; // valid
int &ref = a++; // invalid
Whereas if you recall how a++ works, it doesn’t immediately increment the value it holds. For clarity, you can think of it as getting incremented in the next statement. So what basically happens is that, a++ returns an rvalue, which is basically just a value like the value of an expression that is not stored. You can think of a++ = 20; as follows after being processed:
int a = 10;

// On compilation, a++ is replaced by the value of a which is an rvalue:
10 = 20; // Invalid

// Value of a is incremented
a = a + 1;
That should help to understand why a++ = 20; won’t work. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SangeethSudheer
sackshamsharmaintern
kanheremahesh1729
C-Operators
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
more command in Linux with Examples

14 Oct, 2019
more command is used to view the text files in the command prompt, displaying one screen at a time in case the file is large (For example log files). The more command also allows the user do scroll up and down through the page. The syntax along with options and command is as follows. Another application of more is to use it with some other command after a pipe. When the output is large, we can use more command to see output one by one.
Syntax:
more [-options] [-num] [+/pattern] [+linenum] [file_name]
[-options]: any option that you want to use in order to change the way the file is displayed. Choose any one from the followings: (-d, -l, -f, -p, -c, -s, -u)
[-num]: type the number of lines that you want to display per screen.
[+/pattern]: replace the pattern with any string that you want to find in the text file.
[+linenum]: use the line number from where you want to start displaying the text content.
[file_name]: name of the file containing the text that you want to display on the screen.
While viewing the text file use these controls:
Enter key: to scroll down line by line.Space bar: To go to the next page.b key: To go to back one page.
Options:
-d : Use this command in order to help the user to navigate. It displays “[Press space to continue, ‘q’ to quit.]” and displays “[Press ‘h’ for instructions.]” when wrong key is pressed.Example:more -d sample.txt
Example:
more -d sample.txt
-f : This option does not wrap the long lines and displays them as such.Example:more -f sample.txt
Example:
more -f sample.txt
-p : This option clears the screen and then displays the text.Example:more -p sample.txt
Example:
more -p sample.txt
-c : This command is used to display the pages on the same area by overlapping the previously displayed text.Example:more -c sample.txt
Example:
more -c sample.txt
-s : This option squeezes multiple blank lines into one single blank line.Example:more -s sample.txt
Example:
more -s sample.txt
-u : This option omits the underlines.Example:more -u sample.txt
Example:
more -u sample.txt
+/pattern : This option is used to search the string inside your text document. You can view all the instances by navigating through the result.Example:more +/reset sample.txt
Example:
more +/reset sample.txt
+num : This option displays the text after the specified number of lines of the document.Example:more +30 sample.txt
Example:
more +30 sample.txt
Using more to Read Long Outputs: We use more command after a pipe to see long outputs. For example, seeing log files, etc.
cat a.txt | more

Akanksha_Rai
linux-command
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Solve Linear Algebraic Equation in R Programming – solve() Function

25 Jun, 2020
solve() function in R Language is used to solve linear algebraic equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated.
Syntax: solve(a, b)
Parameters:a: coefficients of the equationb: vector or matrix of the equation
Example 1:
# R program to illustrate# solve function  # Calling solve() function to# calculate value of x in# ax = b, where a and b is # taken as the argumentssolve(5, 10)solve(2, 6)solve(3, 12)
Output:
[1] 2
[1] 3
[1] 4

Example 2:
# R program to illustrate# solve function  # Create 3 different vectors # using combine method. a1 <- c(3, 2, 5) a2 <- c(2, 3, 2) a3 <- c(5, 2, 4)     # bind the three vectors into a matrix  # using rbind() which is basically # row-wise bindingA <- rbind(a1, a2, a3)     # print the original matrix print(A)     # Use the solve() function  # to calculate the inverseT1 <- solve(A)     # print the inverse of the matrixprint(T1) 
Output:
   [, 1] [, 2] [, 3]
a1    3    2    5
a2    2    3    2
a3    5    2    4
              a1          a2         a3
[1, ] -0.29629630 -0.07407407  0.4074074
[2, ] -0.07407407  0.48148148 -0.1481481
[3, ]  0.40740741 -0.14814815 -0.1851852

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ADDTIME() function in MySQL - GeeksforGeeks

16 Nov, 2020
ADDTIME() function in MySQL is used to add the specified time intervals to the given date and time. It returns the date or DateTime after adding the time interval.
Syntax :
ADDTIME(expr1, expr2)

Parameter : This method accepts two parameter.
expr1 : The given datetime or time which we want to modify.
expr2 : The time interval which we want to add to given datetime. It can be both positive and negative.
Returns : It returns the date or DateTime after adding the given time interval.
Example-1 :Adding 15 seconds with the specified time using ADDTIME Function.
SELECT ADDTIME("11:34:21", "15") as Updated_time ;

Output :
Example-2 :Adding 10 minutes with the specified time using ADDTIME Function.
SELECT ADDTIME("10:54:21", "00:10:00") 
as Updated_time ;

Output :
Example-3 :Adding 12 hours with the specified datetime using ADDTIME Function.
SELECT ADDTIME("2009-02-20 18:04:22.333444", "12:00:00") 
as Updated_time ;

Output :
Example-4 :Adding 10 hours 30 minute 25 second and 100000 Microseconds with the specified datetime using ADDTIME Function.
SELECT ADDTIME("2020-09-20 17:04:22.222333", "10:30:25.100000") 
as Updated_time ;

Output :
Example-5 :The ADDTIME function can be used to set value of columns. To demonstrate create a table named ScheduleDetails
CREATE TABLE ScheduleDetails(
TrainId INT NOT NULL,
StationName VARCHAR(20) NOT NULL,
TrainName VARCHAR(20) NOT NULL,
ScheduledlArrivalTime TIME NOT NULL,
PRIMARY KEY(TrainId )
);
Now inserting values in ScheduleDetails table. We will use ADDTIME function which will denote delay in arrival timing. The value in ExpectedArrivalTime column will be the value given by ADDTIME Function.
INSERT INTO  
ScheduleDetails (TrainId, StationName, TrainName, ScheduledlArrivalTime )
VALUES
(12345, 'NJP', 'Saraighat Express', "17:04:22");

Now, checking the ScheduleDetails table :
SELECT *, ADDTIME(ScheduledlArrivalTime, "00:10:00") 
AS ExpectedArrivalTime FROM ScheduleDetails;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
How to Alter Multiple Columns at Once in SQL Server?
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
SQL Query to Convert VARCHAR to INT
SQL | Date functions
SQL - SELECT from Multiple Tables with MS SQL Server
SQL Query to Insert Multiple Rows
How to set the maximized bounds for a Frame in Java?

To set maximized bounds, use the setMaximizedBounds() method. Here, we will create a frame, which when maximized will form a shape −
JFrame frame = new JFrame("Login!");
Above, we have created a frame and now we will use the Rectangle class to specify an area of coordinates −
Rectangle bounds = new Rectangle(50, 10, 100, 200);
Now, set maximized bounds −
frame.setMaximizedBounds(bounds);
The following is an example to set the maximized bounds for a frame −
package my;
import java.awt.GridLayout;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Login!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("DeptId", SwingConstants.CENTER);
      label2 = new JLabel("SSN", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField deptid = new JTextField(20);
      JTextField ssn = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(deptid);
      frame.add(ssn);
      frame.add(passwd);
      Rectangle bounds = new Rectangle(50, 10, 100, 200);
      frame.setMaximizedBounds(bounds);
      frame.setSize(550, 200);
      frame.setVisible(true);
   }
}
Now, maximize it and you can see the rectangle bounds set above −
C library function - acos()

The C library function double acos(double x) returns the arc cosine of x in radians.
Following is the declaration for acos() function.
double acos(double x)
x − This is the floating point value in the interval [-1,+1].
x − This is the floating point value in the interval [-1,+1].
This function returns principal arc cosine of x, in the interval [0, pi] radians.
The following example shows the usage of acos() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main () {
   double x, ret, val;

   x = 0.9;
   val = 180.0 / PI;

   ret = acos(x) * val;
   printf("The arc cosine of %lf is %lf degrees", x, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
The arc cosine of 0.900000 is 25.855040 degrees


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to convert negative values in a matrix to 0 in R?

To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0).
Consider the below data frame −
 Live Demo
M1<-matrix(sample(-10:2,40,replace=TRUE),ncol=2)
M1
      [,1] [,2]
[1,]   0    -2
[2,]  -1    0
[3,]  -10   1
[4,]  -4   -8
[5,]  -7   -8
[6,]   0    0
[7,]  -7    0
[8,]  -8   -3
[9,]  -1   -9
[10,] -4   -10
[11,]  1    -7
[12,]  0    -5
[13,] -6    -3
[14,] -4    -4
[15,] -4    -4
[16,]  0     2
[17,] -7    -2
[18,] -7    -2
[19,] -5    -5
[20,] -6    -7
Converting negative values in matrix M1 to 0 −
pmax(M1,0)
     [,1] [,2]
[1,]  0    0
[2,]  0    0
[3,]  0    1
[4,]  0    0
[5,]  0    0
[6,]  0    0
[7,]  0    0
[8,]  0    0
[9,]  0    0
[10,] 0    0
[11,] 1    0
[12,] 0    0
[13,] 0    0
[14,] 0    0
[15,] 0    0
[16,] 0    2
[17,] 0    0
[18,] 0    0
[19,] 0    0
[20,] 0    0
 Live Demo
M2<-matrix(sample(-10:10,80,replace=TRUE),ncol=4)
M2
      [,1] [,2] [,3] [,4]
[1,]  -10   1    4    7
[2,]  -9    5    6    2
[3,]   7    4    1   -5
[4,]   2    9    0    2
[5,]  -2   -6    1   -9
[6,]   8   -9   -9    1
[7,]   3   -3    0   -1
[8,]   5    0   -3    5
[9,]  -2    5    7   -5
[10,] -3    0   -8    1
[11,] -4    3   -2   -4
[12,] 5     4   -5    2
[13,] 0    10   -1   -8
[14,] 5    -9   -4   -1
[15,] 6   -6     2    0
[16,] -6  -9    -5   -8
[17,] -4   4   -9    -3
[18,] 4  -10    4     7
[19,] -9  -8    2    -4
[20,] -2   3    9    -8
Converting negative values in matrix M2 to 0 −
pmax(M2,0)
      [,1] [,2] [,3] [,4]
[1,]   0    1    4    7
[2,]   0    5    6    2
[3,]   7    4    1    0
[4,]   2    9    0    2
[5,]   0    0    1    0
[6,]   8    0    0    1
[7,]   3    0    0    0
[8,]   5    0    0    5
[9,]   0    5    7    0
[10,] 0     0    0    1
[11,] 0    3     0    0
[12,] 5    4     0    2
[13,] 0   10     0    0
[14,] 5    0     0    0
[15,] 6    0     2    0
[16,] 0    0     0    0
[17,] 0    4     0    0
[18,] 4    0     4    7
[19,] 0    0     2    0
[20,] 0    3     9    0
Perl | length() Function - GeeksforGeeks

25 Jun, 2019
length() function in Perl finds length (number of characters) of a given string, or $_ if not specified.
Syntax:length(VAR)
Parameter:VAR: String or a group of strings whose length is to be calculatedReturn:Returns the size of the string.
Example 1:
#!/usr/bin/perl  # String whose length is to be calculated$orignal_string = "Geeks for Geeks";  # Function to calculate length$string_len = length($orignal_string);  # Printing the Lengthprint "Length of String is: $string_len";
Output:
Length of String is: 15
 Example 2:
#!/usr/bin/perl  # String whose length is to be calculated$orignal_string = "123456 is Geeks Code";  # Function to calculate length$string_len = length($orignal_string);  # Printing the Lengthprint "Length of String is: $string_len";
Output:
Length of String is: 20
Note : Scalar context on an array or hash is used if the corresponding size is to be determined.
Perl-function
Perl-String
Perl-String-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Polymorphism in OOPs
Perl | Arrays
Perl | Arrays (push, pop, shift, unshift)
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | Subroutines or Functions
Perl | Boolean Values
Introduction to Perl
Perl | join() Function
Perl | sleep() Function
How do I write not greater than in a MySQL query?

The not greater than in a query can be written simply like less than or equal to ( <=). The syntax is as follows −
select * from yourTableName where yourColumnName<=yourColumnName;
Let us first create a table −
mysql> create table DemoTable1480
   -> (
   -> StudentName varchar(40),
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1480 values('Chris',78);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1480 values('Bob',45);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1480 values('John',67);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1480 values('Adam',56);
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1480;
This will produce the following output −
+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           78 |
| Bob         |           45 |
| John        |           67 |
| Adam        |           56 |
+-------------+--------------+
4 rows in set (0.00 sec)
Following is the query to write not greater than in a MySQL query −
mysql> select * from DemoTable1480 where StudentMarks <=65;
This will produce the following output −
+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Bob         |           45 |
| Adam        |           56 |
+-------------+--------------+
2 rows in set (0.00 sec)
Difference Between Properties and Indexers in C# - GeeksforGeeks

24 Jul, 2020
Properties in C# are named members that use access modifiers to set and retrieve values of fields declared in a secured manner. Properties are used for abstracting and encapsulating access to a field of a class by defining only important actions and hiding their implementation. Properties are invoked through a described name and can be declared as a static or an instance member.
Syntax of declaring a property in C#:
[access_modifier] [return_type] [PropertyName]  
{
//body of property
}

Indexers in C# are data members that act as an array and allow you to access data within objects to be indexed in the same way. Indexers are always declared as instance members, never as static members. Indexers are implemented in the same way as properties, except that the declaration of an indexer must have at least one parameter.
Syntax of creating an indexer in C#:
[access_modifier] [return_type] this [parameter]
{
  get 
  {
     // return value
  }
  set 
  {
    // return value
  }
}

CSharp-Indexers & Properties
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
Class method vs Static method in Python
Difference between BFS and DFS
Differences between TCP and UDP
Difference between Process and Thread
Difference between var, let and const keywords in JavaScript
How to find the difference in number of days between two date columns of an R data frame?

When dealing with date data, we often want to find the difference between dates if the data contains two or more date values. Same thing can be done for the two columns of an R data frame that contains dates but first we need to read those date columns in date format in case they are not recorded as date in R. The finding of difference in number of days can be done by using difftime function.
Consider the below data −
date1<-c("2020/02/02","2020/02/04","2020/02/05","2020/02/06","2020/02/08","2020/02/12","2020/02/13","2020/02/15","2020/02/16","2020/02/17","2020/02/18","2020/02/19","2020/02/20","2020/02/22","2020/02/23","2020/02/24","2020/02/25","2020/02/26","2020/02/27","2020/03/01")
date1
[1] "2020/02/02" "2020/02/04" "2020/02/05" "2020/02/06" "2020/02/08"
[6] "2020/02/12" "2020/02/13" "2020/02/15" "2020/02/16" "2020/02/17"
[11] "2020/02/18" "2020/02/19" "2020/02/20" "2020/02/22" "2020/02/23"
[16] "2020/02/24" "2020/02/25" "2020/02/26" "2020/02/27" "2020/03/01"
date2<-c("2020/03/02","2020/03/03","2020/03/05","2020/03/06","2020/03/07","2020/03/08","2020/03/10","2020/03/13","2020/03/14","2020/03/15","2020/03/16","2020/03/17","2020/03/18","2020/03/20","2020/03/21","2020/03/22","2020/03/23","2020/03/24","2020/03/26","2020/03/27")
date2
[1] "2020/03/02" "2020/03/03" "2020/03/05" "2020/03/06" "2020/03/07"
[6] "2020/03/08" "2020/03/10" "2020/03/13" "2020/03/14" "2020/03/15"
[11] "2020/03/16" "2020/03/17" "2020/03/18" "2020/03/20" "2020/03/21"
[16] "2020/03/22" "2020/03/23" "2020/03/24" "2020/03/26" "2020/03/27"
df<-data.frame(date1,date2)
df
date1 date2
1 2020/02/02 2020/03/02
2 2020/02/04 2020/03/03
3 2020/02/05 2020/03/05
4 2020/02/06 2020/03/06
5 2020/02/08 2020/03/07
6 2020/02/12 2020/03/08
7 2020/02/13 2020/03/10
8 2020/02/15 2020/03/13
9 2020/02/16 2020/03/14
10 2020/02/17 2020/03/15
11 2020/02/18 2020/03/16
12 2020/02/19 2020/03/17
13 2020/02/20 2020/03/18
14 2020/02/22 2020/03/20
15 2020/02/23 2020/03/21
16 2020/02/24 2020/03/22
17 2020/02/25 2020/03/23
18 2020/02/26 2020/03/24
19 2020/02/27 2020/03/26
20 2020/03/01 2020/03/27
Changing the format of date1 and date2 to date format −
df$date1<-as.Date(df$date1,format="%Y/%m/%d")
df$date2<-as.Date(df$date2,format="%Y/%m/%d")
Finding the difference between two dates in number of days −
df$Date_difference_in_days <-difftime(df$date1,df$date2,units=c("days"))
df
date1 date2 Date_difference_in_days
1 2020-02-02 2020-03-02 -29 days
2 2020-02-04 2020-03-03 -28 days
3 2020-02-05 2020-03-05 -29 days
4 2020-02-06 2020-03-06 -29 days
5 2020-02-08 2020-03-07 -28 days
6 2020-02-12 2020-03-08 -25 days
7 2020-02-13 2020-03-10 -26 days
8 2020-02-15 2020-03-13 -27 days
9 2020-02-16 2020-03-14 -27 days
10 2020-02-17 2020-03-15 -27 days
11 2020-02-18 2020-03-16 -27 days
12 2020-02-19 2020-03-17 -27 days
13 2020-02-20 2020-03-18 -27 days
14 2020-02-22 2020-03-20 -27 days
15 2020-02-23 2020-03-21 -27 days
16 2020-02-24 2020-03-22 -27 days
17 2020-02-25 2020-03-23 -27 days
18 2020-02-26 2020-03-24 -27 days
19 2020-02-27 2020-03-26 -28 days
20 2020-03-01 2020-03-27 -26 days
Parent and Child classes having same data member in Java

The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
Following is an example −
 Live Demo
class Demo_base {
   int value = 1000;
   Demo_base() {
      System.out.println("This is the base class constructor");
   }
}
class Demo_inherits extends Demo_base {
   int value = 10;
   Demo_inherits() {
      System.out.println("This is the inherited class constructor");
   }
}
public class Demo {
   public static void main(String[] args) {
      Demo_inherits my_inherited_obj = new Demo_inherits();
      System.out.println("In the main class, inherited class object has been created");
      System.out.println("Reference of inherited class type :" + my_inherited_obj.value);
      Demo_base my_obj = my_inherited_obj;
      System.out.println("In the main class, parent class object has been created");
      System.out.println("Reference of base class type : " + my_obj.value);
   }
}
This is the base class constructor
This is the inherited class constructor
In the main class, inherited class object has been created
Reference of inherited class type :10
In the main class, parent class object has been created
Reference of base class type : 1000
A class named ‘Demo_base’ contains an integer value and a constructor that prints relevant message. Another class named ‘Demo_inherits’ becomes the child class to parent class ‘Demo_base’. This means, the ‘Demo_inherits’ class extends to the base class ‘Demo_base’.
In this class, another value for the same variable is defined, and a constructor of the child class is defined with relevant message to be printed on the screen. A class named Demo contains the main function, where an instance of the child class is created, and its associated integer value is printed on the screen. A similar process is done for the parent class, by creating an instance and accessing its associated value and printing it on the screen.
How to hide the colorbar of a Seaborn heatmap?

To hide the colorbar of a Seaborn heatmap, we can use cbar=False in heatmap() method.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a dataframe using 4 columns.
Make a dataframe using 4 columns.
Use heatmap() method to plot rectangular data as a color-encoded matrix.
Use heatmap() method to plot rectangular data as a color-encoded matrix.
To display the figure, use show() method.
To display the figure, use show() method.
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(np.random.random((4, 4)), columns=["a", "b", "c", "d"])
sns.heatmap(df, cbar=False)

plt.show()
Geolocation clearWatch() API

The clearWatch method cancels an ongoing watchPosition call. When cancelled, the watchPosition call stops retrieving updates about the current geographic location of the device.
Here is the syntax of this method −
clearWatch(watchId);

Here is the detail of parameters −
watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.
watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned by the watchPosition call.
The clearWatch method does not return a value.
<!DOCTYPE HTML>

<html>
   <head>
   
      <script type = "text/javascript">
         var watchID;
         var geoLoc;
         
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }
         
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            } else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }
         
         function getLocationUpdate(){
            
            if(navigator.geolocation){
               
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               geoLoc = navigator.geolocation;
               watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
            } else {
               alert("Sorry, browser does not support geolocation!");
            }
         }
         
         function stopWatch() {
            geoLoc.clearWatch(watchID);
         }
      </script>
   </head>
   
   <body>
      
      <form>
         <input type = "button" onclick = "getLocationUpdate();" value = "Watch Update"/>
         <input type = "button" onclick = "stopWatch();" value = "Stop Watch"/>
      </form>
      
   </body>
</html>
This will produce following result −

    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
How to save new state to local JSON using ReactJS ?

14 Apr, 2021
Sometimes we need to store the state locally on the browser in a JSON format. We can save any information to the local storage of the browser and access that information anytime later.
Setting up environment and Execution:
Step 1: Create React App by using the following command.npx create-react-app foldername
Step 1: Create React App by using the following command.
npx create-react-app foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:cd foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
App.js
import React, { Component }  from 'react';   class App extends Component {     state = {     data: "This is data",     num: 123,     boolean: true,   }     // save data to localStorage   saveStateToLocalStorage = () => {     localStorage.setItem('state', JSON.stringify(this.state));   }     // Fetch data from local storage   getStateFromLocalStorage = () => {     let data = localStorage.getItem('state');     if(data !== undefined) {       this.setState(JSON.parse(data));     }   }     componentDidMount() {     // Fetch data from local storage     this.getStateFromLocalStorage();   }     render() {     return (       <div>         <h2>GeeksforGeeks</h2>         <button onClick={this.saveStateToLocalStorage}>           Save State to local storage\         </button>       </div>     );   } }   export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
JSON
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to do crud operations in ReactJS ?
How to create a multi-page website using React.js ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Differences between Functional Components and Class Components in React
D3.js selection.property() Function

16 Jun, 2022
The selection.property() function is used to set or change the property and value of a particular element. The value of a particular property can be deleted by setting its value to null.
Syntax:
selection.property(name[, value]);
Parameters: This function accept two parameters as mentioned above and described below:
name: The name of the property to set.
value: The property value to be set.
Return Value: This function does not return any value.
Example 1:
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width, initial-scale=1.0">     <script src="https://d3js.org/d3.v4.min.js">    </script></head> <body>    <div>        <input type="text">    </div>     <script>         // Sets value property of the input tag        var input = d3.select("input")            .property("value", "some value from input");        var text = document.querySelector("input");                 // Value from input        console.log(text.value);    </script></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" path1tent=        "width=device-width, initial-scale=1.0">     <script src="https://d3js.org/d3.v4.min.js">    </script></head> <body>    <div>        <input type="checkbox" class="checkbox"            name="" id="">checkbox<br>         <button>Click me</button>    </div>         <script>        function func() {             // Sets checked and value property            // of the checkbox            var chk = d3.select(".checkbox").property(                "value", "some value from checkbox");            var chk = d3.select(".checkbox")                .property("checked", true);            var text = document.querySelector(".checkbox");             // Value from checkbox            console.log(text.value);            console.log(text.checked);        }                 let btn = document.querySelector("button");        btn.addEventListener("click", func);    </script></body> </html>
Output:
Before clicking the click me button:
After clicking the click me button:
surinderdawra388
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logger isLoggable() method in Java with Examples

26 Mar, 2019
isLoggable() method of a Logger class is used to return a response in boolean value which provides an answer to the query that if a message of the given level would actually be logged by this logger or not. This check is based on the Loggers effective level, which may be inherited from its parent.
Syntax:
public boolean isLoggable(Level level)

Parameters: This method accepts one parameter level which represents message logging level.
Return value: This method returns true if the given message level is currently being logged.
Below programs illustrate the isLoggable() method:
Program 1:
// Java program to demonstrate// Logger.isLoggable() method  import java.util.logging.*;  public class GFG {      private static Logger logger        = Logger.getLogger(            GFG.class.getName());      public static void main(String args[])    {          // Check if the Level.INFO        // is currently being logged.        boolean flag            = logger.isLoggable(                Level.INFO);          // Print value        System.out.println("The Level.INFO"                           + " is currently being logged - "                           + flag);    }}
The Level.INFO is currently being logged - true

Program 2:
// Java program to demonstrate// Logger.isLoggable() method  import java.util.logging.*;  public class GFG {      private static Logger logger        = Logger.getLogger(            GFG.class.getName());      public static void main(String args[])    {          // Check if the Level.OFF        // is currently being logged.        boolean flag            = logger.isLoggable(Level.OFF);          // Print value        System.out.println("The Level.OFF"                           + " is currently being logged - "                           + flag);    }}
The Level.OFF is currently being logged - true

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/logging/Logger.html#isLoggable(java.util.logging.Level)
Java - util package
Java-Functions
Java-Logger
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
homogeneity_score using sklearn in Python

01 Oct, 2020
An entirely homogeneous clustering is one where each cluster has information that directs a place toward a similar class label. Homogeneity portrays the closeness of the clustering algorithm to this (homogeneity_score) perfection. 
This metric is autonomous of the outright values of the labels. A permutation of the cluster label values won’t change the score value in any way.
Syntax : sklearn.metrics.homogeneity_score(labels_true, labels_pred)
The Metric is not symmetric, switching label_true with label_pred will return the completeness_score.
Parameters :
labels_true:<int array, shape = [n_samples]> : It accept the ground truth class labels to be used as a reference.
labels_pred: <array-like of shape (n_samples,)>: It accepts the cluster labels to evaluate.
Returns:
homogeneity:<float>: Its return the score between 0.0 and 1.0 stands for perfectly homogeneous labeling.
Example1:
Python3
import pandas as pdimport matplotlib.pyplot as pltfrom sklearn.cluster import KMeansfrom sklearn.metrics import homogeneity_score    # Changing the location file# cd C:\Users\Dev\Desktop\Credit Card Fraud  # Loading the datadf = pd.read_csv('creditcard.csv')  # Separating the dependent and independent variablesy = df['Class']X = df.drop('Class', axis=1)  # Building the clustering modelkmeans = KMeans(n_clusters=2)  # Training the clustering modelkmeans.fit(X)  # Storing the predicted Clustering labelslabels = kmeans.predict(X)  # Evaluating the performancehomogeneity_score(y, labels)
Output:
0.00496764949717645

Example 2: Perfectly homogeneous:
Python3
from sklearn.metrics.cluster import homogeneity_score  # Evaluate the scorehscore = homogeneity_score([0, 1, 0, 1], [1, 0, 1, 0])  print(hscore)
Output:
1.0

Example 3: Non-perfect labelings that further split classes into more clusters can be perfectly homogeneous:
Python3
from sklearn.metrics.cluster import homogeneity_score  # Evaluate the scorehscore = homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3])  print(hscore)
Output:
0.9999999999999999

Example 4: Include samples from different classes don’t make for homogeneous labeling:
Python3
from sklearn.metrics.cluster import homogeneity_score  # Evaluate the scorehscore = homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1])  print(hscore)
Output:
0.0

python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to make an ArrayList read only in Java

11 Dec, 2018
Given an ArrayList, the task is to make this ArrayList read-only in Java.
Examples:
Input: ArrayList: [1, 2, 3, 4, 5]
Output: Read-only ArrayList: [1, 2, 3, 4, 5] 

Input: ArrayList: [geeks, for, geeks]
Output: Read-only ArrayList: [geeks, for, geeks]

An ArrayList can be made read-only easily with the help of Collections.unmodifiableList() method. This method takes the modifiable ArrayList as a parameter and returns the read-only unmodifiable view of this ArrayList.
Syntax:
readOnlyArrayList = Collections.unmodifiableList(ArrayList);
Below is the implementation of the above approach:
// Java program to demonstrate// unmodifiableList() method  import java.util.*;  public class GFG1 {    public static void main(String[] argv)        throws Exception    {        try {              // creating object of ArrayList<Character>            List<Character> list = new ArrayList<Character>();              // populate the list            list.add('X');            list.add('Y');            list.add('Z');              // printing the list            System.out.println("Initial list: "                               + list);              // getting readonly list            // using unmodifiableList() method            List<Character>                immutablelist = Collections                                    .unmodifiableList(list);              // printing the list            System.out.println("ReadOnly ArrayList: "                               + immutablelist);              // Adding element to new Collection            System.out.println("\nTrying to modify"                               + " the ReadOnly ArrayList.");            immutablelist.add('A');        }          catch (UnsupportedOperationException e) {            System.out.println("Exception thrown : " + e);        }    }}
Initial list: [X, Y, Z]
ReadOnly ArrayList: [X, Y, Z]

Trying to modify the ReadOnly ArrayList.
Exception thrown : java.lang.UnsupportedOperationException

Java-ArrayList
Java-Collections
Java-List-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.