code-rag-bench/online-tutorials huggingface dataset:
How do I switch to the active tab in Selenium?

We can switch to the active tab in Selenium. The methods Keys.chord and sendKeys are used to open a new tab. More than one key can be passed at once with the Keys.chord method.
The Keys.CONTROL and Keys.ENTER combined are passed as parameters to the Keys.chord method. This is stored as a string and again passed as a parameter to the sendKeys method.
String tb = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Company']")).sendKeys(tb);
All the window ids which are opened are stored in an array list. By default, the driver has the focus on the parent window. To switch the focus to the new tab, switchTo().window method is used.
The getWindowHandle method is used to hold the window id of the active tab and it is then passed as parameter to the switchTo().window method. The getWindowHandles method holds all the opened window ids.
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.ArrayList;
public class SwitchActiveTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // Keys.Chord string
      String tb = Keys.chord(Keys.CONTROL,Keys.ENTER);
      driver.findElement(By.xpath("//*[text()='FAQ']")).sendKeys(tb);
      Thread.sleep(10000);
      // store window ids in array list
      ArrayList<String> wid = new ArrayList<String>(driver.getWindowHandles());
      //switch to active tab
      driver.switchTo().window(wid.get(1));
      System.out.println("Page title of active tab: " + driver.getTitle());
      //switch to parent
      driver.switchTo().window(newTb.get(0));
      System.out.println("Page title of parent window: " + driver.getTitle());
      driver.quit();
   }
}
How to Handle alerts in Selenium?

We can handle alerts in Selenium webdriver by using the Alert interface. An alert can be of three types – a prompt which allows the user to input text, a normal alert and a confirmation alert.
By default, the webdriver can only access the main page, once an alert comes up, the method switchTo().alert() is used to shift the focus webdriver control to the alert.
A normal alert is shown below −
A confirmation alert is shown below −
A prompt alert is shown below −
To accept an alert (to click on the OK button in alert), the method switchTo().alert().accept() is used. To dismiss an alert (to click on the Cancel button in alert), the method switchTo().alert().dismiss() is used.
To extract the alert text, the method switchTo().alert().getText() is used. To input text inside a confirmation alert, the method switchTo().alert().sendKeys() is used.
The text to be entered is passed as a parameter to the sendKeys method.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
public class AlertHandle{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://the-internet.herokuapp.com/javascript_alerts");
      // identify element
      WebElement c=driver.findElement(By.xpath("//button[text()='Click for JS Prompt']"));
      c.click();
      //shift to alert
      Alert a = driver.switchTo().alert();
      //get alert text
      String s = a.getText();
      System.out.println("Alert text is: " + s);
      //input text to alert
      a.sendKeys("Selenium");
      //dismiss alert
      a.dismiss();
      c.click();
      //accept alert
      a.accept();
      driver.quit();
   }
}
C# program to remove all the numbers after decimal places

Use the Truncate method in C# to remove all the number after decimal places.
Let’s say the following is our number −
9.15M
To remove the numbers after decimal places, use Truncate() −
decimal.Truncate(9.15M)
Let us see the complete code −
 Live Demo
using System;
using System.Linq;
class Demo {
   static void Main() {
      decimal val = 9.15M;
      Console.WriteLine(decimal.Truncate(val));
   }
}
9
Difference between Single and Multiple Inheritance in C++ - GeeksforGeeks

