code-rag-bench/online-tutorials huggingface dataset:
send_keys 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 send_keys method on Action Chains in Python Selenium. send_keys method is used to send keys to current focused element.
Syntax –
send_keys(*keys_to_send)
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")element = driver.find_element_by_name("passwd")
Now one can use send_keys method as an Action chain as below –
action.click(on_element=element)
action.send_keys("Arrays")

To demonstrate, send_keys 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_class_name("gsc-input")  # create action chain objectaction = ActionChains(driver)  # click the itemaction.click(on_element = element)  # send keysaction.send_keys("Arrays")  # 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.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
Convert integer to string in Python
How to close child browser window in Selenium WebDriver using Java?

We can close the child browser window in Selenium webdriver. The getWindowHandles and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure.
The getWindowHandle method is used to store the browser window currently active. To iterate over the window handles, the iterator method is used. We have to add import java.util.Set to accommodate Set and import java.util.List and import java.util.Iterator statements to accommodate iterator in our code.
By default, the driver object can access the elements of the parent window. In order to switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
public class CloseChildWindow {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      //implicit wait
      driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
      driver.findElement(By.id("login-google-button")).click();
      // window handles
      Set w = driver.getWindowHandles();
      // window handles iterate
      Iterator t = w.iterator();
      String ch = t.next();
      String pw = t.next();
      // switching child window
      driver.switchTo().window(ch);
      System.out.println("Child window title "+ driver.getTitle());
      // close the child browser window
      driver.close();
      // switching parent window
      driver.switchTo().window(pw);
      System.out.println("Parent window title: "+ driver.getTitle());
      driver.quit();
turtle.pen() function in Python

24 Dec, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return or set the pen’s attributes in a ‘pen-dictionary’ with the following key/value pairs:
“shown” : True/False
“pendown” : True/False
“pencolor” : color-string or color-tuple
“fillcolor” : color-string or color-tuple
“pensize” : positive number
“speed” : number in range 0..10
“resizemode” : “auto” or “user” or “noresize”
“stretchfactor”: (positive number, positive number)
“shearfactor” : number
“outline” : positive number
“tilt” : number
This dictionary can be used as an argument for a subsequent pen()-call to restore the former pen-state. Moreover, one or more of these attributes can be provided as keyword-arguments. This can be used to set several pen attributes in one statement.
Syntax : turtle.pen(pen=None, **pendict) 
Parameters:
pen : a dictionary with some or all of the below listed keys.
**pendict : one or more keyword-arguments with the below listed keys as keywords.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # check default valuesprint(turtle.pen())
Output : 
{‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘black’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 1, ’tilt’: 0.0} 
Example 2 :
Python3
# import packageimport turtle # check default to compareprint(turtle.pen()) # update with some inputsturtle.pen(pencolor="red", outline=2) # again checkprint(turtle.pen())
Output :
{‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘black’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 1, ’tilt’: 0.0} {‘shown’: True, ‘pendown’: True, ‘pencolor’: ‘red’, ‘fillcolor’: ‘black’, ‘pensize’: 1, ‘speed’: 3, ‘resizemode’: ‘noresize’, ‘stretchfactor’: (1.0, 1.0), ‘shearfactor’: 0.0, ‘outline’: 2, ’tilt’: 0.0} 
simmytarika5
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Instant toString() method in Java with Examples

28 Nov, 2018
The toString() method of Instant class returns string representation of this instant using ISO-8601 representation and format used is the same as DateTimeFormatter.ISO_INSTANT.
Syntax:
public String toString()
Returns: This method returns an ISO-8601 representation of this instant, not null.
Below programs illustrate the toString() method:
Program 1:
// Java program to demonstrate// Instant.toString() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a Instant object        Instant instant            = Instant.parse("2018-10-28T19:34:50.63Z");          // print Instant using toString()        System.out.println("Instant: "                           + instant.toString());          // addition of 84000 seconds to this instant        Instant returnedValue            = instant.plusSeconds(84000);          // print result Instant using toString()        System.out.println("Returned Instant: "                           + returnedValue.toString());    }}
Program 2:
// Java program to demonstrate// Instant.toString() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a Instant object        Instant instant            = Instant.parse("2022-06-21T19:34:50.63Z");          // print Instant using toString()        System.out.println("Instant: "                           + instant);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#toString()
Java-Functions
Java-Instant
Java-time 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
Java Programming Examples
Functional Interfaces in Java
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
How does inline JavaScript work with HTML ?

30 Sep, 2019
Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”...”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag.
Syntax:
<script>
    // JavaScript Code
</script>

Example:
<!DOCTYPE html> <html>     <head>     <title>Inline JavaScript</title>     <meta charset="utf-8">     <meta name="viewport"           content="width=device-width, initial-scale=1">     <link rel="stylesheet"           href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></head>     <body>     <div class="container">         <h1 style="text-align:center;color:green;">           GeeksforGeeks       </h1>         <form>             <div class="form-group">                 <label for="">Enter Your Name:</label>                 <input id="name"                       class="form-control"                        type="text"                        placeholder="Input Your Name Here">             </div>             <div class="form-group">                 <button id="btn-alert"                        class="btn btn-success btn-lg float-right"                         type="submit">                      Submit                  </button>             </div>         </form>     </div>     <script>        var user_name = document.getElementById("name");        document.getElementById("btn-alert").addEventListener("click", function(){            var value=user_name.value.trim();            if(!value)                alert("Name Cannot be empty!");            else                alert("Hello, " + value + "!\nGreetings From GeeksforGeeks.");        });    </script></body>    </html> 
Output:
As soon as we enter a name and press the submit button, the JavaScript code inside the script tag will be triggered and we will get a pop-up message with our name and greeting text.
For deeper knowledge, you can visit What is the inline function in JavaScript ?
Note: Using Inline JavaScript is a bad practice and it is not recommended. It can be used for demonstration purposes so that the demonstrator doesn’t have to deal with 2 separate files at a time. It is recommended to write JavaScript code in a separate .js file and then link the same using src attribute in the script tag.
Picked
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
Different ways to import csv file in Pandas

19 Dec, 2018
CSV files are the “comma separated values”, these values are separated by commas, this file can be view like as excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format.
Let’s see the different ways to import csv file in Pandas.
Method #1: Using read_csv() method.
# importing pandas module  import pandas as pd        # making data frame  df = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")      df.head(10) 
Output:
 Providing file_path.
# import pandas as pdimport pandas as pd   # Takes the file's folderfilepath = r"C:\Gfg\datasets\nba.csv"   # read the CSV filedf = pd.read_csv(filepath)   # print the first five rowsprint(df.head())
Output: Method #2: Using csv module.
One can directly import the csv files using csv module.
# import the module csvimport csvimport pandas as pd   # open the csv filewith open(r"C:\Users\Admin\Downloads\nba.csv") as csv_file:           # read the csv file    csv_reader = csv.reader(csv_file, delimiter=',')           # now we can use this csv files into the pandas    df = pd.DataFrame([csv_reader], index=None)    df.head()      # iterating values of first columnfor val in list(df[1]):    print(val)
Output:
Picked
Python pandas-basics
Python-pandas
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
Taylor’s Theorem and Taylor series

03 May, 2020
Taylor’s theorem is used for the expansion of the infinite series such as  etc. so that we can approximate the values of these functions or polynomials. Taylor’s theorem is used for approximation of k-time differentiable function.
Statement:Let the (n-1)th derivative of  i.e. be continuous in  the nth derivative exist in  and  be a given positive integer. Then there exists at least one number  lying between 0 and 1 such that:.....
where  and Putting x=a+h or h=x-a we write equation as:.....Taylor’s remainders Rn after n terms due to:1. Cauchy: we just put p=1 in the Taylor’s theorem to get 2. Lagrange: p=n gives 
Taylor’s formula :Using Lagrange’s remainder we get the Taylor’s formula:..... where As n →∞ if R→0 then the last term of the formula becomesTherefore the Taylor’s formula further reduces toThis formula is now used to give the infinite series expansion of f(x) about point a.
Example:Obtain the Taylor’s series expansion ofabout the point x= -1.
Explanation:According to the formula we have a= -1 here and f(x) is provided to us. First of all we need to calculate f(a) and then we calculate derivatives of f(x) at given point until it becomes zero.Now we stop here as the next derivative will be zero. f^n(x)
=0 for n>5 
Thus the Taylor series expansion of f(x) about x= -1 is:.....
Substituting the values as calculated by us we get
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java - How to Use Comparator?

Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that defines precisely what sorted order means.
The Comparator interface defines two methods: compare( ) and equals( ). The compare( ) method, shown here, compares two elements for order −
int compare(Object obj1, Object obj2)

obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.
The equals( ) method, shown here, tests whether an object equals the invoking comparator −
boolean equals(Object obj)

obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.
Overriding equals( ) is unnecessary, and most simple comparators will not do so.
import java.util.*;

class Dog implements Comparator<Dog>, Comparable<Dog> {
   private String name;
   private int age;
   Dog() {
   }

