code-rag-bench/online-tutorials huggingface dataset:
Longest Palindromic Substring

In a given string, we have to find a substring, which is a palindrome and it is longest.
To get the longest palindromic substring, we have to solve many subproblems, some of the subproblems are overlapping. They are needed to be solved for multiple times. For that reason, the Dynamic programming is helpful. Using a table, we can store the result of the previous subproblems, and simply use them to generate further results.
Input:
A String. Say “thisispalapsiti”
Output:
The palindrome substring and the length of the palindrome.
Longest palindrome substring is: ispalapsi
Length is: 9
findLongPalSubstr(str)
Input − The main string.
Output − Longest palindromic substring and its length.
Begin
   n := length of the given string
   create a n x n table named palTab to store true or false value
   fill patTab with false values
   maxLen := 1

   for i := 0 to n-1, do
      patTab[i, i] = true       //as it is palindrome of length 1
   done

   start := 0
   for i := 0 to n-2, do
      if str[i] = str[i-1], then
         palTab[i, i+1] := true
         start := i
         maxLen := 2
   done

   for k := 3 to n, do
      for i := 0 to n-k, do
         j := i + k – 1
         if palTab[i+1, j-1] and str[i] = str[j], then
            palTab[i, j] := true
            if k > maxLen, then
               start := i
               maxLen := k
      done
   done
   display substring from start to maxLen from str, and return maxLen
 End
#include<iostream>
using namespace std;

int findLongPalSubstr(string str) {
   int n = str.size();        // get length of input string
 
   bool palCheckTab[n][n];    //true when substring from i to j is palindrome
   
   for(int i = 0; i<n; i++)
      for(int j = 0; j<n; j++)
         palCheckTab[i][j] = false;      //initially set all values to false
 
   int maxLength = 1;
   
   for (int i = 0; i < n; ++i)
      palCheckTab[i][i] = true;       //as all substring of length 1 is palindrome
 
   int start = 0;
   for (int i = 0; i < n-1; ++i) {
      if (str[i] == str[i+1]) {      //for two character substring both characters are equal
         palCheckTab[i][i+1] = true;
         start = i;
         maxLength = 2;
      }
   }
 
   for (int k = 3; k <= n; ++k) {       //for substrings with length 3 to n
      for (int i = 0; i < n-k+1 ; ++i) {
         int j = i + k - 1;
         if (palCheckTab[i+1][j-1] && str[i] == str[j]) {    //if (i,j) and (i+1, j-1) are same, then check palindrome
            palCheckTab[i][j] = true;
            if (k > maxLength) {
               start = i;
               maxLength = k;
            }
         }
      }
   }
   cout << "Longest palindrome substring is: " << str.substr(start, maxLength) << endl;
   return maxLength; // return length
}
 
int main() {
   char str[] = "thisispalapsiti";
   cout << "Length is: "<< findLongPalSubstr(str);
}
Longest palindrome substring is: ispalapsi
Length is: 9
HTML | <form> enctype Attribute - GeeksforGeeks

10 Jun, 2019
The HTML <form> enctype Attribute is used to specify that data that will be present in form should be encoded when submitting to the server. This type of attribute can be used only if method = “POST”.
Syntax:
<form enctype="value"> 
Attribute Value: This attribute contains three value which are listed below:
application/x-www-form-urlencoded: It is the default value. It encodes all the characters before sent to the server. It converts spaces into + symbols and special character into its hex value.
multipart/form-data: This value does not encode any character.
text/plain: This value convert spaces into + symbols but special characters are not converted.
Example: This Example illustrates the use of enctype attribute in <form> element.
<!DOCTYPE html><html>  <head>    <title>Form enctype attribute</title></head>  <body style="text-align: center">    <h1 style="color: green">GeeksforGeeks</h1>    <h2>Form enctype Attribute</h2>    <form action="#"          method="post"           enctype="multipart/form-data">        First name:        <input type="text"                name="fname">        <br> Last name:        <input type="text"               name="lname">        <br> Address:        <input type="text"                name="Address">        <br>        <input type="submit"               value="Submit">    </form></body>  </html>
Output :
Supported Browsers: The browsers supported by <form> enctype Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to call another enum value in an enum's constructor using java?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can define an enumeration using the keyword enum followed by the name of the enumeration as −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Enumerations are similar to classes and, you can have variables, methods (Only concrete methods) and constructors within them.
For suppose we have elements in an enumeration with values as −
enum Scoters {
   ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000);
}
To define a constructor in it, first of all declare an instance variable to hold the values of the elements.
private int price;
Then, declare a parameterized constructor initializing above created instance variable.
Scoters (int price) {
   this.price = price;
}
To initialize the enum with values in another enum.
Declare the desired enum as the instance variable.
Initialize it with a parameterized constructor.
import java.util.Scanner;
enum State{
   Telangana, Delhi, Tamilnadu, Karnataka, Andhrapradesh
}
enum Cities {
   Hyderabad(State.Telangana), Delhi(State.Delhi), Chennai(State.Tamilnadu), Banglore(State.Karnataka), Vishakhapatnam(State.Andhrapradesh);
   //Instance variable
   private State state;
   //Constructor to initialize the instance variable
   Cities(State state) {
      this.state = state;
   }
   //Static method to display the country
   public static void display(int model){
      Cities constants[] = Cities.values();
      System.out.println("State of: "+constants[model]+" is "+constants[model].state);
   }
}
public class EnumerationExample {
   public static void main(String args[]) {
      Cities constants[] = Cities.values();
      System.out.println("Value of constants: ");
      for(Cities d: constants) {
         System.out.println(d.ordinal()+": "+d);
      }
      System.out.println("Select one model: ");
      Scanner sc = new Scanner(System.in);
      int model = sc.nextInt();
      //Calling the static method of the enum
      Cities.display(model);
   }
}
Value of constants:
0: Hyderabad
1: Delhi
2: Chennai
3: Banglore
4: Vishakhapatnam
Select one model:
2
State of: Chennai is Tamilnadu
Bash Script - Arithmetic Operators - GeeksforGeeks