16 Oct, 2019
Single Inheritance:Single inheritance is one in which the derived class inherits the single base class either publicly, privately or protectedly. In single inheritance, the derived class uses the features or members of the single base class. These base class members can be accessed by derived class or child class according to the access specifier specified during inheriting the parent class or base class.
Syntax:
Class DerivedClass_name : access_specifier Base_Class
{
    //Class's Body 
}; 
Example of Single Inheritance:
#include<iostream>using namespace std;class A {public:    int k = 1000;    float salary = 80000;};class B : public A {public:    float bonus = 8000;    void ts()    {        cout<<"Total salary.."<<(salary + bonus)<<endl;    }};int main(){    B b1;    cout<<"Salary:"<<b1.salary<<endl;    cout<<"Bonus:"<<b1.bonus<<endl;    b1.ts();    return 0;}
Output:
Salary: 80000
Bonus: 8000
total salary..88000 
In the this example, A is the base class or parent class and B is the derived class or child class.
Multiple Inheritance:Multiple inheritance is one in which the derived class acquires two or more base classes. In multiple inheritance, the derived class are allowed to use the joint features of the inherited base classes. Every base class is inherited by the derived class by notifying the separate access specifier for each of them. The base class members can be accessed by derived class or child class according to the access specifier specified during inheriting the parent class or base class.
Syntax:
Class DerivedClass_name : access_specifier Base_Class1, access_specifier Base_Class2
{
    //Class's Body 
}; 
Example of Multiple Inheritance:
#include<iostream>using namespace std;class A {public:    float salary = 80000;};  class B {public:    float bonus = 8000;};  class C : public A, public B {public:    void ts()    {        cout<<"Total salary.."<<(salary + bonus)<<endl;    }};int main(){    C b1;    b1.ts();    return 0;}
Output:
Total salary..88000 
In the this example, A and B are the base classes and C is the derived class.
Difference between Single and multiple Inheritance:
cpp-class
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Iterators in C++ STL
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Differences between Black Box Testing vs White Box Testing
Getting month name instead of numeric month number in report in SAP

There are various methods this can be done
a) Use the Function module MONTH_NAME_GET - This Function module is used to return all the month and names in the respective language.
b) You can also use the below formula −
cstr(monthname(month({inputdate})))
where “inputdate” is the date for which month name is required.
c) Find the numeric value of month and use if condition. For example -
IF month = “01” THEN January
Plotting animated quivers in Python using Matplotlib

To animate quivers in Python, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create u and v data points using numpy.
Create a figure and a set of subplots.
Plot a 2D field of arrows using quiver() method.
To animate the quiver, we can change the u and v values, in animate() method. Update the u and v values and the color of the vectors.
To display the figure, use show() method.
import numpy as np
import random as rd
from matplotlib import pyplot as plt, animation

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

x, y = np.mgrid[:2 * np.pi:10j, :2 * np.pi:5j]
u = np.cos(x)
v = np.sin(y)

fig, ax = plt.subplots(1, 1)
qr = ax.quiver(x, y, u, v, color='red')

def animate(num, qr, x, y):
   u = np.cos(x + num * 0.1)
   v = np.sin(y + num * 0.1)
   qr.set_UVC(u, v)
   qr.set_color((rd.random(), rd.random(), rd.random(), rd.random()))
   return qr,

anim = animation.FuncAnimation(fig, animate, fargs=(qr, x, y),
                              interval=50, blit=False)

plt.show()
How to declare global variables in Android?