   Dog(String n, int a) {
      name = n;
      age = a;
   }

   public String getDogName() {
      return name;
   }

   public int getDogAge() {
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d) {
      return (this.name).compareTo(d.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1) {
      return d.age - d1.age;
   }
}

public class Example {

   public static void main(String args[]) {
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy", 3));
      list.add(new Dog("Lacy", 2));
      list.add(new Dog("Roger", 10));
      list.add(new Dog("Tommy", 4));
      list.add(new Dog("Tammy", 1));
      Collections.sort(list);   // Sorts the array list

      for(Dog a: list)   // printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");
      
      for(Dog a: list)   // printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+ a.getDogAge() + ", ");
   }
}
This will produce the following result −
Lacy, Roger, Shaggy, Tammy, Tommy,
Tammy  : 1, Lacy  : 2, Shaggy  : 3, Tommy  : 4, Roger  : 10,

Note − Sorting of the Arrays class is as the same as the Collections.

    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to catch all the exceptions in C++?

Exceptions are the problems which arise at the time of execution of program. It is an event which is thrown at runtime. It protects the code and run the program even after throwing an exception. Exception handling is used to handle the exceptions. We can use try catch block to protect the code.
Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
Here is an example of catching all the exceptions in C++ language,
 Live Demo
#include <iostream>
using namespace std;

void func(int a) {
   try {
      if(a==0) throw 23.33;
      if(a==1) throw 's';
   } catch(...) {
      cout << "Caught Exception!\n";
   }
}
int main() {
   func(0);
   func(1);
   return 0;
}
Here is the output
Caught Exception!
Caught Exception!
unordered_set rehash() function in C++ STL - GeeksforGeeks

28 Sep, 2018
The unordered_set::rehash() is a built-in function in C++ STL which is used to set the number of buckets in the container of unordered_set to given size or more. If size is greater than the current size of the container, then rehash is called. If it is lower than the current size, then the function has no effect on bucket count of hash.
Syntax:
unordered_set_name.rehash(size_type n)
Parameter: The function accepts a mandatory parameter n which specifies the minimum number of buckets for the container.
Return Value: This function doesn’t returns anything.
Below programs illustrate the unordered_set::rehash() function:
Program 1:
// C++ program to illustrate the// unordered_set::rehash()#include <iostream>#include <string>#include <unordered_set>  using namespace std;  int main(){    // declaration    unordered_set<string> us;      // rehashed    us.rehash(9);      // insert elements    us.insert("geeks");    us.insert("for");    us.insert("geeks");    us.insert("users");      for (auto it = us.begin(); it != us.end(); it++) {        cout << *it << " ";    }      cout << "\nThe bucket count is "         << us.bucket_count();      return 0;}
users for geeks 
The bucket count is 11

Program 2:
// C++ program to illustrate the// unordered_set::rehash()#include <iostream>#include <string>#include <unordered_set>  using namespace std;  int main(){    // declaration    unordered_set<string> us;      // rehash the unordered_set    us.rehash(20);      // insert strings    us.insert("geeks");    us.insert("for");    us.insert("geeks");    us.insert("users");    us.insert("are");    us.insert("experts");    us.insert("in");    us.insert("DS");      // prints the elements    for (auto it = us.begin(); it != us.end(); it++) {        cout << *it << " ";    }      cout << "\nThe bucket count is "         << us.bucket_count();      return 0;}
DS in experts are users for geeks 
The bucket count is 23

CPP-Functions
cpp-unordered_set
cpp-unordered_set-functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Multidimensional Arrays in C / C++
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Bitwise Operators in C/C++
Virtual Function in C++
Iterators in C++ STL
Constructors in C++
Copy Constructor in C++
Tryit Editor v3.7

Tryit: HTML footer element
Word Dictionary using Python Tkinter

In this article, we will create a GUI-based dictionary using PyDictionary and Tkinter
Module.
PyDictionary is a Python Module that helps to get meaning translations, antonyms and synonyms of words. It uses WordNet for getting meanings, Google for translations, and synonym.com for getting synonyms and antonyms. PyDictionary uses BeautifulSoup, Requests module as the dependencies.
In order to create the application, we will first install these modules in our environment using pip install PyDictionary
After installing, we will create a tkinter frame and some other element.
# Import Required Librares
from tkinter import *
from PyDictionary import PyDictionary

# Create instances and objests
dictionary = PyDictionary()
win =Tk()

#Define the size of the window
win.geometry("700x400")

win.title("Python Dictionary")

#Define Helper Function to use the other atributes of PyDictionary Class
def dict():
   meaning.config(text=dictionary.meaning(word.get())['Noun'][0])

#Define Labels and Buttons
Label(win, text="Dictionary", font=("Times New Roman" ,20)).pack(pady=20)

# Frame 1
frame = Frame(win)
Label(frame, text="Type any Word ", font=("Poppins bold", 15)).pack(side=LEFT)
word = Entry(frame, font=("Times New Roman", 15))
word.pack()
frame.pack(pady=10)
# Frame 2
frame1 = Frame(win)
Label(frame1, text="Meaning:", font=("Aerial", 18)).pack(side=LEFT)
meaning = Label(frame1, text="", font=("Poppins",15), width= 30)
meaning.pack()
frame1.pack(pady=10)

Button(win, text="Find", font=("Poppins bold",15), command=dict).pack()

# Execute Tkinter
win.mainloop()
Running the above code will create and display the Dictionary Application. However,
using PyDictionary, we can add other attributes like finding synonym, antonyms, etc.
Now, type “Hello” in the textbox and click the “Find” button. It will pull the meaning of “Hello” from the dictionary.
How to add a title to JTable in Java Swing?

To display a title to the JTable, you can set a title for the JPanel, which already consists of a JTable.
Here, we are using createTitledBorder() for the JPanel to set the title for the panel border that would eventually work for table title.
Let’s say the following is the JPanel −
JPanel panel = new JPanel();
Now, use setBorder() and the BorderFactory class to set a title border for the panel that would be our table title as well −
panel.setBorder(BorderFactory.createTitledBorder(
   BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT,
TitledBorder.TOP));
The following is an example to add a title to a JTable −
package my;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder(
      BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT,
      TitledBorder.TOP));
      String[][] rec = {
         { "001", "David", "AUS" },
         { "002", "Steve", "AUS" },
         { "003", "Yuvraj", "IND" },
         { "004", "Kane", "NZ" },
         { "005", "Ben", "ENG" },
         { "006", "Eion", "ENG" },
         { "007", "Miller", "SA" },
         { "008", "Rohit", "IND" }
      };
      String[] header = { "Id", "Player", "Team" };
      JTable table = new JTable(rec, header);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
Java String contains() Method

❮ String Methods

Find out if a string contains a sequence of characters:
String myStr = "Hello";
System.out.println(myStr.contains("Hel"));   // true
System.out.println(myStr.contains("e"));     // true
System.out.println(myStr.contains("Hi"));    // false

Try it Yourself »

The contains() method checks whether a string contains a sequence of characters.
Returns true if the characters exist and false if not.
public boolean contains(CharSequence chars)

The CharSequence interface is a readable sequence of char values, found in the java.lang package.
true - sequence of characters exists
false - sequence of characters do not exist
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Rexx - ask Command

This command is used to read a line from the default input stream.
variable = ask 

Variable − The variable to store the value entered by the user.
Variable − The variable to store the value entered by the user.
None
/* Main program */ 
input = ask 
say input
When we run the above program we will get the following result. If we input the value hello, we will get the output of hello.
ASK

