code-rag-bench/online-tutorials huggingface dataset:
reset_actions method – Action Chains in Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around reset_actions method on Action Chains in Python Selenium. reset_actions method clears actions that are already stored locally and on the remote end. It is one of most used methods, since after some operation, action instance needs to be reset to perform next operation.
Syntax –
reset_actions
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")another_element = driver.find_element_by_name("passwd")
Now one can use reset_actions method as an Action chain as below –
action.click(on_element = element)
action.reset_actions()
action.click(on_element = another_element)

To demonstrate, reset_actions method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # click the itemaction.click(on_element = element)  # perform the operationaction.perform()  # get another element another_element = driver.find_element_by_link_text("Courses")  # reset the actionaction.reset_actions()  # click the itemaction.click(on_element = another_element)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between @Bean and @Component annotation in Spring.

Spring supports multiple types annotations such as @Component,@Controller,@service @Repository and @Bean. All theses can be found under the org.springframework.stereotype package.
When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @componentScan) each class and inject the instance of the classes to the IOC container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean.
@Component
public class Pizza{

   ........


}
@Configuration
class AppConfiguration{

   @Bean
   public User getUse(){
      return new User();
   }
}
How to check whether a Button is clicked with JavaScript?

Following is the code for checking whether a button is clicked using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body onbeforeunload="return pageUnload()">
<h1>Checking whether a Button is clicked using JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to check if the button is clicked</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let clickCount = 0;
   BtnEle.addEventListener("click", () => {
      clickCount++;
      resEle.innerHTML =
      "The button has been clicked " + clickCount + " times ";
   });
</script>
</body>
</html>
On clicking the button 5 times −
Perl push Function

This function pushes the values in LIST onto the end of the list ARRAY. Used with pop to implement stacks.
Following is the simple syntax for this function −
push ARRAY, LIST

This function returns number of elements in new array.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$, = ",";
@array = ( 1, 2 );
print "Before pushing elements  @array \n";
push(@array, (3, 4, 5));
print "After pushing elements  @array \n";
When above code is executed, it produces the following result −
Before pushing elements  1 2
After pushing elements  1 2 3 4 5
SimpleDateFormat toPattern() Method in Java with Examples

05 Feb, 2021
The toPattern() Method of SimpleDateFormat class is used to return the pattern of the date format.
Syntax:  
public String toPattern()
Parameters: The method does not take any parameters.
Return Value: The method returns the pattern string describing this Date format.
Below programs illustrate the working of toPattern() Method of SimpleDateFormat:
Example 1:  
Java
// Java code to illustrate toPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo {    public static void main(String[] args)        throws InterruptedException    {        SimpleDateFormat SDformat            = new SimpleDateFormat();         // Initializing Calendar object        Calendar cal = Calendar.getInstance();         // Getting the Current Date        String Todaysdate            = SDformat.format(cal.getTime());         // Displaying the date        System.out.println("Current Date: "                           + Todaysdate);         // Using toPattern() method        // to Print the Date Pattern        System.out.println("The Date Pattern- "                           + SDformat.toPattern());    }}
Current Date: 1/29/19 6:05 AM
The Date Pattern- M/d/yy h:mm a
 
arorakashish0911
Java-Functions
Java-SimpleDateFormat
Java-text package
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
Replacing Element in Java Vector - GeeksforGeeks

11 Dec, 2020
To replace an element in Java Vector, set() method of java.util.Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of a Vector is zero-based. So, to replace the first element, 0 should be the index passed as parameter.
Declaration:
 public Object set(int index, Object element)
Return Value: 
The element which is at the specified index
Exception Throws:
IndexOutOfBoundsException 
when the index is out of range 
i.e, index < 0 or index >= size()
Implementation:
Java
// Replacing Element in Java Vectorimport java.util.Vector;public class Sias {    public static void main(String args[])    {        try {              // create a instance vector            Vector<Integer> vector = new Vector<>();              // insert the values in vector            vector.add(1);            vector.add(2);            vector.add(3);            vector.add(4);            vector.add(5);              // display the vector            System.out.println("original vector : "                               + vector);              // call set() and replace 2 index value            vector.set(2, 10);              // display vector after replacing value            System.out.println("after replace the value : "                               + vector);            // call set() and replace 9th index value            // which is exception as arrayoutofbound            vector.set(9, 91);              // display vector after replacing value            System.out.println("after replace the value : "                               + vector);        }        catch (Exception e) {            System.out.println(e);        }    }}
original vector : [1, 2, 3, 4, 5]
after replace the value : [1, 2, 10, 4, 5]
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9