This example demonstrates How to declare global variables in Android?
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/actionEvent"
      android:textSize = "40sp"
      android:layout_marginTop = "30dp"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show global variable.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView actionEvent;
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      actionEvent = findViewById(R.id.actionEvent);
      actionEvent.setText("Click");
      actionEvent.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            singleToneClass singleToneClass = com.example.myapplication.singleToneClass.getInstance();
            singleToneClass.setData("Tutorialspoint.com");
            actionEvent.setText(singleToneClass.getData());
         }
      });
   }
}
Step 4 − Add the following code to src/singleToneClass.java
package com.example.myapplication;
public class singleToneClass {
   String s;
   private static final singleToneClass ourInstance = new singleToneClass();
   public static singleToneClass getInstance() {
      return ourInstance;
   }
   private singleToneClass() {
   }
   public void setData(String s) {
      this.s = s;
   }
   public String getData() {
      return s;
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Now click on textview, it will show the result as shown below –
Click here to download the project code
How to do session handling in Selenium Webdriver?

We can perform session handling with the help of Selenium webdriver with a TestNG framework. To trigger different sessions, we shall use the attribute parallel in the TestNG XML file.
A TestNG execution configuration is done in the TestNG XML. To create multiple sessions, we shall add the attributes – parallel and thread-count in the XML file.
The attribute thread-count controls the number of sessions to be created while executing the tests in a parallel mode. The value of parallel attribute is set to methods.
In our example, we would have three methods with three different session ids which are executing in parallel.
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.SessionId;
public class TestNG10 {
   @Test
   public void myTest () {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/index.htm");
      //get session ID
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }@Test
   public void myTest1 () {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.google.com/");
      //get session ID
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }@Test
   public void myTest2 () {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //launch URL
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm/");
      //get session ID
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }
}
TestNG XML Implementation.
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<!—parallel methods set for execution with 3 threads-->
<suite name="Test-Suite" parallel="methods" thread-count="3">
   <test name="Tutorialspoint" >
      <classes>
         <class name="TestNG10" />
      </classes>
   </test>
</suite>
Fuzzy Search in JavaScript - GeeksforGeeks

05 Nov, 2020
Fuzzy searching matches the meaning, not necessarily the precise wording or specified phrases. It performs something the same as full-text search against data to see likely misspellings and approximate string matching. it’s a very powerful tool that takes into consideration the context of the phrase you wish to look.
Fuzzy Search is additionally called as approximate string matching. It’s powerful because often text data is messy. For instance, shorthand and abbreviated text are common in various sorts of data. Additionally, outputs from OCR or voice to text conversions tend to be messy or imperfect. Thus, we want to make the foremost of our data by extrapolating the maximum amount of information as possible.
Fuzzy search is more powerful than exact searching when used for research and investigation. Fuzzy search is very useful when researching unfamiliar, foreign-language, or sophisticated terms, the correct spellings of which don’t seem to be widely known. Fuzzy search can also be used to locate individuals supported incomplete or partially inaccurate identifying information.
Installing the package:
$ npm install --save fuse.js
Example:
Javascript
const Fuse = require('fuse.js') const people = [    {        name: "John",        city: "New York"    },    {        name: "Steve",        city: "Seattle"    },    {        name: "Bill",        city: "Omaha"    }] const fuse = new Fuse(people, {    keys: ['name', 'city']}) // Searchconst result = fuse.search('jon') console.log(result)
Output:
[ { item: { name: 'John', city: 'New York' }, refIndex: 0 } ]

Some common fuzzy search libraries for JavaScript are:
List.js : https://listjs.com/
Fuse.js : https://fusejs.io/
Fuzzy-search :https://www.npmjs.com/package/fuzzy-search
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Express.js express.Router() Function
How to set input type date in dd-mm-yyyy format using HTML ?
Installation of Node.js on Linux
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
C Program for Reversed String Pattern

Given a string str, our task is to print its reversed pattern. The Pattern will be incremental in reversed order, and when the string is completed fill ‘*’ in the remaining places.
Like we enter a string “abcd”, now in first line we have to print “a” then in next line we have to print “cb” and then in third line we will print “**d”.
Input: str[] = { “abcd” }
Output: a
c b
* * d
Explanation −
In first line print 1 character
In second line print 2 characters in reverse order
In third line Print 3 characters in reverse order, if the string is less than 3 then print the characters and fill the blank spaces with *.
Input: str[] = {“tutorialspoint”}
Output:
The approach used below is as follows −
We will traverse the string from i=0 and will check i<n && k<(n-i)*2 is true
Then we will take a variable k and Set k as ((i*(i+1))/2)-1
We will check If k >= n-1 then, will Print "* " else will print the string’s value in reverse order
Start
In function int reverse_it(char str[], int n)
   Step 1-> Declare and Initialize i, j=0 , k=0
   Step 2-> Loop For i=0 and i<n && k<(n-i)*2 and i++
      Set k as ((i*(i+1))/2)-1
      Loop For j=0 and j<i && k<(n-i)*2 and j++
      If k >= n-1 then,
         Print "* "
      Else
         Print "%c ",str[k]
         Decrement k by 1
      End loop
      Print new line
   End loop
In Function int main(int argc, char const *argv[])
   Step 1-> Declare and initialize string str[]
   Step 2-> Declare and Initialize size as sizeof(str)/sizeof(str[0])
   Step 3-> Call function reverse_it(str, size);
Stop
 Live Demo
#include <stdio.h>
int reverse_it(char str[], int n) {
   int i, j=0 , k=0;
   for(i=0; i<n && k<(n-i)*2; i++) {
      //Assigning k
      k = ((i*(i+1))/2)-1;
      for(j=0; j<i && k<(n-i)*2; j++) {
         //will check if k is greater than the total number of characters
         //then we will print * for filling the extra characters
         if(k >= n-1)
            printf("* ");
            //print the string in reverse order
         else
            printf("%c ",str[k]);
            k--;
      }
      //for line break after reverse sequence
      printf("\n");
   }
   return 0;
}
//Main Function
int main(int argc, char const *argv[]) {
   char str[] = {"tutorialspoint"};
   int size = sizeof(str)/sizeof(str[0]);
   reverse_it(str, size);
   return 0;
}
If run the above code it will generate the following output −
Java Examples - Use Collections

How to use different types of Collections ?
Following example uses different types of collection classes and adds an element in those collections.
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;

public class Main {
   public static void main(String[] args) {
      List lnkLst = new LinkedList();
      lnkLst.add("element1");
      lnkLst.add("element2");
      lnkLst.add("element3");
      lnkLst.add("element4");
      displayAll(lnkLst);
      
      List aryLst = new ArrayList();
      aryLst.add("x");
      aryLst.add("y");
      aryLst.add("z");
      aryLst.add("w");
      displayAll(aryLst);
      
      Set hashSet = new HashSet();
      hashSet.add("set1");
      hashSet.add("set2");
      hashSet.add("set3");
      hashSet.add("set4");
      displayAll(hashSet);
      
      SortedSet treeSet = new TreeSet();
      treeSet.add("1");
      treeSet.add("2");
      treeSet.add("3");
      treeSet.add("4");
      displayAll(treeSet);
      
      LinkedHashSet lnkHashset = new LinkedHashSet();
      lnkHashset.add("one");
      lnkHashset.add("two");
      lnkHashset.add("three");
      lnkHashset.add("four");
      displayAll(lnkHashset);
      
      Map map1 = new HashMap();
      map1.put("key1", "J");
      map1.put("key2", "K");
      map1.put("key3", "L");
      map1.put("key4", "M");
      displayAll(map1.keySet());
      displayAll(map1.values());
      
      SortedMap map2 = new TreeMap();
      map2.put("key1", "JJ");
      map2.put("key2", "KK");
      map2.put("key3", "LL");
      map2.put("key4", "MM");
      displayAll(map2.keySet());
      displayAll(map2.values());
      
      LinkedHashMap map3 = new LinkedHashMap();
      map3.put("key1", "JJJ");
      map3.put("key2", "KKK");
      map3.put("key3", "LLL");
      map3.put("key4", "MMM");
      displayAll(map3.keySet());
      displayAll(map3.values());
   }
   static void displayAll(Collection col) {
      Iterator itr = col.iterator();
      while (itr.hasNext()) {
         String str = (String) itr.next();
         System.out.print(str + " ");
      }
      System.out.println();
   }
}
The above code sample will produce the following result.
element1 element2 element3 element4 
x y z w 
set1 set2 set3 set4 
1 2 3 4 
one two three four 
key4 key3 key2 key1 
M L K J 
key1 key2 key3 key4 
JJ KK LL MM 
key1 key2 key3 key4 
JJJ KKK LLL MMM 

 Print
 Add Notes
 Bookmark this page
std::all_of() in C++ - GeeksforGeeks

06 Jul, 2017
The C++ function is defined in <algorithm> library in STL. This function operates on whole range of array elements and can save time to run a loop to check each elements one by one. It checks for a given property on every element and returns true when each element in range satisfies specified property, else returns false.Syntax:
template <class InputIterator, class UnaryPredicate>
bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred);
first : Input iterators to the initial positions in a sequence.
last : Input iterators to the final positions in a sequence.
pred : An unary predicate function that accepts an element and returns a bool.
Exception : Throws exception if either predicate or an operation on an iterator throws exception.Examples:
// C++ code to demonstrate working of all_of()#include <vector>#include <algorithm>#include <iostream>int main(){    std::vector<int> v(10, 2);          // illustrate all_of    if (std::all_of(v.cbegin(), v.cend(), [](int i){ return i % 2 == 0; }))     {        std::cout << "All numbers are even\n";    }  }
Output:
All numbers are even

// C++ code to demonstrate working of all_of()#include<iostream>#include<algorithm> // for all_of()using namespace std;int main(){    // Initializing array    int ar[6] =  {1, 2, 3, 4, 5, -6};      // Checking if all elements are positive    all_of(ar, ar+6, [](int x) { return x>0; })?          cout << "All are positive elements" :          cout << "All are not positive elements";      return 0;  }
Output:
All are not positive elements

In the above code, -6 being a negative element negates the condition and returns false.
Useful array algorithms STL functions
This article is contributed by Manjeet Singh . 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.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
List in C++ Standard Template Library (STL)
PriorityQueue iterator() Method in Java - GeeksforGeeks

10 Dec, 2018
The Java.util.PriorityQueue.iterator() method is used to return an iterator of the same elements as the Priority Queue. The elements are returned in random order from what present in the Queue.
Syntax:
Iterator iterate_value = Priority_Queue.iterator();

Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the queue and returns the values(iterators).
Below programs illustrate the Java.util.PriorityQueue.iterator() method:Program 1:
// Java code to illustrate iterator()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<String> queue = new PriorityQueue<String>();          // Use add() method to add elements into the Queue        queue.add("Welcome");        queue.add("To");        queue.add("Geeks");        queue.add("4");        queue.add("Geeks");          // Displaying the PriorityQueue        System.out.println("PriorityQueue: " + queue);          // Creating an iterator        Iterator value = queue.iterator();          // Displaying the values after iterating through the queue        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
PriorityQueue: [4, Geeks, To, Welcome, Geeks]
The iterator values are: 
4
Geeks
To
Welcome
Geeks

Program 2:
// Java code to illustrate iterator()import java.util.*;  public class PriorityQueueDemo {    public static void main(String args[])    {        // Creating an empty PriorityQueue        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();          // Use add() method to add elements into the Queue        queue.add(10);        queue.add(15);        queue.add(30);        queue.add(20);        queue.add(5);          // Displaying the PriorityQueue        System.out.println("PriorityQueue: " + queue);          // Creating an iterator        Iterator value = queue.iterator();          // Displaying the values after iterating through the queue        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
PriorityQueue: [5, 10, 30, 20, 15]
The iterator values are: 
5
10
30
20
15

Java - util package
Java-Collections
Java-Functions
java-priority-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
Internal Working of HashMap in Java
Python | Count of common elements in the lists - GeeksforGeeks

09 Sep, 2019
Sometimes, while working with Python list we can have a problem in which we have to compare two lists for index similarity and hence can have a task of counting equal index pairs. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + zip()This task can be performed by passing the zip(), which performs task of mapping both list with each other, to the sum() which computes the sum according to equal indices.
# Python3 code to demonstrate working of# Identical element summation in lists# using sum() + zip()  # initialize liststest_list1 = [5, 6, 10, 4, 7, 1, 19]test_list2 = [6, 6, 10, 3, 7, 10, 19]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Identical element summation in lists# using sum() + zip()res = sum(x == y for x, y in zip(test_list1, test_list2))  # printing resultprint("Summation of Identical elements : " + str(res))
The original list 1 is : [5, 6, 10, 4, 7, 1, 19]
The original list 2 is : [6, 6, 10, 3, 7, 10, 19]
Summation of Identical elements : 4

 
Method #2 : Using sum() + map() + eqThe task performed in above method using zip() can be executed here using the map function which performs similar task. The equality check can be performed by inbuilt eq operator.
# Python3 code to demonstrate working of# Identical element summation in lists# using sum() + map() + eqfrom operator import eq  # initialize liststest_list1 = [5, 6, 10, 4, 7, 1, 19]test_list2 = [6, 6, 10, 3, 7, 10, 19]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Identical element summation in lists# using sum() + map() + eqres = sum(map(eq, test_list1, test_list2))  # printing resultprint("Summation of Identical elements : " + str(res))
The original list 1 is : [5, 6, 10, 4, 7, 1, 19]
The original list 2 is : [6, 6, 10, 3, 7, 10, 19]
Summation of Identical elements : 4

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Create Dropdown menu with Bootstrap

To create the Dropdown menu with Bootstrap, use the .dropdown-menu class.
You can try to run the following code to implement drop-down menu:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "dropdown">
         <button type = "button" class = "btn dropdown-toggle" id = "dropdownMenu1" data-toggle = "dropdown">
            Department
            <span class = "caret"></span>
         </button>
         <ul class = "dropdown-menu pull-right" role = "menu" aria-labelledby = "dropdownMenu1">
            <li role = "presentation">
               <a role = "menuitem" tabindex = "-1" href = "#">IT</a>
            </li>
            <li role = "presentation">
               <a role = "menuitem" tabindex = "-1" href = "#">Marketing</a>
            </li>
            <li role = "presentation">
               <a role = "menuitem" tabindex = "-1" href = "#">
                  Finance
               </a>
            </li>
            <li role = "presentation">
               <a role = "menuitem" tabindex = "-1" href = "#">Separated link</a>
            </li>
         </ul>
      </div>
   </body>
</html>
Character class: subtraction - Java regular expressions

You can subtract one range from other and use it as new range. You can achieve this by using two variants of character classes i.e. negation and intersection.
For example the intersection of ranges [a-l] and [^e-h] gives you the characters a to l as rage subtracting the characters [e-h]
 Live Demo
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[a-l&&[^e-h]]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
         System.out.print(matcher.group()+" ");
      }
      System.out.println("Number of matched characters: "+count);
   }
}
Enter input text:
abcdefghijklmnopq
a b c d i j k l Number of matched characters: 8
Combine two images in MATLAB