 Print
 Add Notes
 Bookmark this page
How does [\d+] regular expression work in Python?

The following code shows what the regular expression [\d+] does on the given string
[\d+] regular expression refers to one digit (0-9) or + character 
import re
result = re.findall(r'[\d+]', 'Taran123tula+456')
print result
['1', '2', '3', '+', '4', '5', '6']
C++ List Library - remove_if() Function

The C++ function std::list::remove_if() removes elements from the list that fulfills the condition. It removes all elements for which predicate returns true.
Following is the declaration for std::list::remove_if() function form std::list header.
template <class Predicate>
void remove_if (Predicate pred);

pred − Unary predicate that, which takes a value of the same type and returns true for those values to be removed from the container.
None.
If pred is guaranteed to not throw, then function never throws exceptions.
Linear i.e. O(n)
The following example shows the usage of std::list::remove_if() function.
#include <iostream>
#include <list>

using namespace std;

bool foo(int n) {
   return (n > 5);
}

int main(void) {
   list<int> l = {1, 2, 3, 4, 5, 6, 7, 8, 9};

   cout << "Contents of list before remove_if operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   /* remove all elements larger than 5 */
   l.remove_if(foo);

   cout << "Contents of list after remove_if operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Contents of list before remove_if operation
1
2
3
4
5
6
7
8
9
Contents of list after remove_if operation
1
2
3
4
5

 Print
 Add Notes
 Bookmark this page
What are the rules to declare variables in C++?

To declare a variable, you need to know what data type it is going to be of and what its name would be. The variable name has constraints on what you can name it. Following are the rules for naming variables −
 Variable names in C++ can range from 1 to 255 characters.
 All variable names must begin with a letter of the alphabet or an underscore(_).
 After the first initial letter, variable names can also contain letters and numbers.  
 Variable names are case sensitive.
 No spaces or special characters are allowed.
 You cannot use a C++ keyword (a reserved word) as a variable name.
Here are some examples of acceptable variable names −
mohd        Piyush    abc    move_name  a_123
myname50   _temp       j     a23b9      retVal
You can declare variables using the syntax −
datatype variable_name;
For example,
int my_var;
float my_float;
...
Python - Largest number possible from list of given numbers

In this article, we are going to learn how to find the possible largest number from the given list of numbers. We will see two different ways to find to solve the problem. Follow the below steps to solve the problem.
Import the itertools module for permutations method.
Initialize the list with numbers and an empty list.
Iterate over the permutations of the list.Join all the combinations and add the result to the empty list.
Join all the combinations and add the result to the empty list.
Find the max number from the result with max method and key as int.
Convert the string to integer and print it.
Let's see the code.
 Live Demo
# importing the module
import itertools

# initializing the list
numbers = [45, 35, 138, 43, 67]

# result
result = []

# permutations
for permutation in itertools.permutations(str(number) for number in numbers):
   result.append(''.join(permutation))

# finding max
maximum = max(result, key=int)

# printing the max
print(int(maximum))
If you run the above code, then you will get the following result.
67454335138

Let's see another way to solve the problem. We will sorted function to solve the problem. Follow the below steps to write the code.
Pass the list to the sorted function.
Write a function called get_key that accepts two arguments.
Return -1 if the str(first) + str(second) > str(second) + str(first) else 1.
Joining the list of elements using join method.
Print the result by converting into an integer.
As we are using a function as key, we have to convert it to the key using cmp_to_key method from functools. Let's see the code.
 Live Demo
from functools import cmp_to_key

# initializing the list
numbers = [45, 35, 138, 43, 67]

def get_key(first, second):
   if str(first) + str(second) > str(second) + str(first):
      return -1
   return 1

# getting the result
result = sorted(numbers, key=cmp_to_key(get_key))

# joining the result
result = "".join(str(integer) for integer in result)

# printing the result
print(int(result))
If you run the above code, then you will get the following result.
67454335138

If you have any queries in the tutorial, mention them in the comment section.
Auto insert values into a MySQL table in a range?

For this, you can create a stored procedure. Let us first create a table.
mysql> create table DemoTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.55 sec)
Following is the query to create a stored procedure to auto insert values to a table from range 10 to 20 −
mysql> DELIMITER //
mysql> CREATE PROCEDURE AutoInsertValuesToTable()
   -> BEGIN
   ->    DECLARE startingRange INT DEFAULT 10;
   ->    WHILE startingRange <= 20 DO
   ->       INSERT DemoTable(Value) VALUES (startingRange );
   ->       SET startingRange = startingRange + 1;
   ->    END WHILE;
   -> END
   -> //
Query OK, 0 rows affected (0.23 sec)
mysql> DELIMITER ;
Here is the query to call the stored procedure −
mysql> call AutoInsertValuesToTable();
Query OK, 1 row affected (1.10 sec)
Now you can check the value is inserted into the above table or not −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
|    10 |
|    11 |
|    12 |
|    13 |
|    14 |
|    15 |
|    16 |
|    17 |
|    18 |
|    19 |
|    20 |
+-------+
11 rows in set (0.00 sec)
The value inserted into the above table successfully from range 10 to 20.
Pascal - Nested Loops

Pascal allows using one loop inside another loop. Following section shows few examples to illustrate the concept.
The syntax for a nested for-do loop statement in Pascal is as follows −
for variable1:=initial_value1 to [downto] final_value1 do

begin
   for variable2:=initial_value2 to [downto] final_value2 do
   
