code-rag-bench/online-tutorials huggingface dataset:
How to find the difference between two dataframes in R ?

21 Apr, 2021
In this article, we will discuss how to find the difference between two data frames or compare two dataframes or data sets in R Programming Language. 
Intersect function in R helps to get the common elements in the two datasets.
Syntax:
intersect(names(data_short), names(data_long))
Example:
R
first <-       data.frame(             "1" = c('0.44','0.554','0.67','0.64'),             "2" = c('0.124','0.22','0.82','0.994'),             "3" = c('0.82','1.22','0.73','1.23')         )  second <-     data.frame(            "1" = runif(4),             "2" = runif(4),             "3" = runif(4),             "d" = runif(4),             "e" = runif(4)         )  second[intersect(names(first), names(second))]
Output:
    1                    2               3
1 0.562627228 0.9391250 0.6437934
2 0.003867576 0.7131200 0.9313777
3 0.129852760 0.2657934 0.9291285
4 0.325867139 0.2367633 0.1211350
This function unlike intersect helps to view the columns that are the missing in first dataframe. 
Syntax:
setdiff( dataframe2, dataframe 1)
Example:
R
first <-       data.frame(             "1" = c('0.44','0.554','0.67','0.64'),             "2" = c('0.124','0.22','0.82','0.994'),             "3" = c('0.82','1.22','0.73','1.23')         )  second <-     data.frame(            "1" = runif(4),             "2" = runif(4),             "3" = runif(4),             "d" = runif(4),             "e" = runif(4)         )  second[setdiff(names(second), names(first))]
Output:
 d                  e
1 0.7899783 0.04363003
2 0.9167861 0.39865991
3 0.3314494 0.13963663
4 0.7005957 0.73401069
We will select from dplyr to get the columns of the dataframe on which some operations will be performed to get the desired difference between the two dataframes. 
Example:
R
library("dplyr")  first <-       data.frame(             "1" = c('0.44','0.554','0.67','0.64'),             "2" = c('0.124','0.22','0.82','0.994'),             "3" = c('0.82','1.22','0.73','1.23')         )  second <-     data.frame(            "1" = runif(4),             "2" = runif(4),             "3" = runif(4),             "d" = runif(4),             "e" = runif(4)         )  second%>%select(which(!(colnames(second) %in% colnames(first))))
Output:
    d                e
1 0.7899783 0.04363003
2 0.9167861 0.39865991
3 0.3314494 0.13963663
4 0.7005957 0.73401069
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
PostgreSQL – ILIKE operator

28 Aug, 2020
The PostgreSQL ILIKE operator is used query data using pattern matching techniques. Its result include strings that are case-insensitive and follow the mentioned pattern.It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below:
Percent ( %) for matching any sequence of characters.
Underscore ( _) for matching any single character.
Syntax: string ILIKE pattern;
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.
Now, let’s look into a few examples.
Example 1:Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that begins with “ke” using the ILIKE operator in our sample database.
SELECT
    first_name,
        last_name
FROM
    customer
WHERE
    first_name ILIKE 'Ke%';
Output:
Notice few things in the above example, the WHERE clause contains a special expression: the first_name, the LIKE operator, and a string that contains a percent (%) character, which is referred to as a pattern.
Example 2:Here we will query for customers whose first name begins with any single character, is followed by the literal string “aR”, and ends with any number of characters using the ILIKE operator in our sample database.
SELECT
    first_name,
    last_name
FROM
    customer
WHERE
    first_name ILIKE '_aR%';
Output:
postgreSQL-operators
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Find Maximum difference pair - GeeksforGeeks