04 Jan, 2022
In this article, we will see arithmetic operators in bash script. Arithmetic operators is used to perform arithmetic operations.
Bash script supports 11 arithmetic operators. All the operators with their uses is given below:
16/3
result = 5
16/ 3
result = 1
x= 13
x+=3
result = 16
x= 13
x -= 3
result = 10
x= 10
x*=3
result = 30
x = 31
x/=3
result = 10
x= 31
x%=3
result = 1
3**2
result = 9
Let’s see the examples for the uses of arithmetic operators:
Code:
Sum=$((10+3))  
echo "Sum = $Sum"  
Output:
Code:
Difference=$((10-3))  
echo "Difference = $Difference"  
Output:
Code:
Product=$((10*3))  
echo "Product = $Product"  
Output:
Code:
Division=$((10/3))  
echo "Division = $Division"  
Output:
Code:
Modulo=$((10%3))  
echo "Modulo = $Modulo"  
Output:
Code:
Exponent=$((10**2))  
echo "Exponent = $Exponent"  
Output:
Example to show use of all the operators in a single code
Code:
x=10
y=20
echo "x=10, y=5"  
echo "Addition of x and y"  
echo $(( $x + $y ))  
echo "Subtraction of x and y"  
echo $(( $x - $y ))  
echo "Multiplication of x and y"  
echo $(( $x * $y ))  
echo "Division of x by y"  
echo $(( $x / $y ))  
echo "Exponentiation of x,y"  
echo $(( $x ** $y ))  
echo "Modular Division of x,y"  
echo $(( $x % $y ))  
echo "Incrementing x by 10, then x= "  
(( x += 10 ))    
echo $x  
echo "Decrementing x by 15, then x= "  
(( x -= 15 ))  
echo $x  
echo "Multiply of x by 2, then x="  
(( x *= 2 ))  
echo $x  
echo "Dividing x by 5, x= "  
(( x /= 5 ))  
echo $x  
echo "Remainder of Dividing x by 5, x="  
(( x %= 5 ))  
echo $x  
Output:
There are some of the different ways to perform Arithmetic Operations.
This could be used for arithmetic expansion. Let’s see an example to see the use of double quotes.
Code:
#!/bin/bash
 
first=10
second=3
 
echo $(( first + second ))   # addition
echo $(( $first + $second )) # this is also valid
 
echo $(( first - second ))   # subtraction
echo $(( $first - $second )) # this is also valid
 
 Output:
13
13
7
7
let command is used to perform arithmetic operations. 
Example
code:
#!/bin/bash
 
x=10
y=3
 
let "z = $(( x * y ))"  # multiplication
echo $z
let z=$((x*y))
echo $z
 
let "z = $(( x / y ))"  # division
echo $z
let z=$((x/y))
echo $z
Output:
30
30
3
3
Arithmetic expansion could be done using backticks and expr.
Code:
a=10
b=3

# there must be spaces before/after the operator

sum=`expr $a + $b`
echo $sum

sub=`expr $a - $b`
echo $sub

mul=`expr $a \* $b`
echo $mul

div=`expr $a / $b`
echo $div
Output:
13
7
30
3
Bash-Script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
nohup Command in Linux with Examples
mv command in Linux with examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
How to find the cumulative sum for factor levels in an R data frame?