22 Sep, 2021
In this article, we will learn how to combine two images of the same size in MATLAB.
Now, let’s suppose we have been given two colored images of different sizes. One image has the main figure on the left side and the other has one on the right side. We need to combine the two images such that both figures appear on them. 
We need to combine them.
Step 1: Make left half of right_side_image 0 intensity image(black). Also, make right half of left_side_image 0 intensity region.
Syntax:
image_var = imread(” image path here “);
var_name = rgb2gray (image_var);
size( image_var )
imshow( var_name , [ ]);
or 
imtool( var_name, [ ]);
Access half columns :
image_var( :, 1:150); 
Example I:
Matlab
% MATLAB code for read the left % and right side of images.left=imread("logo_left.png");right=imread("logo_right.png");  % Convert them into grayscale images.left=rgb2gray(left);right=rgb2gray(right);  % Display the gray scaled images.imtool(left, []);imtool(right, []);  % Display the size of both images, then choose resize.size(left) % size of left is= 160   300     3size(right) % size of right is= 160   300     3  % Make other half as 0 intensity region.left(:, 150:300)=0;right(:, 1:150)=0;  % Display both images.imtool(left, []);imtool(right, []);
Output: 
In the above program first, we read the left and right images.
Converted the colored images into grayscale images.
Displayed the images.
Displayed the sizes of both images.
Converted other half intensity as 0. made half part dark.
Displayed modified images.
Step 2: Combine the left and right parts.
Syntax:
new_image = image_1 + image_2
// condition: both images must be of same size and type.
Example II:
Matlab
% MATLAB code for image combine % read the left and right sided images.left=imread("logo_left.png");right=imread("logo_right.png");  % Convert them into grayscale images.left=rgb2gray(left);right=rgb2gray(right);  % Display the gray scaled images.imtool(left, []);imtool(right, []);  % Display the size of both images, then choose resize.size(left) % size of left is= 160   300     3size(right) % size of right is= 160   300     3  % Make other half as 0 intensity region.left(:, 150:300)=0;right(:, 1:150)=0;  % Display both images.imtool(left, []);imtool(right, []);  % Combine left and right images and display.combined=uint8(left+right);imtool(combined,[]);
Output: 
The output image is the combination of two images.
MATLAB image-processing
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Crack PDF Files in Python?