Time Complexity: O(n), where n is the length of the vector
Java-Vector
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
A Problem in Many Binary Search Implementations - GeeksforGeeks

15 Dec, 2016
Consider the following C implementation of Binary Search function, is there anything wrong in this?
// A iterative binary search function. It returns location of x in// given array arr[l..r] if present, otherwise -1int binarySearch(int arr[], int l, int r, int x){    while (l <= r)    {        // find index of middle element        int m = (l+r)/2;          // Check if x is present at mid        if (arr[m] == x) return m;          // If x greater, ignore left half        if (arr[m] < x) l = m + 1;          // If x is smaller, ignore right half        else r = m - 1;    }      // if we reach here, then element was not present    return -1;}
The above looks fine except one subtle thing, the expression “m = (l+r)/2”. It fails for large values of l and r. Specifically, it fails if the sum of low and high is greater than the maximum positive int value (231 – 1). The sum overflows to a negative value, and the value stays negative when divided by two. In C this causes an array index out of bounds with unpredictable results.
What is the way to resolve this problem?Following is one way:
        int mid = low + ((high - low) / 2); 
Probably faster, and arguably as clear is (works only in Java, refer this):
        int mid = (low + high) >>> 1; 
In C and C++ (where you don’t have the >>> operator), you can do this:
        mid = ((unsigned int)low + (unsigned int)high)) >> 1 
The similar problem appears in Merge Sort as well.
The above content is taken from google reasearch blog.
Please refer this as well, it points out that the above solutions may not always work.
The above problem occurs when array length is 230 or greater and the search repeatedly moves to second half of the array. This much size of array is not likely to appear most of the time. For example, when we try the below program with 32 bit Code Blocks compiler, we get compiler error.
int main(){    int arr[1<<30];    return 0;}
Output:
error: size of array 'arr' is too large
Even when we try boolean array, the program compiles fine, but crashes when run in Windows 7.0 and Code Blocks 32 bit compiler
#include <stdbool.h>int main(){    bool arr[1<<30];    return 0;}
Output: No compiler error, but crashes at run time.
Sources:http://googleresearch.blogspot.in/2006/06/extra-extra-read-all-about-it-nearly.htmlhttp://locklessinc.com/articles/binary_search/
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Binary Search
Searching
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search an element in a sorted and rotated array
Given an array of size n and a number k, find all elements that appear more than n/k times
k largest(or smallest) elements in an array
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array
Most frequent element in an array
Best First Search (Informed Search)
Draw Diamond shape using Turtle graphics in Python - GeeksforGeeks

11 Jun, 2021
In this article, we are going to learn how to draw the shape of a Diamond using turtle graphics in Python.
Turtle graphics:
forward(length): moves the pen in the forward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
Approach:
Import the turtle modules.
Define an instance for the turtle.
First, make the bigger triangle
Then make three lines inside the bigger triangle
Then make 4 small triangles
Then make one line above these four triangles
Below is the Python implementation of the above approach:
Python3
# python program# import for turtle moduleimport turtle # defining instance of turtlepen = turtle.Turtle()wn = turtle.Screen() # this is for bigger trianglepen.left(60)pen.forward(200)pen.left(120)pen.forward(200)pen.left(120)pen.forward(200)pen.left(150) # this for making three lines# inside the bigger trianglepen.forward(174)pen.backward(174)pen.left(16.5)pen.forward(180)pen.backward(180)pen.right(31.5)pen.forward(180)pen.right(75) # this is for making upper triangle1pen.forward(53)pen.left(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle2pen.right(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle3                   pen.right(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle1pen.right(120)pen.forward(50)pen.left(120)pen.forward(50)pen.left(180)pen.forward(50) # this is for making line above all 4 small trianglepen.left(300)pen.forward(160)
Output:
ruhelaa48
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Lodash _.isString() Method - GeeksforGeeks