Cumulative sums are mostly used in descriptive analysis of data but sometimes we might want to calculate them in understanding the time series analysis for moving sums but it is very rare. If we have a factor column in an R data frame then it would not make sense to find the cumulative sum for all factor levels together, we must find the cumulative sums for each level. This can be easily done by using ave function.
Consider the below data frame −
 Live Demo
set.seed(15)
x1<-as.factor(sample(LETTERS[1:3],20,replace=TRUE))
x2<-rpois(20,5)
df1<-data.frame(x1,x2)
df1
  x1 x2
1  A 5
2  C 6
3  B 2
4  B 3
5  A 8
6  B 5
7  A 5
8  A 3
9  C 5
10 A 2
11 C 5
12 B 6
13 A 2
14 A 5
15 A 4
16 C 6
17 B 8
18 A 5
19 B 8
20 B 3
Finding cumulative sum of x2 values for different values of x1 −
df1$CumSum_x2_based_on_x1<-ave(x2,x1,FUN=cumsum)
df1
  x1 x2 CumSum_x2_based_on_x1
1  A 5    5
2  C 6    6
3  B 2    2
4  B 3    5
5  A 8    13
6  B 5    10
7  A 5    18
8  A 3    21
9  C 5    11
10 A 2    23
11 C 5    16
12 B 6    16
13 A 2    25
14 A 5    30
15 A 4    34
16 C 6    22
17 B 8    24
18 A 5    39
19 B 8    32
20 B 3    35
Let’s have a look at another example −
 Live Demo
Group<-sample(c("GRP1","GRP2","GRP3","GRP4"),20,replace=TRUE)
Response<-sample(1:10,20,replace=TRUE)
df2<-data.frame(Group,Response)
df2
 Group Response
1  GRP2    1
2  GRP3    1
3  GRP2    8
4  GRP2    1
5  GRP2    4
6  GRP1    7
7  GRP1    8
8  GRP1    2
9  GRP1    1
10 GRP1    1
11 GRP4    3
12 GRP3    9
13 GRP4    4
14 GRP1    9
15 GRP4    5
16 GRP2    8
17 GRP2    10
18 GRP3    5
19 GRP3    8
20 GRP3    8
Finding cumulative sum of Response values for different values of Group
df2$CumSum_of_GroupLevels<-ave(Response,Group,FUN=cumsum)
df2
  Group Response CumSum_of_GroupLevels
1  GRP2    1       1
2  GRP3    1       1
3  GRP2    8       9
4  GRP2    1       10
5  GRP2    4       14
6  GRP1    7       7
7  GRP1    8       15
8  GRP1    2       17
9  GRP1    1       18
10 GRP1    1       19
11 GRP4    3       3
12 GRP3    9       10
13 GRP4    4       7
14 GRP1    9       28
15 GRP4    5       12
16 GRP2    8       22
17 GRP2    10       32
18 GRP3    5       15
19 GRP3    8       23
20 GRP3    8       31
C++ Program for QuickSort - GeeksforGeeks

06 Feb, 2022
Similar to the Merge Sort algorithm, the Quick Sort algorithm is a Divide and Conquer algorithm. It initially selects an element as a pivot element and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. 
Always pick the first element as a pivot (implemented below).Always pick the last element as the pivot.Pick a random element as a pivot.Pick median as a pivot.
Always pick the first element as a pivot (implemented below).
Always pick the last element as the pivot.
Pick a random element as a pivot.
Pick median as a pivot.
The key process in quickSort is the partition() process. The aim of the partition() function is to receive an array and an element x of the array as a pivot, put x at its correct position in a sorted array and then put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time i.e.  Big O(n) .Pseudo Code for recursive QuickSort function : 
/* low  --> Starting index,  high  --> Ending index */
quickSort(arr[], low, high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        pi = partition(arr, low, high);

        quickSort(arr, low, pi - 1);  // Before pi
        quickSort(arr, pi + 1, high); // After pi
    }
}
CPP
// C++ Implementation of the Quick Sort Algorithm.#include <iostream>using namespace std; int partition(int arr[], int start, int end){     int pivot = arr[start];     int count = 0;    for (int i = start + 1; i <= end; i++) {        if (arr[i] <= pivot)            count++;    }     // Giving pivot element its correct position    int pivotIndex = start + count;    swap(arr[pivotIndex], arr[start]);     // Sorting left and right parts of the pivot element    int i = start, j = end;     while (i < pivotIndex && j > pivotIndex) {         while (arr[i] <= pivot) {            i++;        }         while (arr[j] > pivot) {            j--;        }         if (i < pivotIndex && j > pivotIndex) {            swap(arr[i++], arr[j--]);        }    }     return pivotIndex;} void quickSort(int arr[], int start, int end){     // base case    if (start >= end)        return;     // partitioning the array    int p = partition(arr, start, end);     // Sorting the left part    quickSort(arr, start, p - 1);     // Sorting the right part    quickSort(arr, p + 1, end);} int main(){     int arr[] = { 9, 3, 4, 2, 1, 8 };    int n = 6;     quickSort(arr, 0, n - 1);     for (int i = 0; i < n; i++) {        cout << arr[i] << " ";    }     return 0;}
1 2 3 4 8 9 
Please refer complete article on QuickSort for more details!
hitesh_tripathi
shreyasnaphad
Quick Sort
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Pi(π) in C++ with Examples
Const keyword in C++
C library function - tolower()