26 Dec, 2020
Prerequisite: tqdm
In this article, we will learn How to Crack a Protected PDF File Using Python. Here we will use the Brute force Method, to Crack a PDF File using pikepdf module in Python.
Required Modules :
pikepdf is a Python module, which is used to create, manipulate, and repair PDF Files.
pip install pikepdf
tqdm is one of the more comprehensive packages for progress bars with python and is handy for those instances you want to build scripts that keep the users informed on the status of your application.
pip install tqdm
We won’t be using pikepdf for that though, we just gonna need to open the password-protected PDF file, if it succeeds, that means it’s a correct password, and it’ll raise a PasswordError exception otherwise.
Understand step by step Implementation:
Here we will use a text file that contains a password list, get it here.
We will iterate through all password lists and try to open the file with each password, bypassing the password argument to open() method, if the password will not match it will raise PasswordError. 
The last step is progress, like how many words are remaining, for showing the progress we will use tqdm module.
Below is the full implementation:
Python3
# Import Required Moduleimport pikepdffrom tqdm import tqdm  # Empty password listpasswords = []  # Contain passwords in text filepassword_text_file = "Password Text File"  # Iterate through each line# and store in passwords listfor line in open(password_text_file):    passwords.append(line.strip())      # iterate over passwordsfor password in tqdm(passwords, "Cracking PDF File"):    try:                # open PDF file and check each password        with pikepdf.open("Protected PDF File",                          password = password) as p:                        # If password is correct, break the loop            print("[+] Password found:", password)            break                  # If password will not match, it will raise PasswordError    except pikepdf._qpdf.PasswordError as e:                # if password is wrong, continue the loop        continue
Output:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Element Occurrence in dictionary of list values

29 Mar, 2019
Sometimes we can have a task in which we are required to count the occurrences of test elements in list or winning numbers, against the numbers with the associated keys with list as values. This can have applications in gaming or other utilities. Let’s discuss certain ways in which this can be done.
Method #1 : Using dictionary comprehension + sum()This task can be performed using the combination of above two utilities in which we use dictionary comprehension to bind the logic and sum function can be used to perform the summation of the matches found from test list.
# Python3 code to demonstrate# Element Occurrence in dictionary value list# using list comprehension + sum()  # initializing dictionarytest_dict = { "Akshat" : [1, 4, 5, 3],              "Nikhil" : [4, 6],              "Akash" : [5, 2, 1] }  # initializing test list test_list = [2, 1]  # printing original dictprint("The original dictionary : " + str(test_dict))  # printing original list print("The original list : " + str(test_list))  # using list comprehension + sum()# Element Occurrence in dictionary value listres = {idx : sum(1 for i in j if i in test_list)                for idx, j in test_dict.items()}  # print resultprint("The summation of element occurrence : " + str(res))
The original dictionary : {'Nikhil': [4, 6], 'Akshat': [1, 4, 5, 3], 'Akash': [5, 2, 1]}
The original list : [2, 1]
The summation of element occurrence : {'Nikhil': 0, 'Akshat': 1, 'Akash': 2}

 
Method #2 : Using collections.Counter()Python offers an inbuilt function that performs the task of extracting the frequency and using this and conditioning to presence in test list, we can solve the above problem using this function.
# Python3 code to demonstrate# Element Occurrence in dictionary value list# using collections.Counter()from collections import Counter  # initializing dictionarytest_dict = { "Akshat" : [1, 4, 5, 3],              "Nikhil" : [4, 6],              "Akash" : [5, 2, 1] }  # initializing test list test_list = [2, 1]  # printing original dictprint("The original dictionary : " + str(test_dict))  # printing original list print("The original list : " + str(test_list))  # using collections.Counter()# Element Occurrence in dictionary value list# omits the 0 occurrence word keyres = dict(Counter(j for j in test_dict           for i in test_list if i in test_dict[j]))  # print resultprint("The summation of element occurrence : " + str(res))
The original dictionary : {'Nikhil': [4, 6], 'Akshat': [1, 4, 5, 3], 'Akash': [5, 2, 1]}
The original list : [2, 1]
The summation of element occurrence : {'Akshat': 1, 'Akash': 2}

Python dictionary-programs
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set top-right corner border with CSS

Use the border-top-right radius property in CSS to set the top right radius border. You can try to run the following code to implement border-top-right-radius property −
Live Demo
<html>
   <head>
      <style>
         #rcorner {
            border-radius: 25px;
            border-top-right-radius: 45px;
            background: orange;
            padding: 20px;
            width: 400px;
            height: 250px;
         }
      </style>
   </head>
   <body>
      <p id = "rcorner">Rounded border-top-right corner!</p>
   </body>
</html>
Construct a Turing Machine for language L = {02n1n | n>=0} - GeeksforGeeks

14 Jun, 2020
Prerequisite – Turing Machine
The language L = {02n1n | n >= 0} represents a kind of language where we use only 2 symbols, i.e., 0 and 1. In the beginning language has some number of 0’s followed by exactly half number of 1’s . Any such string which falls in this category will be accepted by this language.
Examples :
Input : 001
Output : YES

Input : 00001
Output : NO 

Input :  or empty string
Output : YES 
Basic Representation –
Start of Computation :The tape contains the input string w, the tape head is on the leftmost symbol of w, and the Turing machine is in the start state Q0.
Basic Idea :The tape head reads the leftmost symbol of w, which is 0 and makes is blank then the next left most 0 is made blank after this we traverse to the rightmost 1 of the string and make it blank. In nth is way we have reduced the string to 02n-21n-1.If the string belongs to language L then at end empty string will be left and hence gets accepted by the machine.
Meanings of symbols used:R, L – direction of movement of one unit on either side.B-Blank.0, 1 – symbols whose combination string is to be tested.
Working Procedure :
Step-1:As we know the string will have twice number of zeros in the starting than the number of ones. So, we will first make the first two zeros Blank and go from state Q0 to Q1 and from state Q1 to Q2.
Step-2:After making them Blank we will traverse to the end of the string till we get the rightmost 1 in state Q3 and make it Blank reaching state Q4.
Step-3:Now we will traverse back till we get the left most zero in the string and return to the state Q0 from Q4.
Step-4:We are just reducing the string by making left most two zeros Blank and rightmost 1 Blank and if the string belongs to the language then it will be left empty and hence get accepted at state Q5 which is Final state. If the string is empty it will also get accepted at Q5.
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arden's Theorem in Theory of Computation
Pushdown Automata Acceptance by Final State
Boyer-Moore Majority Voting Algorithm
Construct a Turing Machine for language L = {ww | w ∈ {0,1}}
CYK Algorithm for Context Free Grammar
Context-sensitive Grammar (CSG) and Language (CSL)
Halting Problem in Theory of Computation
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Decidable and Undecidable problems in Theory of Computation
Introduction To Grammar in Theory of Computation
Optional toString() method in Java with examples