29 Apr, 2019
Sometimes, we need to find the specific problem of getting the pair which yields the maximum difference, this can be solved by sorting and getting the first and last elements of the list. But in some case, we don’t with to change the ordering of list and perform some operation in a similar list without using extra space. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + max() + combination() + lambda
This particular task can be performed using the combination of above functions in which we use list comprehension to bind all the functionalities and max function to get the maximum difference, combination function finds all differences internally and lambda function is used to compute the difference.
# Python3 code to demonstrate# maximum difference pair# using list comprehension + max() + combinations() + lambdafrom itertools import combinations  # initializing listtest_list = [3, 4, 1, 7, 9, 1]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + max() + combinations() + lambda# maximum difference pairres = max(combinations(test_list, 2), key = lambda sub: abs(sub[0]-sub[1]))  # print resultprint("The maximum difference pair is : " + str(res))
The original list : [3, 4, 1, 7, 9, 1]
The maximum difference pair is : (1, 9)

 
Method #2 : Using list comprehension + nlargest() + combination() + lambda
This method has potential of not only finding a single maximum but also k maximum difference pairs if required and uses nlargest function instead of max function to achieve this functionality.
# Python3 code to demonstrate# maximum difference pair# using list comprehension + nlargest() + combinations() + lambdafrom itertools import combinationsfrom heapq import nlargest  # initializing listtest_list = [3, 4, 1, 7, 9, 8]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + max() + combinations() + lambda# maximum difference pair# computes 2 maximum pair differencesres = nlargest(2, combinations(test_list, 2),          key = lambda sub: abs(sub[0]-sub[1]))  # print resultprint("The maximum difference pair is : " + str(res))
The original list : [3, 4, 1, 7, 9, 8]
The maximum difference pair is : [(1, 9), (1, 8)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
XML - Declaration

This chapter covers XML declaration in detail. XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document.
Following syntax shows XML declaration −
<?xml
   version = "version_number"
   encoding = "encoding_declaration"
   standalone = "standalone_status"
?>
Each parameter consists of a parameter name, an equals sign (=), and parameter value inside a quote. Following table shows the above syntax in detail −
An XML declaration should abide with the following rules −
If the XML declaration is present in the XML, it must be placed as the first line in the XML document.
If the XML declaration is present in the XML, it must be placed as the first line in the XML document.
If the XML declaration is included, it must contain version number attribute.
If the XML declaration is included, it must contain version number attribute.
The Parameter names and values are case-sensitive.
The Parameter names and values are case-sensitive.
The names are always in lower case.
The names are always in lower case.
The order of placing the parameters is important. The correct order is: version, encoding and standalone.
The order of placing the parameters is important. The correct order is: version, encoding and standalone.
Either single or double quotes may be used.
Either single or double quotes may be used.
The XML declaration has no closing tag i.e. </?xml>
The XML declaration has no closing tag i.e. </?xml>
Following are few examples of XML declarations −
XML declaration with no parameters −
<?xml >

XML declaration with version definition −
<?xml version = "1.0">

XML declaration with all parameters defined −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>

XML declaration with all parameters defined in single quotes −
<?xml version = '1.0' encoding = 'iso-8859-1' standalone = 'no' ?>


    84 Lectures 
     6 hours 

 Frahaan Hussain

    29 Lectures 
     2 hours 

 YouAccel

    27 Lectures 
     1 hours 

 Jordan Stanchev

    16 Lectures 
     2 hours 

 Simon Sez IT
 Print
 Add Notes
 Bookmark this page
How to raise an exception in Python?

We can force raise an exception using the raise keyword. Here is the syntax for calling the “raise” method.
raise [Exception [, args [, traceback]]]
where, the Exception is the name of the exception; the optional “args” represents the value of the exception argument.
The also optional argument, traceback, is the traceback object used for the exception.
#raise_error.py
try:
i = int ( input ( "Enter a positive integer value: " ) )
if i <= 0:
raise ValueError ( "This is not a positive number!!" )
except ValueError as e:
print(e)
If we execute the above script at terminal as follows
$python raise_error.py
Enter a positive integer: –6
Following is displayed since we have entered a negative number:
This is not a positive number!!
Alternate example code
# Here there is no variable or argument passed with the raised exception
import sys
try:
i = int ( input("Enter a positive integer value: "))
if i <= 0:
raise ValueError#("This is not a positive number!!")
except ValueError as e:
print sys.exc_info()
output
Enter a positive integer value: -9
(<type 'exceptions.ValueError'>, ValueError(), <traceback object at
 0x0000000003584EC8>)
SQLite - Arithmetic Operators

Following are some simple examples showing the usage of SQLite Arithmetic Operators −
sqlite> .mode line
sqlite> select 10 + 20;
10 + 20 = 30

sqlite> select 10 - 20;
10 - 20 = -10

sqlite> select 10 * 20;
10 * 20 = 200

sqlite> select 10 / 5;
10 / 5 = 2

sqlite> select 12 %  5;
12 %  5 = 2

    25 Lectures 
     4.5 hours 

 Sandip Bhattacharya

    17 Lectures 
     1 hours 

 Laurence Svekis

    5 Lectures 
     51 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Python | Pandas Timestamp.weekday_name

08 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.weekday_name attribute return the name of the day of the week for the given date in the Timestamp object.
Syntax : Timestamp.weekday_name
Parameters : None
Return : name of the week day
Example #1: Use Timestamp.weekday_name attribute to find the name of the weekday for the given date in the Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,            hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.weekday_name attribute to find the weekday name.
# return the name of the weekdayts.weekday_name
Output :
As we can see in the output, the Timestamp.weekday_name attribute has returned ‘Monday’ indicating that the date in the given Timestamp object is ‘Monday’.
Example #2: Use Timestamp.weekday_name attribute to find the name of the weekday for the given date in the Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009,  month = 5, day = 31,        hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.weekday_name attribute to find the weekday name.
# return the name of the weekdayts.weekday_name
Output :
As we can see in the output, the Timestamp.weekday_name attribute has returned ‘Sunday’ indicating that the date in the given Timestamp object is ‘Sunday’.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.outer() function – Python

05 May, 2020
numpy.outer() function compute the outer product of two vectors.
Syntax : numpy.outer(a, b, out = None)
Parameters :a : [array_like] First input vector. Input is flattened if not already 1-dimensional.b : [array_like] Second input vector. Input is flattened if not already 1-dimensional.out : [ndarray, optional] A location where the result is stored.
Return : [ndarray] Returns the outer product of two vectors. out[i, j] = a[i] * b[j]
Code #1 :
# Python program explaining# numpy.outer() function   # importing numpy as geek import numpy as geek   a = geek.ones(4)b = geek.linspace(-1, 2, 4)  gfg = geek.outer(a, b)  print (gfg)
Output :
[[-1.  0.  1.  2.]
 [-1.  0.  1.  2.]
 [-1.  0.  1.  2.]
 [-1.  0.  1.  2.]]

 Code #2 :
# Python program explaining# numpy.outer() function   # importing numpy as geek import numpy as geek   a = geek.ones(5)b = geek.linspace(-2, 2, 5)  gfg = geek.outer(a, b)  print (gfg)
Output :
[[-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]
 [-2. -1.  0.  1.  2.]]

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Break and Next statements in R

04 May, 2020
In R programming, we require a control structure to run a block of code multiple times. Loops come in the class of the most fundamental and strong programming concepts. A loop is a control statement that allows multiple executions of a statement or a set of statements. The word ‘looping’ means cycling or iterating.
Jump statements are used in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are:
Break Statement
Next Statement
Note: In R language continue statement is referred to as the next statement.
The basic Function of Break and Next statement is to alter the running loop in the program and flow the control outside of the loop. In R language, repeat, for and while loops are used to run the statement or get the desired output N number of times until the given condition to the loop becomes false.Sometimes there will be such a condition where we need to terminate the loop to continue with the rest of the program. In such cases R Break statement is used.Sometimes there will be such condition where we don’t want loop to perform the program for specific condition inside the loop. In such cases, R next statement is used.
The break keyword is a jump statement that is used to terminate the loop at a particular iteration.Syntax:
if (test_expression) {
break
}
Example 1: Using break in For-loop
# R program for break statement in For-loop  no <- 1:10  for (val in no){    if (val == 5)     {        print(paste("Coming out from for loop Where i = ", val))        break    }    print(paste("Values are: ", val))}
Output:
[1] "Values are:  1"
[1] "Values are:  2"
[1] "Values are:  3"
[1] "Values are:  4"
[1] "Coming out from for loop Where i =  5"

Example 2: Using break statement in While-loop
# R Break Statement Examplea<-1    while (a < 10){        print(a)        if(a==5)            break        a = a + 1    }    
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

The next statement is used to skip the current iteration in the loop and move to the next iteration without exiting from the loop itself.Syntax:
if (test_condition) 
{
    next
}
Example 1: Using next statement in For-loop
# R Next Statement Example  no <- 1:10  for (val in no)  {    if (val == 6)      {        print(paste("Skipping for loop Where i =  ", val))        next    }    print(paste("Values are:  ", val))}
Output:
[1] "Values are:   1"
[1] "Values are:   2"
[1] "Values are:   3"
[1] "Values are:   4"
[1] "Values are:   5"
[1] "Skipping for loop Where i =   6"
[1] "Values are:   7"
[1] "Values are:   8"
[1] "Values are:   9"
[1] "Values are:   10"

Example 2: Using next statement in While-loop
# R Next Statement Examplex <- 1while(x < 5) {    x <- x + 1;     if (x == 3)         next;     print(x);} 
Output:
[1] 2
[1] 4
[1] 5

Picked
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find Nth odd Fibonacci Number

13 Mar, 2022
Given an integer N. The task is to find the Nth odd Fibonacci number.The odd number fibonacci series is as:  
1, 1, 3, 5, 13, 21, 55, 89, 233, 377, 987, 1597.............and so on.Note: In the above series we have omitted even terms from the general fibonacci sequence.  
Examples:  
Input: N = 3
Output: 3

Input: N = 4
Output: 5
 
Approach: On observing carefully, it can be deduced that every third Fibonacci number is even, so the Nth odd Fibonacci number is the {(3*N+1)/2}th term in the general Fibonacci sequence.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program for Nth odd fibonacci number #include <bits/stdc++.h>using namespace std; // Function to find nth odd fibonacci numberint oddFib(int n){    n = (3 * n + 1) / 2;    int a = -1, b = 1, c, i;    for (i = 1; i <= n; i++) {        c = a + b;        a = b;        b = c;    }    return c;} // Driver Codeint main(){    int n = 4;         cout << oddFib(n);         return 0;}
// Java program for Nth odd fibonacci numberclass GFG{         // Function to find nth odd fibonacci number    static int oddFib(int n)    {        n = (3 * n + 1) / 2;                 int a = -1, b = 1, c = 0, i;                 for (i = 1; i <= n; i++)        {            c = a + b;            a = b;            b = c;        }        return c;    }         // Driver Code    public static void main (String[] args)    {        int n = 4;                 System.out.println(oddFib(n));    }} // This code is contributed by AnkitRai01
# Python3 program for Nth odd fibonacci number # Function to find nth odd fibonacci numberdef oddFib(n):    n = (3 * n + 1) // 2     a = -1    b = 1    c = 0    for i in range(1, n + 1):        c = a + b        a = b        b = c     return c # Driver Coden = 4 print(oddFib(n)) # This code is contributed by mohit kumar
// C# program for Nth odd fibonacci numberusing System;     class GFG{         // Function to find nth odd fibonacci number    static int oddFib(int n)    {        n = (3 * n + 1) / 2;                 int a = -1, b = 1, c = 0, i;                 for (i = 1; i <= n; i++)        {            c = a + b;            a = b;            b = c;        }        return c;    }         // Driver Code    public static void Main (String[] args)    {        int n = 4;                 Console.WriteLine(oddFib(n));    }} // This code is contributed by 29AjayKumar
<script> // JavaScript program for Nth odd fibonacci number // Function to find nth odd fibonacci numberfunction oddFib(n){    n = (3 * n + 1) / 2;    var a = -1, b = 1, c, i;    for (i = 1; i <= n; i++) {        c = a + b;        a = b;        b = c;    }    return c;} // Driver Codevar n = 4;document.write(oddFib(n)); </script>
5
 
Time Complexity: O(N)
Auxiliary Space: O(1) 
mohit kumar 29
ankthon
29AjayKumar
rrrtnx
sagar0719kumar
sooda367
subham348
Fibonacci
Numbers
Mathematical
Mathematical
Fibonacci
Numbers
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Erlang - Macros

Macros are generally used for inline code replacements. In Erlang, macros are defined via the following statements.
-define(Constant, Replacement).
-define(Func(Var1, Var2,.., Var), Replacement).
Following is an example of macros using the first syntax −
-module(helloworld). 
-export([start/0]). 
-define(a,1). 

start() -> 
   io:fwrite("~w",[?a]).
From the above program you can see that the macro gets expanded by using the ‘?’ symbol. The constant gets replaced in place by the value defined in the macro.
The output of the above program will be −
1

An example of a macro using the function class is as follows −
-module(helloworld). 
-export([start/0]). 
-define(macro1(X,Y),{X+Y}). 

start() ->
   io:fwrite("~w",[?macro1(1,2)]).
The output of the above program will be −
{3}

The following additional statements are available for macros −
undef(Macro) − Undefines the macro; after this you cannot call the macro.
undef(Macro) − Undefines the macro; after this you cannot call the macro.
ifdef(Macro) − Evaluates the following lines only if the Macro has been defined.
ifdef(Macro) − Evaluates the following lines only if the Macro has been defined.
ifndef(Macro) − Evaluates the following lines only if Macro is undefined.
ifndef(Macro) − Evaluates the following lines only if Macro is undefined.
else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated.
else − Allowed after an ifdef or ifndef statement. If the condition was false, the statements following else are evaluated.
endif − Marks the end of an ifdef or ifndef statement.
endif − Marks the end of an ifdef or ifndef statement.
When using the above statements, it should be used in the proper way as shown in the following program.
-ifdef(<FlagName>).

-define(...).
-else.
-define(...).
-endif.

 Print
 Add Notes
 Bookmark this page
Spot the difference between two images using Python

24 Feb, 2021
In this article, we will discuss how to spot differences between two given images using python. In order to perform this task, we will be using the ImageChops.difference() method in Pillow module.
Syntax: ImageChops.difference(image1, image2)
Parameters:
image1 first image
image2 second image
Return Value: It returns an Image.
Step 1: So, today we will be building this magical tool using python and that too with only 8 lines of code. But, before that, we have to install the pillow package of python using this command
pip install pillow
Step 2: Now, after installing this we have to get two images. Make sure that these two images are in the same folder where you’ve kept this python program or else you’ve to provide the path of these images.
Step 3: Call the ImageChops.difference() method with the two images as parameters.
Step 4: Generate the difference between the two images using the show() method.
Input:
Python3
# import modulefrom PIL import Image, ImageChops  # assign imagesimg1 = Image.open("1img.jpg")img2 = Image.open("2img.jpg")  # finding differencediff = ImageChops.difference(img1, img2)  # showing the differencediff.show()
Output:
Notice that the output image contains mostly black parts, but some portions of this image are colored. Those colored portions are the spotted differences between the two input images. In this case, the output image shows a total of 6 major differences. 
Python-pil
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Selenium – Find Button by text

03 Mar, 2021
In this article, let’s discuss how to find a button by text using selenium. See the below example to get an idea about the meaning of the finding button by text.
Example:
URL: https://html.com/tags/button/
We need to find the “CLICK ME!” button using the text “Click me!”.
Selenium: The selenium package is used to automate web browser interaction from Python. It is an open-source tool primarily used for testing. Run the following command in the terminal to install this library:
pip install selenium
Setup Web Drivers:
Web Driver is a package to interact with a Web Browser. You can install any Web Driver according to your browser choice. Install any one of them using the given links-
Here, we are going to use ChromeDriver.
Find xpath of the button:
Method 1: Using Inspect ElementRight Click on the element you are trying to find the xpath. Select the “Inspect” option. 
Right click on the highlighted area on the console. Go to Copy xpath 
Method 2: Using Chrome Extension to find xpath easily: We can easily find xpath of an element using a Chrome extension like SelectorGadget. 
Approach:
Import Selenium and time library
Set the Web Driver path with the location where you have downloaded the WebDriverExample- “C:\\chromedriver.exe”
Call driver.get() function to navigate to a particular URL.
Call time.sleep() function to wait for the driver to completely load the webpage.
Use driver.find_element_by_xpath() method to find the button using xpath.
Finding button by text-(i) Using normalize-space() method:driver.find_element_by_xpath(‘//button[normalize-space()=”Click me!”]’)(ii) Using text() method:driver.find_element_by_xpath(‘//button’)Note: It is recommended to use normalize-space() method because it trim the left and right side spaces. It is possible that there can be spaces present at the start or at the end of the target text.
Lastly close the driver using driver.close() function.
Implementation:
Python3
# Import Libraryfrom selenium import webdriverimport time  # set webdriver path here it may vary# Its the location where you have downloaded the ChromeDriverdriver = webdriver.Chrome(executable_path=r"C:\\chromedriver.exe")  # Get the target URLdriver.get('https://html.com/tags/button/')  # Wait for 5 seconds to load the webpage completelytime.sleep(5)  # Find the button using textdriver.find_element_by_xpath('//button[normalize-space()="Click me!"]').click()  time.sleep(5)  # Close the driverdriver.close()
Output:
Picked
Python Selenium-Exercises
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Ruby | Random uuid() function

17 Dec, 2019
Random#uuid() : uuid() is a Random class method which checks returns a random v4 UUID (Universally Unique IDentifier).
Syntax: Random.uuid()
Parameter: Random values
Return: a random v4 UUID (Universally Unique IDentifier).
Example #1 :
# Ruby code for Random.uuid() method  # loading libraryrequire 'securerandom'  # declaring Random valuedate_a = SecureRandom.uuid  # declaring Random valuedate_b = SecureRandom.uuid  # uuid valueputs "Random uuid form : #{date_a}\n\n"  puts "Random uuid form : #{date_b}\n\n"
Output :
Random uuid form : 219474f0-60c5-43b4-8e7f-f91b5c5e1f38

Random uuid form : d6800817-c27b-4651-8d98-dc12eec46706


Example #2 :
# Ruby code for Random.uuid() method  # loading libraryrequire 'securerandom'  # declaring Random valuedate_a = SecureRandom.uuid  # declaring Random valuedate_b = SecureRandom.uuid  # uuid valueputs "Random uuid form : #{date_a}\n\n"  puts "Random uuid form : #{date_b}\n\n"
Output :
Random uuid form : f74b43f6-8b9c-4cd1-aff2-177f517b77aa

Random uuid form : baba4612-6931-46a0-aa8b-7a105fd2f194


Ruby Random-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a pressed effect on button click in CSS?

30 Jul, 2021
In this tutorial, we are going to learn how to add a pressed effect on a button using CSS. This effect is a part of modern UI design and is used on many websites. This effect allows the user to experience an interaction with the button element as compared to the normal behavior.
We’ll take advantage of the active pseudo class. This class is added to an HTML element automatically when it is clicked.
Method 1:We can use CSS transform property to add a pressed effect on the button when it is active. CSS transform property allows us to scale, rotate, move and skew an element.
Example 1:
<!DOCTYPE html><html>  <head>    <style>        /* Adding some basic styling to button */                  .btn {            text-decoration: none;            border: none;            padding: 12px 40px;            font-size: 16px;            background-color: green;            color: #fff;            border-radius: 5px;            box-shadow: 7px 6px 28px 1px rgba(0, 0, 0, 0.24);            cursor: pointer;            outline: none;            transition: 0.2s all;        }        /* Adding transformation when the button is active */                  .btn:active {            transform: scale(0.98);            /* Scaling button to 0.98 to its original size */            box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);            /* Lowering the shadow */        }    </style></head>  <body>      <!-- Button with a class 'btn' -->    <button class="btn">Button</button>  </body>  </html>
Output:
Method 2:For this method, we can play with the translate function in CSS. We’ll use translateY(length) function on active state of button. The translateY() function moves an element on y-axis to a given length (in px).
Example 2:
<!DOCTYPE html><html>  <head>    <style>        /* Adding basic styling to a button */                  .btn {            padding: 15px 40px;            font-size: 16px;            text-align: center;            cursor: pointer;            outline: none;            color: #fff;            background-color: green;            border: none;            border-radius: 5px;            box-shadow: box-shadow:              7px 6px 28px 1px rgba(0, 0, 0, 0.24);        }        /* Adding styles on 'active' state */                  .btn:active {            box-shadow: box-shadow:              7px 6px 28px 1px rgba(0, 0, 0, 0.24);            transform: translateY(4px);            /* Moving button 4px to y-axis */        }    </style></head>  <body>      <button class="btn">Click Me</button>  </body>  </html>
Output:
You can play with other methods when the active pseudo-class is active to create your own effects when the button is clicked.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
CSS-Misc
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
pstree - Unix, Linux Command

pstree visually merges identical branches by putting them in square
brackets and prefixing them with the repetition count, e.g.


    init-+-getty
         |-getty
         |-getty
         ‘-getty



    init-+-getty
         |-getty
         |-getty
         ‘-getty




    init---4*[getty]



    init---4*[getty]






Child threads of a process are found under the parent process and are shown
with the process name in curly braces, e.g.


    icecast2---13*[{icecast2}]



    icecast2---13*[{icecast2}]




If pstree is called as pstree.x11 then it will prompt the user
at the end of the line to press return and will not return until that
has happened. This is useful for when pstree is run in a xterminal.



/proc   location of the proc file system
How to launch a program using C++ program?

Here we will see how to start some third-party application like notepad or anything using C++ program. This program is very simple, we can use command prompt command to do this task.
We will pass the application name inside the system() function. This will open it accordingly.
#include <iostream>
using namespace std;
int main() {
   cout >> "Opening Nodepad.exe" >> endl;
   system("notepad.exe");
}
Difference between tilde ( ~ ) and caret ( ^ ) in package.json

25 Mar, 2022
When we open our package.json file and search for dependency property and in there we find the packages that are listed as a nested object of the dependency property package-name:package-version. Now look at the package version, we find some numbers separated by three dots (e.g. 2.6.2). 
NPM versions are written using three dots separated numbers the first number from the left shows the major release and the second number from the left shows the minor release and the third number shows the patch release of the package.
Syntax: The syntax of the npm version looks like the following.
Major.Minor.Patch
Tilde (~) notation: It is used to match the most recent patch version. Tilde ~ notation freezes the major version and minor version. As we know patch updates are bug fixes that’s why we can say ~ notation allows us to automatically accept bug fixes.
Example: The ~1.2.0 will update all the future patch updates. We have to write just ~1.2.0 and all the next patch update dependencies. For example, 1.2.1, 1.2.2, 1.2.5...............1.2.x.
Note: Patch updates are very small security changes in a package that is why the ~version is approximately equivalent to the version.
Caret (^) notation: It is used for automatically updating the minor updates along with patch updates. 
Example: The ^1.2.4 will update all the future Minor and patch updates, for example, ^1.2.4 will automatically change the dependency to 1.x.x if any update occurs. 
Using caret notation it is important to look at our code regularly if it is compatible with the newest version or not.
Difference between tilde (~) and caret (^) in package.json:
Tilde(~) notation
Caret(^) notation
References: https://docs.npmjs.com/about-semantic-versioning
zinedinegithub
Node-npm
Node.js
NodeJS-Questions
Difference Between
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Compile-time and Run-time Polymorphism in Java
Difference between Internal and External fragmentation
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
C++ Program to Find the GCD and LCM of n Numbers

This is the code to find out the GCD and LCM of n numbers. The GCD or Greatest Common Divisor of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. GCD is also known as Greatest Common Factor.
The least common multiple (LCM) of two numbers is the smallest number (not zero) that is a multiple of both numbers.
Begin
   Take two numbers as input
   Call the function gcd() two find out gcd of n numbers
   Call the function lcm() two find out lcm of n numbers
   gcd(number1, number2)
   Declare r, a, b
   Assign r=0
   a = (number1 greater than number2)? number1: number2
   b = (number1 less than number2)? number1: number2
   r = b
   While (a mod b not equal to 0)
      Do
         r = a mod b
         a=b
         b=r
      Return r
   Done
   lcm(number1, number2)
   Declare a
   a=(number1 greater than number2)?number1:number2
   While(true) do
   If
      (a mod number1 == 0 and a number2 == 0)
      Return a
      Increment a
   Done
End
#include<iostream>
using namespace std;
int gcd(int m, int n) {
   int r = 0, a, b;
   a = (m > n) ? m : n;
   b = (m < n) ? m : n;
   r = b;
   while (a % b != 0) {
      r = a % b;
      a = b;
      b = r;
   }
   return r;
}
int lcm(int m, int n) {
   int a;
   a = (m > n) ? m: n;
   while (true) {
      if (a % m == 0 && a % n == 0)
         return a;
         ++a;
   }
}
int main(int argc, char **argv) {
   cout << "Enter the two numbers: ";
   int m, n;
   cin >> m >> n;
   cout << "The GCD of two numbers is: " << gcd(m, n) << endl;
   cout << "The LCM of two numbers is: " << lcm(m, n) << endl;
   return 0;
}
Enter the two numbers:
7
6
The GCD of two numbers is: 1
The LCM of two numbers is: 42
Metasploit - Exploit

After vulnerability scanning and vulnerability validation, we have to run and test some scripts (called exploits) in order to gain access to a machine and do what we are planning to do.
We have several methods to use exploits. The first and foremost method is to use Armitage GUI which will connect with Metasploit to perform automated exploit testing called HAIL MARY. Let’s see how it works.
Open Kali distribution → Application → Exploit Tools → Armitage.
Next, go to Attacks → Hail Mary and click Yes.
You will see the following screen which would show all the exploits that are being tested.
Next, you will see the icon of the exploitable system (i.e., the system on which the exploit worked) will turn red in color with a thunderstorm pattern over it. At the console, you will see which exploit was successful, with its respective session ID.
Now you can interact with the machine.
The second way (and probably a little professional way) to use an Exploit is by the Command Prompt.
From the Vulnerability Scanner, we found that the Linux machine that we have for test is vulnerable to FTP service. Now we will use an exploit that can work for us. The command is −
msf > use “exploit path”  

Next, use the following command in order to see what parameters you have to set to make it functional.
msf > show options

This exploit shows that we have to set RHOST “target IP”
Next, use the commands −
msf > set RHOST 192.168.1.101   
msf > set RPORT 21

Next, use the command −
msf > run

If the exploit is successful, then you will see one session opened, as shown in the following screenshot.
Now, you can interact with this system.
 Print
 Add Notes
 Bookmark this page
Sort an array according to the order defined by another array in C++

In this section we will see another sorting problem. Suppose we have two arrays A1 and A2. We have to sort A1 in such a way that the relative order among the elements will be same as those are in A2. If some elements are not present in A2, then they will be appended after the sorted elements. Suppose A1 and A2 are the following −
A1 = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8}
A2 = {2, 1, 8, 3}
After the sorting A1 will be like below −
A1 = {2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9}
To solve this problem, we will create our custom compare method. That method will compare and place the elements in the array. The comparison logic will be like below −
if num1 and num2 both are in A2, then number with the lower index in A2 will be treated as smaller than the other number
If either num1 or num2 is present in A2, then that number will be treated as smaller, than the other, which is does not present in A2.
If both are not present in A2, then natural ordering will be used.
compare(num1, num2):
Begin
   if both num1 and num2 are present in A2, then
      return index of num1 – index of num2
   else if num1 is not in A2, then
      return -1
   else if num2 is not in A1, then
      return 1
   else
      num1 – num2
End
 Live Demo
#include<iostream>
#include<algorithm>
using namespace std;
int size = 5;
int A2[5]; //global A2 will be used in compare function
int search_index(int key){
   int index = 0;
   for(int i = 0; i < size; i++){
      if(A2[i] == key)
      return i;
   }
   return -1;
}
int compare(const void *num1, const void *num2){
   int index1 = search_index(*(int*)num1);
   int index2 = search_index(*(int*)num2);
   if (index1 != -1 && index2 != -1)
   return index1 - index2;
   else if (index1 != -1)
      return -1;
   else if (index2 != -1)
      return 1;
   else
      return (*(int*)num1 - *(int*)num2);
}
main(){
   int data[] = {2, 1, 2, 1, 7, 5, 9, 3, 8, 6, 8};
   int n = sizeof(data)/sizeof(data[0]);
   int a2[] = {2, 1, 8, 3};
   int n2 = sizeof(a2)/sizeof(a2[0]);
   for(int i = 0; i<n2; i++){
      A2[i] = a2[i];
   }
   qsort(data, n, sizeof(int), compare);
   for(int i = 0; i<n; i++){
      cout << data[i] << " ";
   }
}
2 2 1 1 8 8 3 5 6 7 9
How can Matplotlib be used to create 3 dimensional contour plot using Python?

Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively.
Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on.
It is written in Python. It is created using Numpy, which is the Numerical Python package in Python.
Python can be installed on Windows using the below command −
pip install matplotlib
The dependencies of Matplotlib are −
Python ( greater than or equal to version 3.4)
NumPy
Setuptools
Pyparsing
Libpng
Pytz
Free type
Six
Cycler
Dateutil
Three dimensional plots are created to view the x−, y− and z−axes of the data points. It can also be used to understand how the gradient descent function works, and to find the optimal values for coefficients for an algorithm.
Let us understand how Matplotlib can be used to create three−dimensional contour plot −
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
def fun(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(−5, 5, 30)
y = np.linspace(−5, 5, 30)

X, Y = np.meshgrid(x, y)
Z = fun (X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_ylabel("Y−axis")
ax.set_xlabel("X−axis")
ax.set_zlabel("Z−axis")

ax.set_title('A sample 3D contour plot')
plt.show()
The required packages are imported and its alias is defined for ease of use.
The required packages are imported and its alias is defined for ease of use.
A function ‘fun’ is created that generates data using the ‘sin’ function using two variables.
A function ‘fun’ is created that generates data using the ‘sin’ function using two variables.
The data values are created using the NumPy library.
The data values are created using the NumPy library.
An empty figure is created using the ‘figure’ function.
An empty figure is created using the ‘figure’ function.
The ‘axes’ function is used to create an axis to plot the graph.
The ‘axes’ function is used to create an axis to plot the graph.
The ‘contour3D’ is used to specify that a 3−dimensional contour plot is being visualized with the data that has been created.
The ‘contour3D’ is used to specify that a 3−dimensional contour plot is being visualized with the data that has been created.
The set_xlabel, set_ylabel, ‘z_label’ and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis, Z-axis and title.
The set_xlabel, set_ylabel, ‘z_label’ and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis, Z-axis and title.
It is shown on the console using the ‘show’ function.
It is shown on the console using the ‘show’ function.
File lastModified() method in Java with Examples - GeeksforGeeks

28 Jan, 2019
The lastModified() function is a part of File class in Java . This function returns the time denoted by the this abstract pathname was last modified.The function returns long value measured in milliseconds, representing the time the file was last modified else returns 0L if the file does not exists or if an exception occurs.
Function signature:
public long lastModified()
Syntax:
long valr = file.lastModified();
Parameters: This method does not accept any parameter.
Return TypeThis function returns long data type representing the time the file was last modified or 0L if the file does not exist.
Exception: This method throws Security Exception if the write access to the file is denied
Below programs illustrates the use of lastModified() function:
Example 1: The file “F:\\program.txt” is a existing file in F: Directory.
// Java program to demonstrate// lastModified() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          // Get the file        File f = new File("F:\\program.txt");          // Get the last modified time of the file        System.out.println("Last modified: "                           + f.lastModified());    }}
Output:
Last modified: 1542654265978
Example 2: The file “F:\\program1.txt” does not exist
// Java program to demonstrate// lastModified() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          // Get the file        File f = new File("F:\\program.txt");          // Get the last modified time of the file        System.out.println("Last modified: "                           + f.lastModified());    }}
Output:
Last modified: 0
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
SHA-1 Hash
Java Program to Convert String to String Array
Modulo or Remainder Operator in Java
How to Replace a Element in Java ArrayList?
How to convert Date to String in Java
How to find the less than probability using normal distribution in R?

The less than probability using normal distribution is the cumulative probability which can be found by using cumulative distribution function of the normal distribution. In R, we have pnorm function that directly calculates the less than probability for a normally distributed random variable that takes Z score, mean and standard deviation.
Live Demo
pnorm(0.95,1,0)
pnorm(0.95,0,1)
pnorm(0.10,0,1)
pnorm(0.10,1,5)
pnorm(0.10,1,50)
pnorm(0.10,25,50)
pnorm(0.12,25,50)
pnorm(0.12,2,0.004)
pnorm(0.12,2,0.5)
pnorm(1,2,0.5)
pnorm(12,20,3)
pnorm(12,12,3)
pnorm(12,15,3)
pnorm(200,15,3)
pnorm(200,201,3)
pnorm(200,201,5)
pnorm(20,25,5)
[1] 0
[1] 0.8289439
[1] 0.5398278
[1] 0.4285763
[1] 0.4928194
[1] 0.309242
[1] 0.309383
[1] 0
[1] 8.495668e-05
[1] 0.02275013
[1] 0.003830381
[1] 0.5
[1] 0.1586553
[1] 1
[1] 0.3694413
[1] 0.4207403
[1] 0.1586553
Sibling of a list element in JavaScript?

To find the sibling of a list element javascript has provided a method called node.nextSibling. If we know any member of a list we can find its sibling. Let's discuss it in a nutshell.
node.nextSibling;
In the following example, there are 3 list elements. Using the nextSibling property the sibling of the first element is found out and displayed the result in the output.
Live Demo
<html>
<body>
<ul><li id="item1">Tesla</li><li id="item2">Spacex</li><li id="item3">Solarcity</li></ul>
<p id="next"></p>
<script>
var x = document.getElementById("item1").nextSibling.innerHTML;
document.getElementById("next").innerHTML = "The sibling element is "+" "+x;
</script>
</body>
</html>
Tesla
Spacex
Solarcity
The sibling element is Spacex
In the following example, there are 3 list elements. Using the nextSibling property the sibling of the second element is found out and displayed the result in the output. The sibling element is nothing but the next element of the target element.
Live Demo
<html>
<body>
<ul><li id="item1">Tesla</li><li id="item2">Spacex</li><li id="item3">Solarcity</li></ul>
<p id="next"></p>
<script>
var x = document.getElementById("item2").nextSibling.innerHTML;
document.getElementById("next").innerHTML = "The sibling element is "+" "+x;
</script>
</body>
</html>
Tesla
Spacex
Solarcity
The sibling element is Solarcity