   begin   
      statement(s);
   end;
end;   
The syntax for a nested while-do loop statement in Pascal is as follows −
while(condition1)do

begin
   while(condition2) do
   
   begin
      statement(s);
   end;
   statement(s);
end;
The syntax for a nested repeat ... until loop Pascal is as follows −
repeat
   statement(s);
   repeat
      statement(s);
   until(condition2);
until(condition1);
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.
The following program uses a nested for loop to find the prime numbers from 2 to 50 −
program nestedPrime;
var
   i, j:integer;

begin
   for i := 2 to 50 do
   
   begin
      for j := 2 to i do
         if (i mod j)=0  then
            break; {* if factor found, not prime *}
      
      if(j = i) then
         writeln(i , ' is prime' );
   end;
end.
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime


    94 Lectures 
     8.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to save a plot in pdf in R?

To save a plot in pdf, we can use the pdf function in base R. For example, if we want to save a plot with the name PDF then it can be done using the below command −
pdf("PDF.pdf")
After this we can create the plot and use dev.off().
pdf("pdfExample.pdf")
plot(1:10)
 Live Demo
dev.off()
To check where it is saved, find the working directory using getwd().
D3.js | d3.scaleIdentity() Function - GeeksforGeeks

12 Feb, 2021
The d3.scaleIdentity() function in D3.js is used to construct a new identity scale with the unit domain [0, 1] and the unit range [0, 1].Syntax:  
d3.scaleIdentity().domain(array of values).range(array of values);
Parameters: This function does not accept any parameters.Return Value: This function returns the corresponding range for the domain’s value. Below program illustrate the d3.scaleIdentity() function in D3.js:Example:  
javascript
<!DOCTYPE html><html> <head>    <title></title>    <script src="https://d3js.org/d3.v4.min.js">  </script></head> <body>     <script>        // Calling the scaleIdentity() function        var A = d3.scaleIdentity()            .domain([0, 1])            .range([0, 1]);         // Getting the corresponding range for        // the domain value        console.log(A('0'));        console.log(A('1'));    </script></body> </html>
Output:  
0
1
Reference: https://devdocs.io/d3~5/d3-scale#scaleBand 
arorakashish0911
D3.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
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 redirect to another page in ReactJS ?
Top 10 Angular Libraries For Web Developers
How to Insert Form Data into Database using PHP ?
How to execute PHP code using command line ?
How to pass data from child component to its parent in ReactJS ?
Tryit Editor v3.7

CSS Media Queries
Tryit: Simple example of using media queries
Python | Convert string enclosed list to list - GeeksforGeeks

20 May, 2019
Given a list enclosed within string (or quotes), write a Python program to convert the given string to list type.
Examples:
Input : "[0, 2, 9, 4, 8]"
Output : [0, 2, 9, 4, 8]

Input : "['x', 'y', 'z']"
Output : ['x', 'y', 'z']