05 Sep, 2020
The _.isString() method is used to find whether the given value is a string object or not. It returns True if the given value is a string. Otherwise, it returns false.  
Syntax:
_.isString(value)

Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to check.
Return Value: This method returns true if the value is a string, else false.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library  const _ = require("lodash");        // Use of _.isString() method console.log(_.isString('GeeksforGeeks')); console.log(_.isString(true)); 
Output:
true
false

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");        // Use of _.isString() method console.log(_.isString('123')); console.log(_.isString(123)); console.log(_.isString("0.123")); 
 Output:
true
false
true

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to get the length of a string in bytes in JavaScript ? - GeeksforGeeks

01 Apr, 2021
Task: To find the size of the given string in bytes.
Example:
Input: "GeeksForGeeks"
Output: 13 bytes

Input: 20€
Output: 5 bytes

Input: "????"
Output: 4 bytes
To achieve this we have two ways the first one is using the Blob API and the second is Buffer API, the first one works with the browser, and the second works with the Node.js environment. blob object is simply a group of bytes that holds the data stored in a file. To read the bytes of a string using blog we create a new instance of Blob object then we pass the string inside it and by using the size property we can get the bytes of a string.
Example 1: Using Blob API.
Javascript
<script>const len = (str) => {    // Creating new Blob object and passing string into it   // inside square brackets and then   // by using size property storin the size   // inside the size variable  let size = new Blob([str]).size;  return size;}   console.log(len("Geeksforgeeks"))console.log(len("true"))console.log(len("false"))console.log(len("12345"))console.log(len("20€"))console.log(len("????"))</script>
Output:
13
4
5
5
5
4
Example 2: Using Buffer API. Now there is another way to achieve this in NodeJS using Buffer. So first create the Buffer object and then pass the string inside it and using the length property you can get the size of the string
Javascript
<script>const len = (str) => {  let size = Buffer.from(str).length;  return size;}   console.log(len("Geeksforgeeks"))console.log(len("true"))console.log(len("false"))console.log(len("12345"))console.log(len("20€"))console.log(len("????"))</script>
Output:
13
4
5
5
5
4
JavaScript-Questions
NodeJS-Questions
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
Python | Convert tuple to float value - GeeksforGeeks

11 Nov, 2019
Sometimes, while working with tuple, we can have a problem in which, we need to convert a tuple to floating-point number in which first element represents integer part and next element represents a decimal part. Let’s discuss certain way in which this can be achieved.
Method : Using join() + float() + str() + generator expression
The combination of above functionalities can solve this problem. In this, we 1st convert the tuple elements into a string, then join them and convert them to desired integer.
# Python3 code to demonstrate working of# Convert tuple to float# using join() + float() + str() + generator expression  # initialize tupletest_tup = (4, 56)  # printing original tuple print("The original tuple : " + str(test_tup))  # Convert tuple to float# using join() + float() + str() + generator expressionres = float('.'.join(str(ele) for ele in test_tup))  # printing resultprint("The float after conversion from tuple is : " + str(res))
The original tuple : (4, 56)
The float after conversion from tuple is : 4.56

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
How to rotate a text canvas using Fabric.js ? - GeeksforGeeks

04 Sep, 2021
In this article, we are going to see how to rotate a text canvas using FabricJS. The canvas means text written is movable and can be stretched according to requirement. Further, the text itself cannot be edited like a textbox.Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and use the angle property to rotate the text to the required angle and render the Canvas on the Text as given in the example below. 
Syntax:  
fabric.Text(text, angle: Number); 
Parameters: This function accepts two parameters as mentioned above and described below:  
text: It specifies the text to be written.
options: It specifies the additional options to be applied and we are using the angle option for this example.
Program: This example uses FabricJS to create simple editable text canvas. 
html
<!DOCTYPE html><html> <head>    <title>        How to rotate a text canvas using Fabric.js?    </title>     <!-- Loading the FabricJS library -->    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">     </script></head> <body>    <canvas id="canvas" width="600" height="200"            style="border:1px solid #000000;">    </canvas>     <script>         // Create a new instance of Canvas        var canvas = new fabric.Canvas("canvas");         // Create a new Textbox instance        var text = new fabric.Text('GeeksforGeeks', {            angle: 10        });         // Render the Textbox on Canvas        canvas.add(text);    </script></body> </html>
Output: 
sagartomar9927
Fabric.js
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
MySQL update datetime column values and add 10 years 3 months 22 days and 10 hours, 30 minutes to existing data?

For this, you can use INTERVAL in MySQL. Let us first create a table −
mysql> create table DemoTable1509
   -> (
   -> ArrivalTime datetime
   -> );
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1509 values('2018-01-21 10:20:30');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1509 values('2019-04-01 11:00:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1509 values('2015-12-12 05:45:20');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1509;
This will produce the following output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2018-01-21 10:20:30 |
| 2019-04-01 11:00:00 |
| 2015-12-12 05:45:20 |
+---------------------+
3 rows in set (0.00 sec)
Here is the query to MySQL update datetime column and add 10 years 3 months 22 days and 10 hours, 30 minutes to existing data −
mysql> update DemoTable1509
    -> set ArrivalTime=ArrivalTime+interval 10 year + interval 3 month +interval 22 day+interval 10 hour+interval 30 minute;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3  Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1509;
This will produce the following output −
+---------------------+
| ArrivalTime         |
+---------------------+
| 2028-05-13 20:50:30 |
| 2029-07-23 21:30:00 |
| 2026-04-03 16:15:20 |
+---------------------+
3 rows in set (0.00 sec)
Find duplicate column values in MySQL and display them

For this, use GROUP BY HAVING clause. Let us first create a table −
mysql> create table DemoTable1858
     (
     ModelNumber varchar(50)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1858 values('Audi A4');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi A6');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi A4');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi Q5');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi R8');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi Q5');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1858;
This will produce the following output −
+-------------+
| ModelNumber |
+-------------+
| Audi A4     |
| Audi A6     |
| Audi A4     |
| Audi Q5     |
| Audi R8     |
| Audi Q5     |
+-------------+
6 rows in set (0.00 sec)
Here is the query to find duplicate column value in MySQL −
mysql> select ModelNumber from DemoTable1858
     group by ModelNumber
     having count(ModelNumber) >=2;
This will produce the following output −
+-------------+
| ModelNumber |
+-------------+
| Audi A4     |
| Audi Q5     |
+-------------+
2 rows in set (0.00 sec)
PyTorch – How to convert an image to grayscale?

To convert an image to grayscale, we apply Grayscale() transformation. It's one of the transforms provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types manipulations on the image data.
Grayscale() transformation accepts both PIL and tensor images or a batch of tensor images. A tensor image is a PyTorch Tensor with shape [3, H, W], where H is the image height and W is the image width. A batch of tensor images is also a torch tensor with [B, 3, H, W]. B is the number of images in the batch.
torchvision.transforms.Grayscale()(img)
It returns a grayscale image.
We could use the following steps to convert an image to grayscale −
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them.
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them.
import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
Read the input image. The input image is a PIL image or a torch tensor.
Read the input image. The input image is a PIL image or a torch tensor.
img = Image.open('laptop.jpg')
Define a transform to convert the original input image to grayscale.
Define a transform to convert the original input image to grayscale.
transform = transforms.Grayscale()
Apply the above defined transform on the input image convert it to grayscale.
Apply the above defined transform on the input image convert it to grayscale.
img = transform(img)
Visualize the grayscaled image.
Visualize the grayscaled image.
img.show()
The following image is used as the input in both the examples.
The following Python3 program converts the input PIL image to grayscale.
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('laptop.jpg')

# define a transform to convert the image to grayscale
transform = transforms.Grayscale()

# apply the above transform on the image
img = transform(img)

# dispaly the image
img.show()

# num of output channels = 1
print(img.mode)
It will produce the following output −
Note that the mode of the grayscale image is L. The grayscale image has a single
channel.
The following Python3 program shows how to convert an input image to grayscale.
# Python program to convert an image to grayscale
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image

# Read the image
img = Image.open('laptop.jpg')

# define a transform to convert the image to grayscale
transform = transforms.Grayscale(3)

# apply the above transform on the image
img = transform(img)

# display the image
img.show()

# the num of output channels =3, R=G=B, but Gray image
print(img.mode)
It will produce the following output −
Note that the mode of output gray image is RGB. It has three channels, Red, Green, and Blue, but it's a grayscale image.
Convert MySQL date format from yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss ?

Let us first create a table −
mysql> create table DemoTable668(JoiningDate varchar(200));
Query OK, 0 rows affected (0.97 sec)
Insert some records in the table using insert command. We have inserted date in the format yyyy-mm-ddThh:mm:ss.sssZ −
mysql> insert into DemoTable668 values('2001-01-10T06:20:00.000Z');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable668 values('2019-07-20T04:00:00.000Z');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable668 values('2016-02-12T05:10:50.000Z');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable668;
This will produce the following output −
+--------------------------+
| JoiningDate              |
+--------------------------+
| 2001-01-10T06:20:00.000Z |
| 2019-07-20T04:00:00.000Z |
| 2016-02-12T05:10:50.000Z |
+--------------------------+
3 rows in set (0.00 sec)
Following is the query to convert the date format from yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss −
mysql> update DemoTable668
   SET JoiningDate = DATE_FORMAT(STR_TO_DATE(JoiningDate,'%Y-%m-%dT%H:%i:%s.000Z'),'%Y-%m-%d %H:%i:%s');
Query OK, 3 rows affected (0.11 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable668;
This will produce the following output −
+---------------------+
| JoiningDate         |
+---------------------+
| 2001-01-10 06:20:00 |
| 2019-07-20 04:00:00 |
| 2016-02-12 05:10:50 |
+---------------------+
3 rows in set (0.00 sec)
Data Structures | Misc | Question 6 - GeeksforGeeks

28 Jun, 2021
The most appropriate matching for the following pairs
X: depth first search            1: heap
Y: breadth-first search          2: queue
Z: sorting                       3: stack
is (GATE CS 2000):
(A) X—1 Y—2 Z-3(B) X—3 Y—1 Z-2(C) X—3 Y—2 Z-1(D) X—2 Y—3 Z-1Answer: (C)Explanation: Stack is used for Depth first SearchQueue is used for Breadth First SearchHeap is used for sortingQuiz of this Question
Data Structures
Data Structures-Misc
Misc
Data Structures
Misc
Data Structures
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 11
Data Structures | Stack | Question 4
Advantages of vector over array in C++
Program to create Custom Vector Class in C++
Multilevel Linked List
5 Methods to Check for NaN values in in Python | by Abhijith Chandradas | Towards Data Science

NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float.
NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.
Finding and dealing with NaN within an array, series or dataframe is easy. However, identifying a stand alone NaN value is tricky. In this article I explain five methods to deal with NaN in python. The first three methods involves in-built functions from libraries. The last two relies on properties of NaN for finding NaN values.
isna() in pandas library can be used to check if the value is null/NaN. It will return True if the value is NaN/null.
import pandas as pdx = float("nan")print(f"It's pd.isna  : {pd.isna(x)}")OutputIt's pd.isna  : True
isnan() in numpy library can be used to check if the value is null/NaN. It is similar to isna() in pandas.
import numpy as npx = float("nan")print(f"It's np.isnan  : {np.isnan(x)}")OutputIt's np.isnan  : True
Math library provides has built-in mathematical functions. The library is applicable to all real numbers. cmath library can be used if dealing with complex numbers.Math library has built in function isnan() to check null/NaN values.
import mathx = float("nan")print(f"It's math.isnan : {math.isnan(x)}")OutputIt's math.isnan  : True
When I started my career working with big IT company, I had to undergo a training for the first month. The trainer, when introducing the concept of NaN values mentioned that they are like aliens we know nothing about. These aliens are constantly shapeshifting, and hence we cannot compare NaN value against itself.The most common method to check for NaN values is to check if the variable is equal to itself. If it is not, then it must be NaN value.
def isNaN(num):    return num!= numx=float("nan")isNaN(x)OutputTrue
Another property of NaN which can be used to check for NaN is the range. All floating point values fall within the range of minus infinity to infinity.
infinity < any number< infinity
However, NaN values does not come within this range. Hence, NaN can be identified if the value does not fall within the range from minus infinity to infinity.
This can be implemented as below:
def isNaN(num):    if float('-inf') < float(num) < float('inf'):        return False     else:        return Truex=float("nan")isNaN(x)OutputTrue
I hope you have found the above article helpful. I am sure there would be many other techniques to check for NaN values based on various other logics. Please share the other methods you have come across to check for NaN/ Null values.
Cheers!
I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.
Explain rename operation in relational algebra (DBMS)?

Query is a question or requesting information. Query language is a language which is used to retrieve information from a database.
Query language is divided into two types −
Procedural language
Procedural language
Non-procedural language
Non-procedural language
Information is retrieved from the database by specifying the sequence of operations to be performed.
For Example − Relational algebra.
Structure Query language (SQL) is based on relational algebra.
Relational algebra consists of a set of operations that take one or two relations as an input and produces a new relation as output.
The different types of relational algebra operations are as follows −
Select operation
Select operation
Project operation
Project operation
Rename operation
Rename operation
Union operation
Union operation
Intersection operation
Intersection operation
Difference operation
Difference operation
Cartesian product operation
Cartesian product operation
Join operation
Join operation
Division operation
Division operation
Select, project, rename comes under unary operation (operate on one table).
It is used to assign a new name to a relation and is denoted by ρ (rho).
ρnewname (tablename or expression)
Consider the student table given below −
The student table is renamed with newstudent with the help of the following command −
ρnewstudent (student)
The name, branch column of student table are renamed and newbranch respectively
ρnewname,newbranch(∏name,branch( student))
Binary operations are applied on two compatible relations.
Two relations R1, R2 are to be compatible if they are of the same degree and the domains of corresponding attributes are the same.
The Rho in DDL used for name of relation and in DML used for name of attributes.
         SQL                      Old name                   New name
Renaming can be used by three methods, which are as follows −
Changing name of the relation.
Changing name of the relation.
Changing name of the attribute.
Changing name of the attribute.
Changing both.
Changing both.
Count number of rows in a MongoDB collection

To count number of documents, use count() in MongoDB. Let us create a collection with documents −
> db.demo664.insertOne({_id:1,ClientName:"Chris"});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo664.insertOne({_id:2,ClientName:"Bob"});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo664.insertOne({_id:3,ClientName:"Sam"});
{ "acknowledged" : true, "insertedId" : 3 }
> db.demo664.insertOne({_id:4,ClientName:"David"});
{ "acknowledged" : true, "insertedId" : 4 }
Display all documents from a collection with the help of find() method −
> db.demo664.find();
This will produce the following output −
{ "_id" : 1, "ClientName" : "Chris" }
{ "_id" : 2, "ClientName" : "Bob" }
{ "_id" : 3, "ClientName" : "Sam" }
{ "_id" : 4, "ClientName" : "David" }
Following is the query to count number of rows −
> var numberOfRows=db.demo664.count();
> print ("Number Of Rows="+numberOfRows);
This will produce the following output −
Number Of Rows=4
D3.js - Transition

Transition is the process of changing from one state to another of an item. D3.js provides a transition() method to perform transition in the HTML page. Let us learn about  transition in this chapter.
The transition() method is available for all selectors and it starts the transition process. This method supports most of the selection methods such as – attr(), style(), etc. But, It does not support the append() and the data() methods, which need to be called before the transition() method. Also, it provides methods specific to transition like duration(), ease(), etc. A simple transition can be defined as follows −
d3.select("body")
   .transition()
   .style("background-color", "lightblue");
A transition can be directly created using the d3.transition() method and then used along with selectors as follows.
var t = d3.transition()
   .duration(2000);
d3.select("body")
   .transition(t)
   .style("background-color", "lightblue");
Let us now create a basic example to understand how transition works.
Create a new HTML file, transition_simple.html with the following code.
<!DOCTYPE html>
<html>
   <head>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <h3>Simple transitions</h3>
      <script>
         d3.select("body").transition().style("background-color", "lightblue");
      </script>
   </body>
</html>
Here, we have selected the body element and then started transition by calling the transition() method. Then, we have instructed to transit the background color from the current color, white to light blue.
Now, refresh the browser and on the screen, the background color changes from white to light blue. If we want to change the background color from light blue to gray, we can use the following transition −
d3.select("body").transition().style("background-color", "gray");
 Print
 Add Notes
 Bookmark this page
Split Array into Consecutive Subsequences in C++

Suppose we have an array nums that is sorted in ascending order. We have to return true if and only if we can split it into 1 or more subsequences such that each subsequence consists of consecutive integers and whose length at least 3. So if the input is like [1,2,3,3,4,4,5,5], then the output will be True, as we have two consecutive sequences. These are [1,2,3,4,5] and [3,4,5].
To solve this, we will follow these steps −
Make a map m and store the frequency of nums into m, store size of nums into m
cnt := n
for i in range 0 to n – 1x := nums[i]if m[x] and m[x + 1] and m[x + 2]decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3while m[x] > 0 and m[x] > m[x – 1]decrease cnt by 1, decrease m[x] by 1 and increase x by 1
x := nums[i]
if m[x] and m[x + 1] and m[x + 2]
decrease m[x], m[x + 1] and m[x + 2] by 1, increase x by 3 and decrease count by 3
while m[x] > 0 and m[x] > m[x – 1]decrease cnt by 1, decrease m[x] by 1 and increase x by 1
decrease cnt by 1, decrease m[x] by 1 and increase x by 1
return true if cnt is 0, otherwise false
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isPossible(vector<int>& nums) {
      unordered_map <int, int> m;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         m[nums[i]]++;
      }
      int cnt = n;
      for(int i = 0; i < n; i++){
         int x = nums[i];
         if(m[x] && m[x + 1] && m[x + 2]){
            m[x]--;
            m[x + 1]--;
            m[x + 2]--;
            x += 3;
            cnt -= 3;
            while(m[x] > 0 && m[x] > m[x - 1]){
               cnt--;
               m[x]--;
               x++;
            }
         }
      }
      return cnt == 0;
   }
};
main(){
   vector<int> v = {1,2,3,3,4,4,5,5};
   Solution ob;
   cout << (ob.isPossible(v));
}
[1,2,3,3,4,4,5,5]
1
How to randomize the items of a list  in Python?