The C library function int tolower(int c) converts a given letter to lowercase.
Following is the declaration for tolower() function.
int tolower(int c);
c − This is the letter to be converted to lowercase.
c − This is the letter to be converted to lowercase.
This function returns lowercase equivalent to c, if such value exists, else c remains unchanged. The value is returned as an int value that can be implicitly casted to char.
The following example shows the usage of tolower() function.
#include <stdio.h>
#include <ctype.h>

int main () {
   int i = 0;
   char c;
   char str[] = "TUTORIALS POINT";
	
   while( str[i] ) {
      putchar(tolower(str[i]));
      i++;
   }
   
   return(0);
}
Let us compile and run the above program to produce the following result −
tutorials point


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Facial expression detection using Deepface module in Python - GeeksforGeeks

28 Jul, 2021
In this article, we are going to detect the facial expression of an already existing image using OpenCV, Deepface, and matplotlib modules in python.
OpenCV: OpenCV is an open-source library in python which is used for computer vision, machine learning, and image processing.
Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Deepface: Deepface was built by an artificial intelligence researchers group at Facebook. It is a framework in python for facial recognition and attributes analysis. Deepface’s core library components are used in Keras and TensorFlow.
pip install deepface
This is the most basic expression detection technique and there are several ways in which we can detect facial expression. 
Step 1: Importing the required module.
Python3
#import the required modulesimport cv2import matplotlib.pyplot as pltfrom deepface import DeepFace
Step 2: Copy the path of the picture of which expression detection is to be done, read the image using “imread()” method in cv2 providing the path within the bracket. imread() reads the image from the file and stores it in an array. Then use imshow() method of matplotlib. imshow() method converts data into image. Now plot the image using show method in order to ensure that the image has been correctly imported.
Python3
# read imageimg = cv2.imread('img1.jpg')  # call imshow() using plt objectplt.imshow(img[:, :, : : -1])  # display that imageplt.show()
Output:
Output image
Step 3: Create a result variable that will store the result. Use Deepface analyze() method, Deepface analyze() method contains strong facial attribute analysis features such as age, gender, facial expressions. Facial expressions include anger, fear, neutral, sad, disgust, happy, and surprise. Print the result. The result shows the facial expressions percentage of the person.
Python3
# storing the resultresult = DeepFace.analyze(img,                          actions = ['emotion'])  # print resultprint(result)
Output:
The result shows that person is 96% happy.
Below is the complete implementation:
Python3
# import the required modulesimport cv2import matplotlib.pyplot as pltfrom deepface import DeepFace  # read imageimg = cv2.imread('img.jpg')  # call imshow() using plt objectplt.imshow(img[:,:,::-1])  # display that imageplt.show()  # storing the resultresult = DeepFace.analyze(img,actions=['emotion'])  # print resultprint(result)
Output:
Picked
python-modules
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
HTML | <col> align Attribute

18 Feb, 2022
The HTML <col> align Attribute is used to set the horizontal alignment of text content inside the col element. It is not supported by HTML 5.
Syntax:
<col align="left | right | center | justify | char">
Attribute Values:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align.
justify: It stretches the text of paragraph to set the width of all lines equal.
char: It sets the text-align to a specific character.
Example:
<!DOCTYPE html><html>  <head>    <title>      HTML col align Attribute  </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>      HTML col align Attribute  </h2>      <table width="500" border="1">        <col align="center">                  <tr>                    <th>Name</th>                    <th>Expenses</th>                </tr>                  <tr>                    <td>BITTU</td>                    <td>2500.00</td>                </tr>                  <tr>                    <td>RAKESH</td>                    <td>1400.00</td>                </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <col> align attribute are listed below:
Google Chrome: Not Supported
Internet Explorer: Not Supported
Firefox: Not Supported
Safari: Not Supported
Opera: Not Supported
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to change the permission of a file using Python?