30 Jul, 2019
The toString() method of java.util.Optional class in Java is used to get the string representation of this Optional instance.
Syntax:
public String toString()

Parameters: This method accepts nothing.
Return value: This method returns the string representation of this Optional instance.
Below programs illustrate toString() method:Program 1:
// Java program to demonstrate// Optional.toString() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(452146);          // get value using toString        String value = op.toString();          // print value        System.out.println("String Representation: "                           + value);    }}
String Representation: Optional[452146]

Program 2:
// Java program to demonstrate// Optional.toString() method  import java.util.Optional;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.empty();          // get value using toString        String value = op.toString();          // print value        System.out.println("String Representation: "                           + value);    }}
String Representation: Optional.empty

References: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#toString–
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Write a C program that does not terminate when Ctrl+C is pressed

In this section we will see how to write a program in C that cannot be terminated by the Ctrl + C key.
The Ctrl + C generates the keyboard interrupt, and it stops the execution of the current process. Here when we will press the Ctrl + C key, it will print a message then continues the execution. To use this functionality, we will use the signal handling technique in C. When the Ctrl + C is pressed it generates SIGINT signal. There are some other signals and their functionalities in the following list.
Here we will use the standard C library function signal() to handle these signals.
#include <stdio.h>
#include <signal.h>
void sigint_handler(int signum) { //Handler for SIGINT
   //Reset handler to catch SIGINT next time.
   signal(SIGINT, sigint_handler);
   printf("Cannot be stopped using Ctrl+C \n");
   fflush(stdout);
}
main () {
   signal(SIGINT, sigint_handler);
   while(1) { //create infinite loop
   }
}
Cannot be stopped using Ctrl+C
Cannot be stopped using Ctrl+C
Raise a File Download Dialog Box in Python

07 Oct, 2021
Raising a File Download Dialog Box for end-user to download files like pdf, media-objects, documents, etc in Python can be done by the use of HTTP Header. It comes in handy where there is a need to develop a feature where instead of showing the files in the browser, the file contains is automatically downloaded.For instance, if you need a file say (GeeksForGeeks.txt) to be downloaded on click of a link from the database the code would somewhat look like below:  
Python3
# python_script.py # HTTP Headerprint ("Content-Type:application/octet-stream; name = \"FileName\"\r\n")print ("Content-Disposition: attachment; filename = \"FileName\"\r\n\n") # Original Filemy_file = open("GeeksForGeeks.txt", "rb") # read the file contenttext = my_file.read(); print (text) # Close opened filemy_file.close()
If you just run the script it will just read the original file as below:  
Note: One needs to make sure the file to be downloaded is in the same directory as the Python script.Using the script in your application: The below code is a simple example of the use of the above script in an application:  
html
<html><body><form enctype = "multipart/form-data" action = "python_script.py" method = "get"> <p>File link:<a href="GeeksForGeeks.txt" download>Click Here</a></p> </form></body></html>                   
Output:  
On click of the “Click Here” link the download box would pop up and start downloading the file. 
ruhelaa48
Python-CGI
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.