The random module in the Python standard library provides a shuffle() function that returns a sequence with its elements randomly placed.
>>> import random
>>> l1=['aa',22,'ff',15,90,5.55]
>>> random.shuffle(l1)
>>> l1
[22, 15, 90, 5.55, 'ff', 'aa']
>>> random.shuffle(l1)
>>> l1
['aa', 'ff', 90, 22, 5.55, 15]
Find most frequent element in a list in Python

In this article we will see how to find the element which is most common in a given list. In other words, the element with highest frequency.
We apply why the set function to get the unique elements of the list and then keep account of each of those elements in the list. Finally apply a max function to get the element with highest frequency.
 Live Demo
# Given list
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
res = max(set(listA), key = listA.count)
print("Element with highest frequency:\n",res)
Running the above code gives us the following result −
Given List:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45
We use the counter function from collections. Then apply the most common function to get the final result.
 Live Demo
from collections import Counter
# Given list
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
occurence_count = Counter(listA)
res=occurence_count.most_common(1)[0][0]
print("Element with highest frequency:\n",res)
Running the above code gives us the following result −
Given List:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45
This is a straight forward approach in which we use the mode function from statistics module. It directly gives us the result.
from statistics import mode
# Given list
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("Given List:\n",listA)
res=mode(listA)
print("Element with highest frequency:\n",res)
Running the above code gives us the following result −
Given List:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45
Clojure - Date and Time