To change the permission of a file, you can use the os.chmod(file, mode) call. Note that the mode should be specified in octal representation and therefore must begin with a 0o. For example, to make a file readonly, you can set the permission to 0o777, you can use:
>>> import os
>>> os.chmod('my_file', 0o777)
You can also use flags from the stat module. You can read more about these flags here: http://docs.python.org/2/library/stat.html
Another way to acheive it is using a subprocess call:
>>> import subprocess
>>> subprocess.call(['chmod', '0444', 'my_file'])
Java program to count the characters in each word in a given sentence

19 May, 2021
Write a Java program to count the characters in each word in a given sentence?Examples:  
Input : geeks for geeks
Output :
geeks->5
for->3
geeks->5
 
Here first we create an equivalent char array of given String.
Now we iterate the char array using for loop. Inside for loop we declare a String with empty implementation.
Whenever we found an alphabet we will perform concatenation of that alphabet with the String variable and increment the value of i.
Now when i reaches to a space it will come out from the while loop and now String variable has the word which is previous of space.
Now we will print the String variable with the length of the String.
 
JAVA
class CountCharacterInEachWords {    static void count(String str)    {        // Create an char array of given String        char[] ch = str.toCharArray();        for (int i = 0; i < ch.length; i++) {             // Declare an String with empty initialization            String s = "";             // When the character is not space            while (i < ch.length && ch[i] != ' ') {                 // concat with the declared String                s = s + ch[i];                i++;            }             if (s.length() > 0)                System.out.println(s + "->" + s.length());                   }    }    public static void main(String[] args)    {        String str = "geeks for geeks";        count(str);    }}
Output:  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
geeks->5
for->3
geeks->5
 
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2Y5vWkeNjcg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
gabaa406
Java-Strings
Java Programs
Strings
Java-Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to 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?
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
set add() in python

04 Sep, 2018
The set add() method adds a given element to a set if the element is not present in the set.
Syntax:
set.add(elem)
The add() method doesn't add an element to the
set if it's already present in it otherwise it 
will get added to the set.
Parameters:
add() takes single parameter(elem) which needs to 
be added in the set.
Returns:
The add() method doesn't return any value.

# set of lettersGEEK = {'g', 'e', 'k'}  # adding 's'GEEK.add('s')print('Letters are:', GEEK)  # adding 's' againGEEK.add('s')print('Letters are:', GEEK)
Output:
('Letters are:', set(['k', 'e', 's', 'g']))
('Letters are:', set(['k', 'e', 's', 'g'])

Application:
It is used to add a new element to the set. 

# set of lettersGEEK = {6, 0, 4}  # adding 1GEEK.add(1)print('Letters are:', GEEK)  # adding 0 GEEK.add(0)print('Letters are:', GEEK)
Output:
('Letters are:', set([0, 1, 4, 6]))
('Letters are:', set([0, 1, 4, 6]))

Adding tuple to a set:
# Python code to demonstrate addition of tuple to a set.s = {'g', 'e', 'e', 'k', 's'}t = ('f', 'o')  # adding tuple t to set s.s.add(t)  print(s)
Output :
{'k', 's', 'e', 'g', ('f', 'o')}

python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
Taking input in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python | datetime.timedelta() function

09 Jun, 2022
Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. 
Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Returns : Date
Code #1: 
Python3
# Timedelta function demonstration from datetime import datetime, timedelta  # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ("initial_date", str(ini_time_for_now)) # Calculating future dates# for two yearsfuture_date_after_2yrs = ini_time_for_now + \                        timedelta(days = 730) future_date_after_2days = ini_time_for_now + \                         timedelta(days = 2) # printing calculated future_datesprint('future_date_after_2yrs:', str(future_date_after_2yrs))print('future_date_after_2days:', str(future_date_after_2days))
initial_date 2019-02-27 12:41:45.018389
future_date_after_2yrs: 2021-02-26 12:41:45.018389
future_date_after_2days: 2019-03-01 12:41:45.018389
Code #2: 
Python3
# Timedelta function demonstrationfrom datetime import datetime, timedelta  # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ('initial_date:', str(ini_time_for_now)) # Calculating past dates# for two yearspast_date_before_2yrs = ini_time_for_now - \                       timedelta(days = 730) # for two hourspast_date_before_2hours = ini_time_for_now - \                        timedelta(hours = 2)  # printing calculated past_datesprint('past_date_before_2yrs:', str(past_date_before_2yrs))print('past_date_before_2hours:', str(past_date_before_2hours))
initial_date 2019-02-27 12:41:46.104662
past_date_before_2yrs: 2017-02-27 12:41:46.104662
past_date_after_2days: 2019-02-27 10:41:46.104662
Code #3: 
Python3
# Timedelta function demonstrationfrom datetime import datetime, timedelta # Using current timeini_time_for_now = datetime.now() # printing initial_dateprint ("initial_date", str(ini_time_for_now)) # Some another datetimenew_final_time = ini_time_for_now + \                 timedelta(days = 2) # printing new final_dateprint ("new_final_time", str(new_final_time))  # printing calculated past_datesprint('Time difference:', str(new_final_time - \                             ini_time_for_now))
initial_date 2019-02-27 12:41:47.386595
new_final_time 2019-03-01 12:41:47.386595
Time difference: 2 days, 0:00:00
abelbraaksma
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
Python OOPs Concepts
Dart – Type System

24 Mar, 2022
The Dart programming language is considered type safe, meaning it ensures that the variable’s value always matches the variable’s static type through a combination of static type checking and runtime checking. It is also known as Sound Typing. It comes in handy while debugging the code at compile time.
All forms of static errors can be resolved by adding type annotations to generic classes.Some frequently used generic collection classes are listed below:
List
Map
Example 1: The below code will throw an error on listwhen a call to the printInts(list) is made.
Dart
void printInts(List<int> x) => print(x); void main() {  var list = [];  list.add(1000);  list.add(2000);  printInts(list);}}
Output:
error - The argument type 'List' can't be assigned to the parameter type 'List' at lib/strong_analysis.dart:27:17 - (argument_type_not_assignable)
The above error occurred due to an unsound implicit cast from a dynamic type List to an integer type , meaning declaring var List = [] doesn’t provide sufficient information to the dart analyzer about the typing of the list items. To resolve this issue we pass the type annotation to the list variable as shown below:
Dart
// Using num data type in Dartvoid printInts(List<int> a) => print(a); void main() {  var list = <int>[];  list.add(1000);  list.add(2000);  printInts(list);}}
Output:
[1000, 2000] 
Soundness is the process of making sure that the code doesn’t run into an invalid state. For instance, if a variable’s static type is boolean, it is not possible to run into a state where the variable evaluates to a non-string value during runtime. 
Benefits of having Soundness:
Debug type related bugs at compile time.
Makes code easier to read and debug.
Get alters when changing code picese that breaks other dependent part of the code.
One of its key features is Ahead Of Time (AOT) compilation, which significantly reduces the compile time of the code and increases efficiency.  
varshagumber28
kothavvsaakash
Dart Data-types
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Checkbox Widget
Flutter - Custom Bottom Navigation Bar
Flutter - AppBar Widget
ListView Class in Flutter
Flutter - Stack Widget
Flutter - Search Bar
How to Append or Concatenate Strings in Dart?
Dart Tutorial
Flutter - Row and Column Widgets
Create a Website Alarm Using Python

19 Nov, 2020
We use Bookmarks to remember the important websites which we think we will use them very often in future.Here’s a simple python code which takes the URL of the website as its first input and the time you want to open it as the second input.
As the time reaches your given value of the time, it’ll open the URL that you requested in the web browser automatically.In this code, we’ll import two python modules – Time and Webbrowser.
# Import the time module, it provides various time-related # functions. import time   # Import the webbrowser module, it is used to # display various HTML documents to the user. import webbrowser   # First Input: It is the time of the form # 'Hours:Minutes:Seconds' that you'll # use to set the alarm. Set_Alarm = input("Set the website alarm as H:M:S:")   # Second Input: It is the URL that you want # to open on the given time. url = input("Enter the website you want to open:")   # This is the actual time that we will use to print. Actual_Time = time.strftime("%I:%M:%S")   # This is the while loop that'll print the time # until it's value will be equal to the alarm time while (Actual_Time != Set_Alarm):     print ("The time is " + Actual_Time)     Actual_Time = time.strftime("%I:%M:%S")     time.sleep(1)     # This if statement plays the role when its the # alarm time and executes the code within it. if (Actual_Time == Set_Alarm):     print ("You should see your webpage now :-)")      # We are calling the open()     # function from the webrowser module.     webbrowser.open(url) 
You can contribute to the code by going here.
This article is contributed by Shivam Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
You can contribute to the code by going here.
Python
Web Technologies
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()
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Message Boxes using PyAutoGUI

26 May, 2020
PyAutoGUI is a Python module which can automate your GUI and programmatically control your keyboard and mouse. This article illustrates the GUI functions to create display boxes.If you want to know more about PyAutoGUI and its ability to automate your keyboard and mouse, follow this article : Mouse and Keyboard Automation using PyAutoGUI
PyAutoGUI does not come with python, so go to command prompt and type the following :
 pip3 install PyAutoGUI
alert() : Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.
# Python Program to show alert() functionimport pyautogui  pyautogui.alert('GeekforGeeks alert box')
Output : It will display the alert box with the given text and when clicked OK it will return ‘OK’
 confirm() : Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.
# Python Program to show confirm() functionimport pyautoguipyautogui.confirm('Geek Shall I proceed?')
Output : It will display the alert box with the given text and on clicking the button it will return the text on the button. In this case its ‘OK’
To have multiple select options –
# Python Program to show confirm() function# with multiple optionsimport pyautoguipyautogui.confirm('Enter option Gfg', buttons =['A', 'B', 'C'])
Output : On clicking A, it will return ‘A’ as output.
 prompt() : Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked.
# Python Program to show prompt() functionimport pyautoguipyautogui.prompt('What is your name?')
Output : It will return the text entered, in this case ‘GeekForGeeks’ or None if cancelled was clicked. 
password() : Displays a message box with text input, and OK & Cancel buttons. Typed characters appear as *. Returns the text entered, or None if Cancel was clicked
# Python Program to show password() functionimport pyautoguipyautogui.password('Enter password (text will be hidden)')
Output : It will return the text/password entered, in this case ‘GeekForGeeks’ or None if cancelled was clicked.
Python-gui
Python-PyAutoGUI
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
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to use stopwatch in PowerShell?

To use the stopwatch in PowerShell, we need to use [System.Diagnostics.Stopwatch] class.
We will create a new object for this class,
$stopwatch = [System.Diagnostics.Stopwatch]::new()
Below are the members of the above stopwatch mentioned class.
PS C:\> $Stopwatch | gm


TypeName: System.Diagnostics.Stopwatch

Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
Reset Method void Reset()
Restart Method void Restart()
Start Method void Start()
Stop Method void Stop()
ToString Method string ToString()
Elapsed Property timespan Elapsed {get;}
ElapsedMilliseconds Property long ElapsedMilliseconds {get;}
ElapsedTicks Property long ElapsedTicks {get;}
IsRunning Property bool IsRunning {get;}
You can see above that you can Start, Stop, Restart, and Reset the stopwatch and before starting all values should be 0.
PS C:\> $Stopwatch.Elapsed

Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 0
TotalDays : 0
TotalHours : 0
TotalMinutes : 0
TotalSeconds : 0
TotalMilliseconds : 0
Now, we will start the timer using the Start() method.
$Stopwatch.Start()

You can check the elapsed time using the Elapsed property.
PS C:\> $Stopwatch.Elapsed

Days : 0
Hours : 0
Minutes : 1
Seconds : 42
Milliseconds : 284
Ticks : 1022842838
TotalDays : 0.00118384587731481
TotalHours : 0.0284123010555556
TotalMinutes : 1.70473806333333
TotalSeconds : 102.2842838
TotalMilliseconds : 102284.2838
To retrieve any of the above property, use the property name. For example,
PS C:\> $Stopwatch.Elapsed.Minutes
4
To stop the stopwatch use Stop(), to Reset the Stopwatch use Reset() methods, and to restart the stopwatch use Restart() method.
PS C:\> $Stopwatch.Reset()
PS C:\> $Stopwatch.Elapsed

Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 0
TotalDays : 0
TotalHours : 0
TotalMinutes : 0
TotalSeconds : 0
TotalMilliseconds : 0

PS C:\> $Stopwatch.Restart()
PS C:\> $Stopwatch.Elapsed

Days : 0
Hours : 0
Minutes : 0
Seconds : 1
Milliseconds : 757
Ticks : 17570261
TotalDays : 2.03359502314815E-05
TotalHours : 0.000488062805555556
TotalMinutes : 0.0292837683333333
TotalSeconds : 1.7570261
TotalMilliseconds : 1757.0261

PS C:\> $Stopwatch.Stop()
PS C:\> $Stopwatch.Elapsed

Days : 0
Hours : 0
Minutes : 6
Seconds : 36
Milliseconds : 121
Ticks : 3961214918
TotalDays : 0.00458473948842593
TotalHours : 0.110033747722222
TotalMinutes : 6.60202486333333
TotalSeconds : 396.1214918
TotalMilliseconds : 396121.4918
Select Rows with Partial String Match in R DataFrame

17 Dec, 2021
In this article, we’ll discuss how to select rows with a partial string match in the R programming language.
The stringr package in R language is used mainly for character manipulations, locale-sensitive operations, altering whitespace, and Pattern-matching. Here we will use its pattern matching functionality to filter data according to partial string match.
Syntax:
df[str_detect(df$column-name, “Pattern”), ]
Parameters:
df: determines the dataframe that is being used.
column-name: determines the column in which strings have to be filtered.
Pattern: determines the string pattern that has to be matched.
Example: This example explains how to extract rows with a partial match using the stringr package. 
R
# Load library stringrlibrary("stringr") # sample dataframedata<- data.frame(names=c('Hello','this','Hell','Geeks',                          'Geek', 'Geeksforgeeks'))                  # Filter data with str_detect for strings# containing "Gee"result1<-data[str_detect(data$name, "Gee"), ] # print result dataresult1 # Filter data with str_detect for strings# containing "Hel"result2<-data[str_detect(data$name, "Hel"), ] # print result dataresult2
Output: 
[1] “Geeks”         “Geek”          “Geeksforgeeks”
[1] “Hello” “Hell” 
Data.table is an extension of data.frame package in R. It is widely used for fast aggregation of large datasets, low latency add/update/remove of columns, quicker ordered joins, and a fast file reader. Here we will use its data update of the column functionality to filter data according to partial string match. We will use %like%-operator to select the string match data and will filter data from the dataframe accordingly. 
Syntax:
df[df$column-name %like% “Pattern”, ]
Parameter:
df: determines the dataframe that is being used.
column-name: determines the column in which strings have to be filtered.
Pattern: determines the string pattern that has to be matched.
Example: This example explains how to extract rows with a partial match using the data.table package.  
R
# load data.table packagelibrary("data.table")   # sample dataframedata<- data.frame(names=c('Hello','this','Hell','Geeks',                          'Geek', 'Geeksforgeeks')) # Filter data with %like% all strings having "Gee"result1<-data[data$name %like% "Gee", ] # print result dataresult1 # Filter data with %like% all strings having "Hel"result2<-data[data$name %like% "Hel", ] # print result dataresult2
Output:
[1] “Geeks”         “Geek”          “Geeksforgeeks”
[1] “Hello” “Hell” 
rajeev0719singh
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 ?
Stack isEmpty() method in Java with Example

24 Dec, 2018
The Java.util.Stack.isEmpty() method in Java is used to check and verify if a Stack is empty or not. It returns True if the Stack is empty else it returns False.
Syntax:
Stack.isEmpty()
Parameters: This method does not take any parameter.
Return Value: This function returns True if the Stackis empty else it returns False.
Below programs illustrate the Java.util.Stack.isEmpty() method:
Program 1:
// Java code to illustrate isEmpty()import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements into the Stack        stack.add("Welcome");        stack.add("To");        stack.add("Geeks");        stack.add("4");        stack.add("Geeks");          // Displaying the Stack        System.out.println("Stack:  " + stack);          // Verifying if the Stack is empty or not        System.out.println("Is the Stack empty? "                           + stack.isEmpty());          // Clearing the Stack        stack.clear();          // Displaying the Stack        System.out.println("Stack after clear(): "                           + stack);          // Verifying if the Stack is empty or not        System.out.println("Is the Stack empty? "                           + stack.isEmpty());    }}
Stack:  [Welcome, To, Geeks, 4, Geeks]
Is the Stack empty? false
Stack after clear(): []
Is the Stack empty? true

Program 2:
// Java code to illustrate isEmpty()import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<Integer> stack = new Stack<Integer>();          // Displaying the Stack        System.out.println("Stack:  " + stack);          // Verifying if the Stack is empty or not        System.out.println("Is the Stack empty? "                           + stack.isEmpty());    }}
Stack:  []
Is the Stack empty? true

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Python | Unit Test Objects Patching | Set-1

12 Jun, 2019
The problem is writing unit tests and need to apply patches to selected objects in order to make assertions about how they were used in the test (e.g., assertions about being called with certain parameters, access to selected attributes, etc.).
To do so, the unittest.mock.patch() function can be used to help with this problem. It’s a little unusual, but patch() can be used as a decorator, a context manager, or stand-alone.
from unittest.mock import patchimport example@patch('example.func')  def test1(x, mock_func):    # Uses patched example.func    example.func(x)     mock_func.assert_called_with(x)
 Code #2: Using unittest.mock.patch as a decorator
with patch('example.func') as mock_func:    example.func(x)     mock_func.assert_called_with(x)
 Code #3: Using unittest.mock.patch to patch things manually.
p = patch('example.func')mock_func = p.start()example.func(x)mock_func.assert_called_with(x)p.stop()
 Code #4: Stacking decorators and context managers to patch multiple objects
@patch('example.func1')@patch('example.func2')@patch('example.func3')  def test1(mock1, mock2, mock3):    ...def test2():    with patch('example.patch1') as mock1, \    patch('example.patch2') as mock2, \    patch('example.patch3') as mock3:    ...
patch() works by taking an existing object with the fully qualified name that you provide and replacing it with a new value. The original value is then restored after the completion of the decorated function or context manager. By default, values are replaced with MagicMock instances. Code #5 : Example
x = 42with patch('__main__.x'):    print(x)  print (x)
Output :
<MagicMock name='x' id='4314230032'>
42
Python-ctype
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts