code-rag-bench/online-tutorials huggingface dataset:
Final arrays in Java - GeeksforGeeks

31 Oct, 2020
Predict the output of following Java program.
class Test {    public static void main(String args[])    {       final int arr[] = {1, 2, 3, 4, 5};  // Note: arr is final       for (int i = 0; i < arr.length; i++)       {           arr[i] = arr[i]*10;             System.out.println(arr[i]);                 }          }    }
Output:
10 
20 
30 
40 
50 
The array arr is declared as final, but the elements of array are changed without any problem. Arrays are objects and object variables are always references in Java. So, when we declare an object variable as final, it means that the variable cannot be changed to refer to anything else. For example, the following program 1 compiles without any error and program 2 fails in compilation.
// Program 1class Test {    int p = 20;    public static void main(String args[])    {       final Test t = new Test();              t.p = 30;       System.out.println(t.p);       }    }
Output: 30
// Program 2class Test {    int p = 20;    public static void main(String args[])    {       final Test t1 = new Test();              Test t2 = new Test();       t1 = t2;        System.out.println(t1.p);          }    }
Output: Compiler Error: cannot assign a value to final variable t1
So a final array means that the array variable which is actually a reference to an object, cannot be changed to refer to anything else, but the members of array can be modified.
As an exercise, predict the output of following program
class Test {    public static void main(String args[])    {       final int arr1[] = {1, 2, 3, 4, 5};       int arr2[] = {10, 20, 30, 40, 50};       arr2 = arr1;             arr1 = arr2;         for (int i = 0; i < arr2.length; i++)          System.out.println(arr2[i]);              }    }
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ashwin1
Java-Array-Programs
Java-Arrays
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
How to handle the StringIndexOutOfBoundsException (unchecked) in Java?

The StringIndexOutOfBoundsException is one of the unchecked exceptions in Java. A string is kind of an ensemble of characters. String object has a range of [0, length of the string]. When someone tries to access the characters with limits exceeding the range of actual string value, this exception occurs.
Live Demo
public class StringDemo {
   public static void main(String[] args) {
      String str = "Welcome to Tutorials Point.";
      System.out.println("Length of the String is: " + str.length());
      System.out.println("Length of the substring is: " + str.substring(28));
   }
}
Length of the String is: 27
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
       at java.lang.String.substring(String.java:1931)
       at StringDemo.main(StringDemo.java:6)
We can check the range of the string using String.length() method and proceed to access the characters of it accordingly.
We can use try and catch block around the code snippet that can possibly throw StringIndexOutOfBoundsException.
Live Demo
public class StringIndexOutOfBoundsExceptionTest {
   public static void main(String[] args) {
      String str = "Welcome to Tutorials Point.";
      try {
        // StringIndexOutOfBoundsException will be thrown because str only has a length of 27.
str.charAt(28);
         System.out.println("String Index is valid");
      } catch (StringIndexOutOfBoundsException e) {
         System.out.println("String Index is out of bounds");
      }
   }
}
String Index is out of bounds
How can I programmatically select a specific subplot in Matplotlib?

To select a specific subplot in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Iterate in a range, i.e., number subplots to be placed.
Iterate in a range, i.e., number subplots to be placed.
In the loop itself, add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
In the loop itself, add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot() method.
Now, select an axes plot line with red color.
Now, select an axes plot line with red color.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

fig = plt.figure()

for index in [1, 2, 3, 4]:
   ax = fig.add_subplot(1, 4, index)
   ax.plot(np.random.rand(5), np.random.rand(5))

ax = fig.add_subplot(1, 4, 2)
ax.plot(np.random.rand(5), np.random.rand(5), color='red')

plt.show()
Find the 3rd largest number in a Java array.

Following is the required program.
Live Demo
public class Tester {
   public static int getThirdLargest(int[] a) {
      int temp;
      //sort the array
      for (int i = 0; i < a.length; i++) {
         for (int j = i + 1; j < a.length; j++) {
            if (a[i] > a[j]) {
               temp = a[i];
               a[i] = a[j];
               a[j] = temp;
            }
         }
      }
      //return third largest element
      return a[a.length - 3];
   }
   public static void main(String args[]) {
      int a[] = { 11,10,4, 15, 16, 13, 2 };
      System.out.println("Third Largest: " +getThirdLargest(a));
   }
}
Third largest: 13
HTML - Background Images

The background attribute can also be used to control the background of an HTML elmement, specifically page body and table backgrounds. You can specify an image to set background of your HMTL page or table. Following is the syntax to use background attribute with any HTML tag.
The background is deprecated and it is recommended to use Style Sheet for background setting.
<tagname background="Image URL"...>
Here are the examples to set background  images of a  table.
<!-- How to set a table background -->
<table background="/images/html.gif" width="100%"  height="100">
<tr><td>
This background is filled up with HTML image.
</td></tr>
</table>
 
<table background="/images/home.gif" width="100%"  height="100">
<tr><td>
This background is filled up with home image.
</td></tr>
</table>
This will produce following result:
Note that when your HTML element is larger than the dimensions of your picture, the image simply begins to repeat itself.

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to create a JSON Object using Object Model in Java?

The javax.json.JsonObject interface can represent an immutable JSON object value and provides an unmodifiable map view to the JSON object name/value mappings. A JsonObject instance can be created from an input source using the static method readObject() of javax.json.JsonReader class and also can be created using the static method createObjectBuilder() of javax.json.Json class.
public static JsonObjectBuilder createObjectBuilder()
import java.io.*;
import javax.json.*;
public class JsonObjectTest {
   public static void main(String[] args) throws Exception {
      JsonObjectBuilder builder = Json.createObjectBuilder();
      builder.add("Name", "Adithya");
      builder.add("Designation", "Python Developer");
      builder.add("Company", "TutorialsPoint");
      builder.add("Location", "Hyderabad");
      JsonObject data = builder.build();
      StringWriter sw = new StringWriter();
      JsonWriter jw = Json.createWriter(sw);
      jw.writeObject(data);
      jw.close();
      System.out.println(sw.toString());
   }
}
{"Name":"Adithya","Designation":"Python Developer","Company":"TutorialsPoint","Location":"Hyderabad"}
Getopt module in Python - GeeksforGeeks

04 May, 2020
The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is in general used for parsing an argument sequence such as sys.argv. In other words, this module helps scripts to parse command-line arguments in sys.argv. It works similar to the C getopt() function for parsing command-line parameters.
The first function provided by this module is of the same name i.e. getopt(). Its primary functionality is to parse command-line options and parameter list. The syntax of the function is as below:
Syntax: getopt.getopt(args, options, [long_options])
Parameters:args: List of arguments to be passed.options: String of option letters that the script wants to recognize. Options that require an argument should be followed by a colon (:).long_options: List of the string with the name of long options. Options that require arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped.
Example 1:
import sysimport getopt    def full_name():    first_name = None    last_name = None      argv = sys.argv[1:]      try:        opts, args = getopt.getopt(argv, "f:l:")          except:        print("Error")      for opt, arg in opts:        if opt in ['-f']:            first_name = arg        elif opt in ['-l']:            last_name = arg            print( first_name +" " + last_name)  full_name()    
Output:
Here we have created a function full_name(), which prints the full name after getting first name and last name from the command line. We have also abbreviated first name as ‘f’ and last name as ‘l’.
Example 2: Now lets look into the case where instead of short-form like ‘f’ or ‘l’, we could use full forms as ‘first_name’ and ‘last_name’.The below code uses full forms to print full name;
import sysimport getopt  def full_name():    first_name = None    last_name = None      argv = sys.argv[1:]      try:        opts, args = getopt.getopt(argv, "f:l:",                                    ["first_name =",                                    "last_name ="])          except:        print("Error")      for opt, arg in opts:        if opt in ['-f', '--first_name']:            first_name = arg        elif opt in ['-l', '--last_name']:            last_name = arg            print( first_name +" " + last_name)  full_name()
Output:
Note: The single dash(‘-‘) for short forms and double dash(‘–‘) for long form of the argument in the code should be used.
python-modules
Python
Write From Home
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
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Stack toString() method in Java with Example

24 Dec, 2018
The toString() method of Java Stack is used to return a string representation of the elements of the Collection.
The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than String type(for instance: Object, Integer)in a String Representation.
Syntax:
public String toString()
Parameter The method does not take any parameters.
Return This method returns a String representation of the collection.
Below examples illustrate the toString() method:
Example 1:
// Java program to demonstrate// Stack toString() method  import java.util.*;  public class collection {    public static void main(String args[])    {        // Creating an Empty Stack        Stack<String> stack            = new Stack<String>();          // Use add() method        // to add elements to the Collection        stack.add("Welcome");        stack.add("To");        stack.add("Geeks");        stack.add("For");        stack.add("Geeks");          // Using toString() method        System.out.println(stack.toString());    }}
[Welcome, To, Geeks, For, Geeks]

Example 2:
// Java program to demonstrate// Stack toString() method  import java.util.*;  public class collection {    public static void main(String args[])    {        // Creating an Empty Stack        Stack<Integer> stack            = new Stack<Integer>();          // Use add() method        // to add elements to the Collection        stack.add(10);        stack.add(20);        stack.add(30);        stack.add(40);          // Using toString() method        System.out.println(stack.toString());    }}
[10, 20, 30, 40]

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – NOT LIKE operator

28 Aug, 2020
The PostgreSQL NOT LIKE works exactly opposite to that of the LIKE operator. It is used to data using pattern matching techniques that explicitly excludes the mentioned pattern from the query result set.Its result include strings that are case-sensitive and doesn’t follow the mentioned pattern.It is important to know that PostgreSQL provides with 2 special wildcard characters for the purpose of patterns matching as below:
Percent ( % ) for matching any sequence of characters.
Underscore ( _ ) for matching any single character.
Syntax: string NOT LIKE pattern;
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.
Now, let’s look into a few examples.
Example 1:Here we will make a query to find the customer in the “customer” table by looking at the “first_name” column to see if there is any value that doesn’t begin with “K” using the NOT LIKE operator in our sample database.
SELECT
    first_name,
        last_name
FROM
    customer
WHERE
    first_name NOT LIKE 'K%';
Output:
Example 2:Here we will query for customers whose first name doesn’t begin with any single character, is not followed by the literal string “her” respectively using the NOT LIKE operator in our sample database.
SELECT
    first_name,
    last_name
FROM
    customer
WHERE
    first_name NOT LIKE '_her%';
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList removeLast() Method in Java

29 Nov, 2020
The Java.util.LinkedList.removeLast() method is used to remove the last element from the LinkedList. This method also returns the element after removing it.Syntax:  
LinkedList.removeLast()
Parameters: This function does not take any parameters.Return Value: The method returns the last element or the element present at the tail of the list.Below program illustrate the Java.util.LinkedList.removeLast() method:  
Java
// Java code to illustrate removeLast()import java.io.*;import java.util.LinkedList; public class LinkedListDemo {    public static void main(String args[])    {        // Creating an empty LinkedList        LinkedList<String> list = new LinkedList<String>();         // Use add() method to add elements in the list        list.add("Geeks");        list.add("for");        list.add("Geeks");        list.add("10");        list.add("20");         // Displaying the list        System.out.println("LinkedList:" + list);         // Remove the tail using removeLast()        System.out.println("The last element is removed: " + list.removeLast());                 // Displaying the final list        System.out.println("Final LinkedList:" + list);                 // Remove the tail using removeLast()        System.out.println("The last element is removed: " + list.removeLast());         // Displaying the final list        System.out.println("Final LinkedList:" + list);    }}
LinkedList:[Geeks, for, Geeks, 10, 20]
The last element is removed: 20
Final LinkedList:[Geeks, for, Geeks, 10]
The last element is removed: 10
Final LinkedList:[Geeks, for, Geeks]
 
Time complexity of removeLast() : O(1) 
moonlight23
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Tabs in ReactJS ?

12 Feb, 2021
Tabs make it easy to explore and switch between different views. Material UI for React has this component available for us and it is very easy to integrate. We can use Tabs Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from "react";import Paper from "@material-ui/core/Paper";import Tab from "@material-ui/core/Tab";import Tabs from "@material-ui/core/Tabs";  const App = () => {  const [value, setValue] = React.useState(2);    return (    <div      style={{        marginLeft: "40%",      }}    >      <h2>How to Create Tabs in ReactJS?</h2>      <Paper square>        <Tabs          value={value}          textColor="primary"          indicatorColor="primary"          onChange={(event, newValue) => {            setValue(newValue);          }}        >          <Tab label="Active TAB One" />          <Tab label="Active TAB Two" />          <Tab label="Disabled TAB!" disabled />          <Tab label="Active Tab Three" />        </Tabs>        <h3>TAB NO: {value} clicked!</h3>      </Paper>    </div>  );};  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
React-Questions
JavaScript
ReactJS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to calculate acceleration, final velocity, initial velocity and time

31 Aug, 2021
Here we can find the acceleration (a), final velocity(v), initial velocity(u) and time(t) using the formula a = (v-u)/t.
At first, functions are defined for all four types of calculations, in which they will accept three inputs and assign the value in three different variables. Then the fourth value is calculated using the acceleration formula and the calculated value is returned. We are going to use the same acceleration formula in different approaches.
Approach: 
In the first approach, we will find initial velocity by using the formula “u = (v-a*t)”
In the second approach, we will find final velocity by using formula “v =  u + a*t”
In the third approach, we will find acceleration by using formula “a = (v – u)/t”
In the fourth approach, we will find time by using formula “t = (v – v)/a”
Example 1: Initial velocity (u) is calculated.
Python3
# code# Enter final velocity in m/s:finalVelocity = 10 # Enter acceleration in m per second squareacceleration = 9.8 #Enter time taken in secondtime = 1initialVelocity = finalVelocity - acceleration * timeprint("Initial velocity = ", initialVelocity)
Output:
Initial velocity =  0.1999999999999993
 
Example 2: Final velocity (v) is calculated.
Python3
# code# initial velocity in m/s:initialVelocity = 10 # acceleration in m per second squareacceleration = 9.8 # time taken in secondtime = 1finalVelocity = initialVelocity + acceleration * timeprint("Final velocity = ", finalVelocity)
Output:
Final velocity =  19.8
Example 3: Acceleration (a) is calculated.
Python3
#code# initial velocity in m/sinitialVelocity = 0 # final velocity in m/sfinalVelocity = 9.8 # time in secondtime = 1 acceleration = (finalVelocity - initialVelocity) / timeprint("Acceleration = ", acceleration)
Output:
Acceleration =  9.8
Example 4: Time (t) is calculated.
Python3
# code#final velocity in m/sfinalVelocity = 10 #initial velocity in m/sinitialVelocity = 0 #acceleration in meter per second squareacceleration = 9.8 time = (finalVelocity - initialVelocity) / accelerationprint("Time taken = ", time)
Output:
Time taken =  1.0204081632653061
anikaseth98
school-programming
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Where and Having Clause in SQL

18 May, 2022
1. WHERE Clause: WHERE Clause is used to filter the records from the table or used while joining more than one table.Only those records will be extracted who are satisfying the specified condition in WHERE clause. It can be used with SELECT, UPDATE, DELETE statements. 
Let us consider below table “Student” 
Roll_no       S_Name      Age

1                a             17

2                b             20

3                c             21

4                d             18

5                e             20

6                f             17

7                g             21

8                h             17 
Consider the Query: 
SELECT S_Name, Age FROM Student 
WHERE Age >=18
OUTPUT of above query is : 
 S_Name      Age

b             20             

c             21             

d             18             

e             20             

g             21             
2. HAVING Clause: HAVING Clause is used to filter the records from the groups based on the given condition in the HAVING Clause. Those groups who will satisfy the given condition will appear in the final result. HAVING Clause can only be used with SELECT statement. 
Let us consider Student table mentioned above and apply having clause on it: 
SELECT Age, COUNT(Roll_No) AS No_of_Students 
FROM Student GROUP BY Age
HAVING COUNT(Roll_No) > 1 
OUTPUT of the above query is : 
Age     No_of_Students

17              3

20              2

21              2 
Difference between Where and Having Clause in SQL : 
ragunpkm2001
aman1jha2017
Picked
SQL-Clauses
DBMS
Difference Between
GATE CS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Const vs Regular iterators in C++ with examples

18 Aug, 2020
Prerequisite: Iterators in STL
Iterators are objects similar to pointers which are used to iterate over a sequence and manipulate the container elements. The advantage of using an iterator is that it reduces the lines of code to a single statement as they allow us to manipulate the built-in arrays in the STL using pointers as iterators. An iterator can either be a constant or a non-constant/regular iterator.
A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can’t be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed). It can be used for access only, and can’t be used for modification. If we try to modify the value of the element using const iterator then it generates an error.
A regular or non const_iterator points to an element inside the container and can be used to modify the element to which it is pointing. Regular Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of a regular iterator is a pointer.A pointer can point to elements in an array and can iterate through them using the increment operator(++). Each container type has a specific regular iterator type designed to iterate through its elements.
Below is a C++ program to demonstrate the difference in the working of the two iterators:
C++
// C++ program to demonstrate a regular// and const_iterator#include <iostream>#include <iterator>#include <vector>using namespace std;  // Function that demonstrate regular// iteratorsvoid regularIterator(vector<int>& v){    // Declare a regular iterator    // to a vector    vector<int>::iterator i;      // Printing the elements of the    // vector v using regular iterator    for (i = v.begin(); i < v.end(); i++) {          // Update elements of vector        *i += 1;        cout << *i << " ";    }}  // Function that demonstrate const// iteratorsvoid constIterator(vector<int>& v1){    // Declare a const_itearor    // to a vector    vector<int>::const_iterator ci;      // Printing the elements of the    // vector v1 using regular iterator    for (ci = v1.begin(); ci < v1.end(); ci++) {          // Below line will throw an error        // as we are trying to modify the        // element to which const_iterator        // is pointing          //*ci += 1;          cout << *ci << " ";    }}  // Driver Codeint main(){    // Declaring vectors    vector<int> v = { 7, 2, 4 };    vector<int> v1 = { 5, 7, 0 };      // Demonstrate Regular iterator    regularIterator(v);      cout << endl;      // Demonstrate Const iterator    constIterator(v1);    return 0;}
8 3 5
5 7 0

C++-const keyword
cpp-iterator
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert number to month name in PHP?

30 Apr, 2019
The month number can be converted into a month name by using PHP functions. There are two functions to convert the given month number into month name.
Method 1: Using mktime() function: The mktime() function is an inbuilt function in PHP which is used to return the Unix timestamp for a date. The timestamp returns a long integer containing the number of seconds between the Unix Epoch (January 1, 1970, 00:00:00 GMT) and the time specified. The hour, minute, second, month, day and year are sent as parameters to the mktime() function and it returns an integer Unix timestamp on success and False on error.
Syntax:
int mktime( $hour, $minute, $second, $month, $day, $year, $is_dst)
Example:
<?php// PHP program to convert number to month name  // Declare month number and initialize it$month_num =12;  // Use mktime() and date() function to// convert number to month name$month_name = date("F", mktime(0, 0, 0, $month_num, 10));  // Display month nameecho $month_name."\n";  ?>
December

Method 2: Using DateTime::createFromFormat() function: The DateTime::createFromFormat() function is an inbuilt function in php which is used to parses a time string according to a specified format. This function accepts three parameters and returns new DateTime in success or false on failure.
Syntax:
DateTime::createFromFormat( $format, $time, $timezone )
Example:
<?php// PHP program to convert number to month name  // Declare month number and initialize it$monthNum = 4;  // Create date object to store the DateTime format$dateObj = DateTime::createFromFormat('!m', $monthNum);  // Store the month name to variable$monthName = $dateObj->format('F');  // Display outputecho $monthName."\n";   ?>
April

Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
GOCC18: Google’s Online Coding Challenge

16 Aug, 2021
The GOCC18 was held on September 26, 2020, for Google SWE New Grad 2021 (India). There were 2 coding questions to attempt, with a 60-minute time limit for completion. Below is the first question of the challenge:
Question1: The cost of a string
Your task is to create a string S considering lowercase English alphabets. You are given an array A of size 26 where A[i] denotes the cost of using the ith Alphabet (consider 1-based indexing). Find lexicographically the largest string S that can be created such that the cost of building the string is exactly W. For example, ‘abc’ is lexicographically smaller than ‘abcd’.
Input format:
The first line contains an integer T denoting the number of test cases.
The first line of each test case contains 26 space-separated integers denoting the costs of characters from ‘a’ to ‘z’.
The second line of each test case contains an integer W.
Output format: For each test case, print the required string S in a new line.
Sample input
1
1 1 2 33 4 6 9 7 36 12 58 32 28 994 22 255 47 69 558 544 21 36 48 85 48 58
236
Sample output
zzzze
Google
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to perform mouse movement to an element in Selenium with python?

We can perform mouse movement to an element in Selenium with the
help of Action Chains class. These classes are generally used for automating
interactions like context menu click, mouse button actions, key press and mouse
movements.
These types of actions are mainly common in complex scenarios like drag and drop
and hovering over an element on the page. The methods of the Action Chains class
are utilized by advanced scripts. We can manipulate DOM with the help of Action
Chains in Selenium.
The action chain object implements the ActionChains in the form of a queue and
then executes the perform() method. On calling the method perform(), all the
actions on action chains will be performed.
The method of creating an Action Chain object is listed below −
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
First we need to import the Action Chain class and then the driver will be
passed as an argument to it.
Now all the operations of action chains can be done with the help of this
object.
Now all the operations of action chains can be done with the help of this
object.
Syntax for creating an object of Action Chains −
from selenium import webdriver
# import Action chains
from selenium.webdriver import ActionChains
# create webdriver object
driver = webdriver.Firefox()
# create action chain object
action = ActionChains(driver)
After creating an object of Action Chains, we can perform numerous operations
one by one like a chain which is queued.
move_to_element() - This method performs movement of mouse to the middle of
the element on the page.
move_to_element(args)
Where args is the element to move to.
#element
source = driver.find_element_by_id("name")
#action chain object
action = ActionChains(driver)
# move to element operation
action.move_to_element(source).click().perform()
Code Implementation for moving to an element.
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then
#invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#to refresh the browser
driver.refresh()
# identifying the source element
source= driver.find_element_by_xpath("//*[text()='Company']");
# action chain object creation
action = ActionChains(driver)
# move to the element and click then perform the operation
action.move_to_element(source).click().perform()
#to close the browser
driver.close()
GATE | GATE-CS-2001 | Question 48

28 Jun, 2021
R(A,B,C,D) is a relation. Which of the following does not have a lossless join, dependency preserving BCNF decomposition?(A) A->B, B->CD(B) A->B, B->C, C->D(C) AB->C, C->AD(D) A ->BCDAnswer: (C)Explanation: Background :
Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)    R1 ∩ R2 → R1
   OR
    R1 ∩ R2 → R2

Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)
    R1 ∩ R2 → R1
   OR
    R1 ∩ R2 → R2

dependency preserving :Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of of FDs before decomposition.A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition.
Question :We know that for lossless decomposition common attribute should be candidate key in one of the relation.
A) A->B, B->CD
R1(AB) and R2(BCD)
B is the key of second and hence decomposition is lossless.
B) A->B, B->C, C->D
R1(AB) , R2(BC), R3(CD)
B is the key of second and C is the key of third, hence lossless.
C) AB->C, C->AD
R1(ABC), R2(CD)
C is key of second, but C->A violates BCNF condition in ABC as C is not a key. We cannot decompose ABC further as AB->C dependency would be lost.
D) A ->BCD
Already in BCNF.
Therefore, Option C AB->C, C->AD is the answer.Quiz of this Question
GATE-CS-2001
GATE-GATE-CS-2001
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | bcdiv() Function

19 Apr, 2018
The bcdiv() function in PHP is an inbuilt function and is used to divide two arbitrary precision numbers. This function accepts two arbitrary precision numbers as strings and returns the division of the two numbers after scaling the result to a specified precision.
Syntax:
string bcdiv ( $num_str1, $num_str2, $scaleVal)
Parameters: This function accepts three parameters as shown in the above syntax and explained below:
$num_str1: This parameter is of string type and represents the dividend. This parameter is mandatory.
$num_str2: This parameter is of string type and represents the divisor. This parameter is mandatory.
$scaleVal: This parameter is of int type and is optional. This parameter tells the number of digits that will appear after the decimal in the result of division. It’s default value is zero.
Return Value: This function returns the division of the number $num_str1 by $num_str2 as string.
Examples:
Input:  $num_str1 = 11.222, $num_str2 = 3
Output: 3
Since the parameter $scaleVal is not specified so
no digits after decimal is appeared in the 
result after division.

Input:  $num_str1 = 11.222, $num_str2 = 3, $scaleVal = 4
Output: 3.7406

Below programs illustrate the bcdiv() function in PHP :
Program 1:
<?php// PHP program to illustrate bcdiv() function   // input numbers$num_str1 = "11.222";  // dividend$num_str2 = "3";  // divisor   // calculates the division of// the two numbers when $scaleVal is// not specified$res = bcdiv($num_str1, $num_str2);  echo $res;   ?>
Output:
3

Program 2:
<?php// PHP program to illustrate bcdiv() function   // input numbers$num_str1 = "11.222";  // dividend$num_str2 = "3";  // divisor  // scale value$scaleVal = 4;  // calculates the division of the two // numbers when $scaleVal is specified$res = bcdiv($num_str1, $num_str2, $scaleVal);  echo $res;   ?>
Output:
3.7406

Reference:http://php.net/manual/en/function.bcdiv.php
PHP-bc
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js zlib.gunzip() Method

12 Oct, 2021
The zlib.gunzip() method is an inbuilt application programming interface of the Zlib module which is used to decompress a chunk of data.
Syntax:
zlib.gunzip( buffer, options, callback )
Parameters: This method accepts three parameters as mentioned above and described below:
buffer: It can be of type Buffer, TypedArray, DataView, ArrayBuffer, and string.
options: It is an optional parameter that holds the zlib options.
callback: It holds the callback function.
Return Value: It returns the chunk of data after decompression.
Below examples illustrate the use of zlib.gunzip() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // gunzip() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "Geek";  // Calling gzip methodzlib.gzip(input, (err, buffer) => {    // Calling gunzip method zlib.gunzip(buffer, (err, buffer) => {      console.log(buffer.toString('utf8'));          }); });  console.log("Data Decompressed...");
Output:
Data Decompressed...
Geek

Example 2:
// Node.js program to demonstrate the     // gunzip() method  // Including zlib moduleconst zlib = require("zlib");  // Declaring input and assigning// it a value stringvar input = "Geek";  // Calling gzip methodzlib.gzip(input, (err, buffer) => {    // Calling gunzip method zlib.gunzip(buffer, (err, buffer) => {      console.log(buffer.toString('hex'));          }); });  console.log("Data Decompressed...");
Output:
Data Decompressed...
4765656b

Reference: https://nodejs.org/api/zlib.html#zlib_zlib_gunzip_buffer_options_callback
Node.js-Zlib-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Compare two Collections in Java?

02 Nov, 2020
Java Collection provides an architecture to store and manipulate the group of objects. Here we will see how to compare Elements in a Collection in Java.
Steps:
Take both inputs with help of asList() function.
Sort them using Collections.sort() method.
Compare them using equals() function.
Print output. (true means both are equal and false means both are different)
Example 1:
Java
// Java program implementing// Comparing elements of Collections  import java.util.*;import java.io.*;  public class ArrayCompareExample {      // main function accepting string arguments    public static void main(String[] args)    {        // create listA        ArrayList<String> listA            = new ArrayList<>(Arrays.asList("a", "b", "c"));          // create listB        ArrayList<String> listB            = new ArrayList<>(Arrays.asList("a", "b", "d"));          // sorting both lists        Collections.sort(listA);        Collections.sort(listB);          // Compare lists using        // equals() method        boolean isEqual = listA.equals(listB);          // print output on screen (true or false)        System.out.println(isEqual);    }}
false
Example 2:
Java
// Java program implementing// Comparing elements of Collections  import java.util.*;import java.io.*;  public class ArrayCompareExample {      // main function accepting string arguments    public static void main(String[] args)    {        // create listA        ArrayList<Integer> listA            = new ArrayList<>(Arrays.asList(3, 4, 5));          // create listB        ArrayList<Integer> listB            = new ArrayList<>(Arrays.asList(4, 5, 3));          // sorting both lists        Collections.sort(listA);        Collections.sort(listB);          // Compare lists using        // equals() method        boolean isEqual = listA.equals(listB);          // print output on screen (true or false)        System.out.println(isEqual);    }}
true
Java-Collections
Java
Java Programs
Java
Java-Collections
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
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
MySQL - MAX Function

MySQL MAX function is used to find out the record with maximum value among a record set.
To understand MAX function, consider an employee_tbl table, which is having the following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to  fetch maximum value of daily_typing_pages, then you can do so simply using the following command −
mysql> SELECT MAX(daily_typing_pages)
   -> FROM employee_tbl;
+-------------------------+
| MAX(daily_typing_pages) |
+-------------------------+
|           350           |
+-------------------------+
1 row in set (0.00 sec)
You can find all the records with maximum value for each name using GROUP BY clause as follows −
mysql> SELECT id, name, MAX(daily_typing_pages)
   -> FROM employee_tbl GROUP BY name;
+------+------+-------------------------+
|  id  | name | MAX(daily_typing_pages) |
+------+------+-------------------------+
|   3  | Jack |           170           |
|   4  | Jill |           220           |
|   1  | John |           250           |
|   2  | Ram  |           220           |
|   5  | Zara |           350           |
+------+------+-------------------------+
5 rows in set (0.00 sec)
You can use MIN Function along with MAX function to find out minimum value as well. Try out the following example −
mysql> SELECT MIN(daily_typing_pages) least, MAX(daily_typing_pages) max
   -> FROM employee_tbl;
+-------+------+
| least |  max |
+-------+------+
|  100  |  350 |
+-------+------+
1 row in set (0.01 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Get count of how many times a string appears in a MySQL column?

Let us first create a table −
mysql> create table DemoTable704 (SubjectName text);
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable704 values('Introduction to MySQL');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable704 values('Introduction to MongoDB');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable704 values('Introduction to MySQL');
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable704 values('Introduction to Java');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable704 values('Introduction to MongoDB');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable704 values('Introduction to MySQL');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable704 values('Introduction to C');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable704 values('Introduction to Spring and Hibernate');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable704;
This will produce the following output -
+--------------------------------------+
| SubjectName                          |
+--------------------------------------+
| Introduction to MySQL                |
| Introduction to MongoDB              |
| Introduction to MySQL                |
| Introduction to Java                 |
| Introduction to MongoDB              |
| Introduction to MySQL                |
| Introduction to C                    |
| Introduction to Spring and Hibernate |
+--------------------------------------+
8 rows in set (0.00 sec)
Following is the query to get count of how many times string appears in column −
mysql> SELECT COUNT(*) from DemoTable704 WHERE SubjectName LIKE '%Introduction to MySQL%';
This will produce the following output -
+----------+
| COUNT(*) |
+----------+
| 3        |
+----------+
1 row in set (0.00 sec)
How to Convert Pytorch tensor to Numpy array?

30 Jun, 2021
In this article, we are going to convert Pytorch tensor to NumPy array.
Method 1: Using numpy().
Syntax: tensor_name.numpy()
Example 1: Converting one-dimensional a tensor to NumPy array
Python3
# importing torch moduleimport torch  # import numpy moduleimport numpy  # create one dimensional tensor with# float type elementsb = torch.tensor([10.12, 20.56, 30.00, 40.3, 50.4])  print(b)  # convert this into numpy array using# numpy() methodb = b.numpy()  # displayb
Output:
tensor([10.1200, 20.5600, 30.0000, 40.3000, 50.4000])
array([10.12, 20.56, 30.  , 40.3 , 50.4 ], dtype=float32)
Example 2: Converting two-dimensional tensors to NumPy array
Python3
# importing torch moduleimport torch  # import numpy moduleimport numpy  # create two dimensional tensor with# integer type elementsb = torch.tensor([[1, 2, 3, 4, 5], [3, 4, 5, 6, 7],                   [4, 5, 6, 7, 8]])  print(b)  # convert this into numpy array using# numpy() methodb = b.numpy()  # displayb
Output:
tensor([[1, 2, 3, 4, 5],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])
array([[1, 2, 3, 4, 5],
      [3, 4, 5, 6, 7],
      [4, 5, 6, 7, 8]])
Method 2: Using numpy.array() method.
This is also used to convert a tensor into NumPy array.
Syntax: numpy.array(tensor_name)
Example: Converting two-dimensional tensor to NumPy array
Python3
# importing torch moduleimport torch  # import numpy moduleimport numpy  # create two dimensional tensor with # integer type elementsb = torch.tensor([[1, 2, 3, 4, 5], [3, 4, 5, 6, 7],                   [4, 5, 6, 7, 8]])  print(b)  # convert this into numpy array using # numpy.array() methodb = numpy.array(b)  # displayb
Output:
tensor([[1, 2, 3, 4, 5],
       [3, 4, 5, 6, 7],
       [4, 5, 6, 7, 8]])
array([[1, 2, 3, 4, 5],
      [3, 4, 5, 6, 7],
      [4, 5, 6, 7, 8]])
Picked
Python-numpy
Python-PyTorch
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function