Since the Clojure framework is derived from Java classes, one can use the date-time classes available in Java in Clojure. The class date represents a specific instant in time, with millisecond precision.
Following are the methods available for the date-time class.
This is used to create the date object in Clojure.
Following is the syntax.
java.util.Date.

Parameters − None.
Return Value − Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
An example on how this is used is shown in the following program.
(ns example)
(defn Example []
   (def date (.toString (java.util.Date.)))
   (println date))
(Example)
The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run.
Tue Mar 01 06:11:17 UTC 2016

This is used to format the date output.
Following is the syntax.
(java.text.SimpleDateFormat. format dt)

Parameters − ‘format’ is the format to be used when formatting the date. ‘dt’ is the date which needs to be formatted.
Return Value − A formatted date output.
An example on how this is used is shown in the following program.
(ns example)
(defn Example []
   (def date (.format (java.text.SimpleDateFormat. "MM/dd/yyyy") (new java.util.Date)))
   (println date))
(Example)
The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run.
03/01/2016

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
Following is the syntax.
(.getTime)

Parameters − None.
Return Value − The number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date.
An example on how this is used is shown in the following program.
(ns example)
(import java.util.Date)
(defn Example []
   (def date (.getTime (java.util.Date.)))
   (println date))
(Example)
The above program produces the following output. This will depend on the current date and time on the system, on which the program is being run.
1456812778160

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.7

Tryit: HTML href attribute
Python | TextBlob.Word.spellcheck() method - GeeksforGeeks

09 Sep, 2019
With the help of TextBlob.Word.spellcheck() method, we can check the word if that word have spelling mistake by using TextBlob.Word.spellcheck() method.
Syntax : TextBlob.Word.spellcheck()Return : Return the word with correctness accuracy.
Example #1 :In this example we can say that by using TextBlob.Word.spellcheck() method, we are able to get the accuracy of word weather it is correct or not.
# import Wordfrom textblob import Word  gfg = Word("Facility")  # using Word.spellcheck() methodprint(gfg.spellcheck())
Output :
[(‘Facility’, 1.0)]
Example #2 :
# import Wordfrom textblob import Word  gfg = Word("Prediction")  # using Word.spellcheck() methodprint(gfg.spellcheck())
Output :
[(‘Prediction’, 1.0)]
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Remove comma from a string in PHP?

To remove comma, you can replace. To replace, use str_replace() in PHP.
Let’s say the following is our input string with comma 
$name="John,Smith";
We want the output after removing comma from the above string is 
JohnSmith
The PHP code is as follows
 Live Demo
<!DOCTYPE html>
<html>
<body>
<?php
$name="John,Smith";
$result = str_replace(',', '', $name);
echo "The actual value is=",$name,"<br>";
echo "After removing the comma(,)=",$result,"<br>";
?>
</body>
</html>
This will produce the following output
The actual value is=John,Smith
After removing the comma(,)=JohnSmith
How to highlight text in a tkinter Text widget?

Tkinter Text widget is used to create text fields that accept multiline user inputs. Let us suppose that in a text widget, we want to highlight some text. In order to highlight a specific text written in the text widget, tkinter provides the tag_add(tag, i,j) method. It adds tags to the specific text by defining the indexes, i and j.
In this example, we will create a window application that contains some text and a button which can be triggered to highlight the text.
#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
win.geometry("750x450")
#Define a function to highlight the text
def add_highlighter():
   text.tag_add("start", "1.11","1.17")
   text.tag_config("start", background= "black", foreground= "white")
#Create a Tex Field
text= Text(win);
text.insert(INSERT, "Hey there! Howdy?")
text.pack()
#Create a Button to highlight text
Button(win, text= "Highlight", command= add_highlighter).pack()
win.mainloop()
Running the above code will display a window that contain a button and a text in it.
Now, click the "Highlight" button to highlight the text "Howdy?"