 Approach #1 : Python eval()
The eval() method parses the expression passed to this method and runs python expression (code) within the program. Here it takes the list enclosed within quotes as expression and runs it, and finally returns the list.
# Python3 program to ways to convert # list enclosed within string to list  def convert(lst):    return eval(lst)      # Driver codelst = "[0, 2, 9, 4, 8]"print(convert(lst))
[0, 2, 9, 4, 8]

 Approach #2 : Using literal_eval()
literal_eval() function works same as eval() with the only difference that it raises an exception if the input isn’t a valid Python datatype, the code won’t be executed.
# Python3 program to ways to convert # list enclosed within string to listfrom ast import literal_eval  def convert(lst):    return literal_eval(lst)      # Driver codelst = "[0, 2, 9, 4, 8]"print(convert(lst))
[0, 2, 9, 4, 8]

 Approach #3 : Using json.loads()
# Python3 program to ways to convert # list enclosed within string to listfrom json import loads  def convert(lst):    return loads(lst)      # Driver codelst = "[0, 2, 9, 4, 8]"print(convert(lst))
[0, 2, 9, 4, 8]

Python list-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Get the substring of the column in Pandas-Python - GeeksforGeeks

10 Jul, 2020
Now, we’ll see how we can get the substring for all the values of a column in a Pandas dataframe. This extraction can be very useful when working with data. For example, we have the first name and last name of different people in a column and we need to extract the first 3 letters of their name to create their username.
Example 1:We can loop through the range of the column and calculate the substring for each value in the column.
# importing pandas as pdimport pandas as pd   # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington",                 "Rosie Bates", "Emily Edward"]}  # converting the dictionary to a# dataframedf = pd.DataFrame.from_dict(dict)  # storing first 3 letters of namefor i in range(0, len(df)):    df.iloc[i].Name = df.iloc[i].Name[:3]  df
Output:
Note: For more information, refer Python Extracting Rows Using Pandas
Example 2: In this example we’ll use str.slice().
# importing pandas as pdimport pandas as pd   # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington",                "Rosie Bates", "Emily Edward"]}  # converting the dictionary to a # dataframedf = pd.DataFrame.from_dict(dict)  # storing first 3 letters of name as usernamedf['UserName'] = df['Name'].str.slice(0, 3)  df
Output:
Example 3: We can also use the str accessor in a different way by using square brackets.
# importing pandas as pdimport pandas as pd   # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington",                 "Rosie Bates", "Emily Edward"]}  # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict)  # storing first 3 letters of name as usernamedf['UserName'] = df['Name'].str[:3]  df
Output:
Example 4: We can also use str.extract for this task. In this example we’ll store last name of each person in “LastName” column.
# importing pandas as pdimport pandas as pd   # creating a dictionarydict = {'Name':["John Smith", "Mark Wellington",                "Rosie Bates", "Emily Edward"]}  # converting the dictionary to a dataframedf = pd.DataFrame.from_dict(dict)  # storing lastname of each persondf['LastName'] = df.Name.str.extract(r'\b(\w+)$',                                      expand = True)  df
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
SQL | Create Table Extension - GeeksforGeeks

21 Mar, 2018
SQL provides an extension for CREATE TABLE clause that creates a new table with the same schema of some existing table in the database.
It is used to store the result of complex queries temporarily in a new table.
The new table created has the same schema as the referencing table.
By default, the new table has the same column names and the data type of the referencing table.
Syntax:
CREATE TABLE newTable LIKE pets
Example:
CREATE TABLE newTable as
            (SELECT * 
             FROM pets
             WHERE pets.BREED = 'German Shepherd')

Queries
pets table:
Query 1:
CREATE TABLE newTable LIKE pets;
SELECT * 
FROM newTable 
where newTable.GENDER = 'Female';
Output:
Explanation: The newTable created is a copy of pets table. So, selecting female pets from newTable returns only two rows in which the pet is a female.Query 2 :
CREATE TABLE newTable as
            (SELECT * 
             FROM pets
             WHERE pets.BREED = 'German Shepherd');
SELECT * from newTable;

Output:
Explanation: First the inner query is evaluated and the results are stored in a new temporary relation. Following this, the outer query is evaluated which create newTable as add the output of inner query to newTable.
References : Database System Concepts 6th Edition by Silberschatz
This article is contributed by Mayank Kumar. 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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Interview Questions
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL - ORDER BY
How to Create a Table With Multiple Foreign Keys in SQL?
C Program for Binary Insertion Sort - GeeksforGeeks

13 Feb, 2022
We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search.
C/C++
C
// C program for implementation of binary insertion sort#include <stdio.h> // A binary search based function to find the position// where item should be inserted in a[low..high]int binarySearch(int a[], int item, int low, int high){    if (high <= low)        return (item > a[low])?  (low + 1): low;     int mid = (low + high)/2;     if(item == a[mid])        return mid+1;     if(item > a[mid])        return binarySearch(a, item, mid+1, high);    return binarySearch(a, item, low, mid-1);} // Function to sort an array a[] of size \'n\'void insertionSort(int a[], int n){    int i, loc, j, selected;     for (i = 1; i < n; ++i)    {        j = i - 1;        selected = a[i];         // find location where selected should be inserted        loc = binarySearch(a, selected, 0, j);         // Move all elements after location to create space        while (j >= loc)        {            a[j+1] = a[j];            j--;        }        a[j+1] = selected;    }} // Driver program to test above functionint main(){    int a[] = {37, 23, 0, 17, 12, 72, 31,              46, 100, 88, 54};    int n = sizeof(a)/sizeof(a[0]), i;     insertionSort(a, n);     printf("Sorted array: \n");    for (i = 0; i < n; i++)        printf("%d ",a[i]);     return 0;}
Please refer complete article on Binary Insertion Sort for more details!
sagartomar9927
sweetyty
archstanton
Insertion Sort
C Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Exit codes in C/C++ with Examples
C program to find the length of a string
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C Program to Check if a Given String is Palindrome - GeeksforGeeks

25 Jul, 2021
Given a string, write a c function to check if it is palindrome or not. A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome. 
 
Algorithm: isPalindrome(str) 1) Find length of str. Let length be n. 2) Initialize low and high indexes as 0 and n-1 respectively. 3) Do following while low index ‘l’ is smaller than high index ‘h’. .....a) If str[l] is not same as str[h], then return false. .....b) Increment l and decrement h, i.e., do l++ and h–. 4) If we reach here, it means we didn’t find a misFollowing is C implementation to check if a given string is palindrome or not. 
C
#include <stdio.h>#include <string.h> // A function to check if a string str is palindromevoid isPalindrome(char str[]){    // Start from leftmost and rightmost corners of str    int l = 0;    int h = strlen(str) - 1;     // Keep comparing characters while they are same    while (h > l)    {        if (str[l++] != str[h--])        {            printf("%s is not a palindrome\n", str);            return;        }    }    printf("%s is a palindrome\n", str);} // Driver program to test above functionint main(){    isPalindrome("abba");    isPalindrome("abbccbba");    isPalindrome("geeks");    return 0;}
abba is a palindrome
abbccbba is a palindrome
geeks is not a palindrome

Recursive function to check if a string is palindromePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
AbhijeetPrakash
rasheduliriyad
FactSet
Morgan Stanley
palindrome
Paytm
TCS
School Programming
Strings
Paytm
Morgan Stanley
FactSet
TCS
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Interfaces in Java
Constructors in C++
Operator Overloading in C++
Copy Constructor in C++
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack