code-rag-bench/online-tutorials huggingface dataset:
Python | Extract Nth words in Strings List

22 Apr, 2020
Sometimes, while working while working with Python Lists, we can have problem in which we need to perform the task of extracting Nth word of each string in List. This can have application in web-development domain. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + split()The combination of above methods can be used to solve this problem. In this, we perform the task of getting Nth word using split and recreate list using list comprehension.
# Python3 code to demonstrate working of # Extract Nth words in Strings List# Using list comprehension + split()      # initializing listtest_list = ['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']  # printing original listprint("The original list is : " + str(test_list))  # initializing N N = 2  # Extract Nth words in Strings List# Using list comprehension + split()res = [sub.split()[N - 1] for sub in test_list if len(sub.split()) > 1]  # printing result print("The Nth words in list are : " + str(res)) 
The original list is : ['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', 'is', 'CS']

 
Method #2 : Using list comprehension + enumerate() + split()The combination of above functions can be used to perform this task. In this, we use enumerate to check for the Nth word rather than split().
# Python3 code to demonstrate working of # Extract Nth words in Strings List# Using list comprehension + <code>enumerate() + split()      # initializing listtest_list = ['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']  # printing original listprint("The original list is : " + str(test_list))  # initializing N N = 2  # Extract Nth words in Strings List# Using list comprehension + <code>enumerate() + split()res = [ele for sub in test_list for idx, ele in enumerate(sub.split()) if idx == (N - 1)]  # printing result print("The Nth words in list are : " + str(res)) 
The original list is : ['Gfg best for', 'All geeks', 'It is for', 'all CS professionals']
The Nth words in list are : ['best', 'geeks', 'is', 'CS']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
GATE | GATE-CS-2003 | Question 85 - GeeksforGeeks

28 Jun, 2021
Consider the following functional dependencies in a database:
  Data_of_Birth → Age
  Age → Eligibility
  Name → Roll_number
  Roll_number → Name
  Course_number → Course_name
  Course_number → Instructor
  (Roll_number, Course_number) → Grade
The relation (Roll_number, Name, Date_of_birth, Age) is:(A) In second normal form but not in third normal form(B) In third normal form but not in BCNF(C) In BCNF(D) None of the aboveAnswer: (D)Explanation: The given table is not in 2NF as age is dependent on date of birth.Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
C++ Modifier Types

C++ allows the char, int,  and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations.
The data type modifiers are listed here −
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int. It automatically implies int. For example, the following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;

To understand the difference between the way signed and unsigned integer modifiers are interpreted by C++, you should run the following short program −
#include <iostream>
using namespace std;
 
/* This program shows the difference between
   * signed and unsigned integers.
*/
int main() {
   short int i;           // a signed short integer
   short unsigned int j;  // an unsigned short integer

   j = 50000;

   i = j;
   cout << i << " " << j;

   return 0;
}
When this program is run, following is the output −
-15536 50000

The above result is because the bit pattern that represents 50,000 as a short unsigned integer is interpreted as -15,536 by a short.
The type qualifiers provide additional information about the variables they precede.
const
Objects of type const cannot be changed by your program during execution.
volatile
The modifier volatile tells the compiler that a variable's value may be changed in ways not explicitly specified by the program.
restrict
A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Only C99 adds a new type qualifier called restrict.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Java program to find all close matches of input string from a list

To find all close matches of input string from a list, the Java code is as follows −
 Live Demo
import java.io.*;
import java.util.*;
public class Demo{
   static String string_encoding(String str){
      HashMap<Character, Integer> my_map = new HashMap<>();
      String result = "";
      int i = 0;
      char ch;
      for (int j = 0; j < str.length(); j++) {
         ch = str.charAt(j);
         if (!my_map.containsKey(ch))
         my_map.put(ch, i++);
         result += my_map.get(ch);
      }
      return result;
   }
   static void match_words( String[] my_arr, String my_pattern){
      int len = my_pattern.length();
      String hash_val = string_encoding(my_pattern);
      for (String word : my_arr){
         if (word.length() == len && string_encoding(word).equals(hash_val))
         System.out.print(word + " ");
      }
   }
   public static void main(String args[]){
      String[] my_arr = { "mno", "aabb", "pqr", "xxyy", "mmnn" };
      String my_pattern = "ddcc";
      System.out.println("The patterns similar to ddcc in the array are :");
      match_words(my_arr, my_pattern);
   }
}
The patterns similar to ddcc in the array are :
aabb xxyy mmnn
A class named Demo contains a function called ‘string_encoding’. This function creates a hashmap and iterates over the string to check if there are any patterns that match the string in question.
Another function named 'match_words' is defined that calls the 'string_encoding' function and
checks to see if there is any match in the arrays with the pattern of the string that is given as a reference. If found, the word is returned. In the main function, the string array is defined along with a pattern. The 'match_words' function is called on this pattern. The relevant output is displayed on the console.
How to create a pdf file in Java?

You can create a PDF file using the PDF Box library. You can set the environment for pdf box by following Pdf Box Environment Tutorial.
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class CreatingEmptyPdf {
   public static void main(String args[]) throws IOException {
      PDDocument document = new PDDocument();
      document.addPage(new PDPage());
      document.save("C:/pdfBox/BlankPdf.pdf");
      
      System.out.println("PDF created");
      document.close();
   }
}
PDF created
Angular 2 - Nested Containers

In Angular JS, it is possible to nest containers inside each other. The outside container is known as the parent container and the inner one is known as the child container. Let’s look at an example on how to achieve this. Following are the steps.
Step 1 − Create a ts file for the child container called child.component.ts.
Step 2 − In the file created in the above step, place the following code.
import { 
   Component 
} from '@angular/core';  

@Component ({ 
   selector: 'child-app', 
   template: '<div> {{values}} </div> ' 
}) 

export class ChildComponent { 
   values = ''; 
   ngOnInit() { 
      this.values = "Hello"; 
   } 
}
The above code sets the value of the parameter this.values to “Hello”.
Step 3 − In the app.component.ts file, place the following code.
import { 
   Component 
} from '@angular/core'; 

import { 
   ChildComponent 
} from './child.component'; 

@Component ({ 
   selector: 'my-app', 
   template: '<child-app></child-app> ' 
}) 

export class AppComponent { }
In the above code, notice that we are now calling the import statement to import the child.component module. Also we are calling the <child-app> selector from the child component to our main component.
Step 4 − Next, we need to ensure the child component is also included in the app.module.ts file.
import { 
   NgModule 
} from '@angular/core'; 

import { 
   BrowserModule 
} from '@angular/platform-browser';  

import { 
   AppComponent 
} from './app.component';  

import { 
   MultiplierPipe 
} from './multiplier.pipe' 

import { 
   ChildComponent 
} from './child.component';  

@NgModule ({ 
   imports: [BrowserModule], 
   declarations: [AppComponent, MultiplierPipe, ChildComponent], 
   bootstrap: [AppComponent] 
}) 

export class AppModule {}
Once you save all the code changes and refresh the browser, you will get the following output.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python | Pandas Index.equals() - GeeksforGeeks

16 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.equals() function determine if two Index objects contains the same elements. If they contain the same elements then the function returns True else the function returns False indicating the values contained in both the Indexes are different.
Syntax: Index.equals(other)
Parameters :Other : index
Returns : boolean value
Example #1: Use Index.equals() function to check if two Indexes contain same elements
# importing pandas as pdimport pandas as pd  # Creating the first Indexidx1 = pd.Index(['Labrador', 'Beagle', 'Labrador', 'Lhasa', 'Husky', 'Beagle'])  # Creating the second Indexidx2 = pd.Index(['Labrador', 'Beagle', 'Pug', 'Lhasa', 'Husky', 'Pitbull'])  # Print the first and second Indexprint(idx1, "\n", idx2)
Output :
Let’s check if the two Indexes are equal or not.
# Checking the equality of the two Indexesidx1.equals(idx2)
Output :
As we can see in the output, the Index.equals() function has returned False indicating that the Indexes are not equal. Example #2: Use Index.equals() function to check the equality of two Indexes.
# importing pandas as pdimport pandas as pd  # Creating the first Indexidx1 = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',                 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])  # Creating the second Indexidx2 = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',                 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])  # Print the first and second Indexprint(idx1, "\n", idx2)
Output :
Let’s check if the two Indices are equal to each other or not.
# test the equalityidx1.equals(idx2)
Output :The function has returned True indicating that both the Indexes are equal to each other.
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Return values of printf() and scanf() in C/C++

29 Nov, 2020
What values do the printf() and scanf() functions return ?  
printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error Example 1: The printf() function in the code written below returns 6. As ‘CODING’ contains 6 characters. 
CPP
// C/C++ program to demonstrate return value// of printf()#include <stdio.h> int main(){    char st[] = "CODING";     printf("While printing ");    printf(", the value returned by printf() is : %d",                                    printf("%s", st));     return 0;}
While printing CODING, the value returned by printf() is : 6
Example 2: The printf() function in the code written below returns 9. As ‘123456789’ contains 9 characters. 
CPP
// C/C++ program to demonstrate return value// of printf() #include <stdio.h>int main(){    long int n = 123456789;     printf("While printing ");    printf(", the value returned by printf() is : %d",                                    printf("%ld", n));     return 0;}
While printing 123456789, the value returned by printf() is : 9
 
 
scanf() : It returns total number of Inputs Scanned successfully, or EOF if input failure occurs before the first receiving argument was assigned.Example 1: The first scanf() function in the code written below returns 1, as it is scanning 1 item. Similarly second scanf() returns 2 as it is scanning 2 inputs and third scanf() returns 3 as it is scanning 3 inputs. 
CPP
// C/C++ program to demonstrate return value// of printf() #include <stdio.h>int main(){    char a[100], b[100], c[100];     // scanf() with one input    printf("\n First scanf() returns : %d",                            scanf("%s", a));     // scanf() with two inputs    printf("\n Second scanf() returns : %d",                       scanf("%s%s", a, b));     // scanf() with three inputs    printf("\n Third scanf() returns : %d",                  scanf("%s%s%s", a, b, c));     return 0;}
Input:
Hey!
welcome to
geeks for geeks


Output:
 First scanf() returns : 1
 Second scanf() returns : 2
 Third scanf() returns : 3
 
mdamircoder
nikhiljangira1
C-Input and Output Quiz
cpp-input-output
C Language
GFacts
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 QDoubleSpinBox – Getting Value Changed Signal

14 Jul, 2020
In this article we will see how we can get the value changed signal of the QDoubleSpinBox. User can set any decimal value(float) to the QDoubleSpinBox with the help of mouse and keyboard, but sometimes there is a need of setting value programmatically in order to overwrite the value entered by the user, it can be set with the help of setValue method. This signal get emitted when the value get changed.
In order to do this we will use valueChanged method with the QDateTimeEdit object.
Syntax : dd_spin.valueChanged.connect(method)
Argument : It takes method as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating double spin box        d_spin = QDoubleSpinBox(self)          # setting geometry to the double spin box        d_spin.setGeometry(100, 100, 150, 40)          # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry to the label        label.setGeometry(100, 200, 300, 80)          # making label multi line        label.setWordWrap(True)          # getting value changed signal of double spin box        d_spin.valueChanged.connect(lambda: spin_method())          def spin_method():              # setting text to the label            label.setText("Value Changed Signal")        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QDoubleSpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Using CHOOSE Function along with VLOOKUP in Excel

21 Aug, 2021
In Excel, managing space is a very important point to consider. Now, let’s suppose you are in a situation where you want to compare multiple columns in the Excel dataset, and you want to derive results, This is not possible using the VLOOKUP function alone. So, to make a function capable of doing something like this, we will introduce a special function known as CHOOSE function. But, if you don’t want to use CHOOSE function, then you have to use a helper column, making the job a little hectic.
So, in this article, we will see how to use VLOOKUP along with CHOOSE function.
First, we will see the syntax of CHOOSE FUNCTION in brief.
Syntax:
=CHOOSE(ARRAY DIMENSIONS(INDEX VALUE(S)),VALUE(1),VALUE(2),VALUE(3),.....)
Here,
 Here we will define array dimensions, ie how many columns should the array have.The next parameter(s) will define what value will go in the subsequent array columns, ie VALUE1 will get filled in the first column, and so on.   
 Here we will define array dimensions, ie how many columns should the array have.
The next parameter(s) will define what value will go in the subsequent array columns, ie VALUE1 will get filled in the first column, and so on.   
Example:
Here we will use this dataset. Let’s suppose we have people in a sales firm, and they are evaluated for bonuses. Now, we want to know who did sales for BED SHEETS, by using VLOOKUP and CHOOSE function. So, first of all, let’s see what the formula is, and then we will understand it part by part.
=VLOOKUP(B9,CHOOSE({1,2},C2:C6,A2:A6),2,TRUE)
Here the output will be as shown below:
Now, we will see part by part how this formula worked:
 B9: This is the targeted value to be compared by VLOOKUP to get the result, ie BED SHEETS.
CHOOSE({1,2},C2:C6,A2:A6): This will create an array,having first column values from C2 TO C6,and second column values from A2 TO A6.
2: The value will be fetched from this column number.
TRUE: This parameter is for enabling approximate search, ie any keyword found nearly matching with the required word will be given as a result.
VLOOKUP(B9, CHOOSE({1,2}, C2:C6, A2:A6),1, TRUE): VLOOKUP will search for the desired keyword from the second column of the array, created by CHOOSE function.
Note: The formula above will use an array, so to execute it use Ctrl+Shift+Enter key combination.
The disadvantage of the above function is that VLOOKUP is not capable of doing a case-sensitive search, so to enhance VLOOKUP you have to make it case sensitive. For reference visit this article.
Excel-VBA
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Normalize Data in Excel?
How to Get Length of Array in Excel VBA?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to make a 3 Axis Graph using Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Show Percentages in Stacked Column Chart in Excel?
How to Create a Macro in Excel?
Python – Remove leading 0 from Strings List

09 Mar, 2020
Sometimes, while working with Python, we can have a problem in which we have data in which we need to perform processing and then pass the data forward. One way to process is to remove a stray 0 that may get attached to a string while data transfer. Lets discuss certain ways in which this task can be performed.
Method #1 : Using lstrip() + list comprehensionThis is one of the one liner with the help of which this task can be performed. In this, we strip the leading 0 using lstrip and the extension of logic to list is done using list comprehension.
# Python3 code to demonstrate # Remove leading 0 from Strings List# using lstrip() + list comprehension  # Initializing listtest_list = ['012', '03', '044', '09']  # printing original listprint("The original list is : " + str(test_list))  # Remove leading 0 from Strings List# using lstrip() + list comprehensionres = [ele.lstrip('0') for ele in test_list]  # printing result print ("The string list after leading 0 removal : " + str(res))
The original list is : ['012', '03', '044', '09']
The string list after leading 0 removal : ['12', '3', '44', '9']

 
Method #2 : Using startswith() + loop + list slicingThis is one of the way in which this task can be performed. In this, we check for initial 0 using startswith() and then list slicing is used to remake string excluding 0.
# Python3 code to demonstrate # Remove leading 0 from Strings List# using startswith() + loop + list slicing  # Initializing listtest_list = ['012', '03', '044', '09']  # printing original listprint("The original list is : " + str(test_list))  # Remove leading 0 from Strings List# using startswith() + loop + list slicingfor idx in range(len(test_list)):    if test_list[idx].startswith('0'):        test_list[idx] = test_list[idx][1:]  # printing result print ("The string list after leading 0 removal : " + str(test_list))
The original list is : ['012', '03', '044', '09']
The string list after leading 0 removal : ['12', '3', '44', '9']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to unchecked a radio button using JavaScript/jQuery?

07 May, 2019
In order to uncheck a radio button, there is a lot of methods available, but we are going to see the most preferred methods.
Example 1: This example unchecks the radio button by using Javascript checked property. The JavaScript Radio checked property is used to set or return the checked state of an Input Radio Button. This property is used to reflect the HTML checked attribute.
<!DOCTYPE html> <html>     <head>         <title>             JavaScript | uncheck a radio button        </title>     </head>           <body style = "text-align:center;" id = "body">                   <h1 style = "color:green;" >             GeeksForGeeks         </h1>                   <input id = "radio" type="radio" name="GFG"                value="GeeksForGeeks" checked>GFG                          <br><br>                  <button onclick = "gfg_Run()">             uncheck        </button>                  <p id="GFG_DOWN" style="color:green;font-size:20px;"></p>                  <script>            var el_down = document.getElementById("GFG_DOWN");                          function gfg_Run() {                var radioButton = document.getElementById("radio");                radioButton.checked = false;                el_down.innerHTML = "Unchecked";            }        </script>     </body> </html>                    
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example unchecks the radio button by using jQuery prop() method. The prop() method in jQuery which is used to set or return the properties and values for the selected elements.
<!DOCTYPE html>  <html>      <head>         <title>             JQuery | Uncheck a radio button        </title>                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">        </script>    </head>           <body style = "text-align:center;" id = "body">                    <h1 style = "color:green;" >              GeeksForGeeks          </h1>                   <input id = "radio" type="radio" name="GFG"                 value="GeeksForGeeks" checked>GFG                          <br><br>                  <button onclick = "gfg_Run()">             uncheck        </button>                  <p id="GFG_DOWN" style="color:green;font-size:20px;"></p>                  <script>            var el_down = document.getElementById("GFG_DOWN");                          function gfg_Run() {                $("#radio").prop("checked", false);                el_down.innerHTML = "Unchecked";            }        </script>     </body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
jQuery-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | DOM onbeforeunload Event

03 Mar, 2022
The onbeforeunload event occurs when you click a text link or picture link or any kind of link which will bring you to a new page. This event will display a confirmation dialog box to inform the user whether the user wants to stay on the page or leave the current page move on to the next linked page. The message in dialog box cannot be removed.
Supported HTML Tags
 <body>
Syntax: 
In HTML:
<element onbeforeunload="myScript">
In JavaScript:
object.onbeforeunload = function(){myScript};
In JavaScript, using the addEventListener() method:
object.addEventListener("beforeunload", myScript);
Below examples illustrate the onbeforeunload Event in HTML DOM:  
Example: Using HTML
HTML
<!DOCTYPE html><html> <head>    <title>HTML | DOM onbeforeunload attribute</title>    <style>        body {            text-align: center;        }                 h1 {            color: green;        }                 a {            text-decoration: none;                     }    </style></head> <body onbeforeunload="return myFunction()">    <h1>GeeksforGeeks</h1>    <h3>HTML | DOM onbeforeunload attribute</h3>      <p>Go to        <a href="https://ide.geeksforgeeks.org/">GeeksforGeeks </a>    ide</p>      <script>        function myFunction() {            return "This document is ready to load";        }    </script></body> </html>
Output: After loading the code:
After clicking the text link:
Example: Using JavaScript
HTML
<!DOCTYPE html><html> <head>    <title>HTML | DOM onbeforeunload attribute</title>    <style>        body {            text-align: center;        }                 h1 {            color: green;        }                 a {            text-decoration: none;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h3>HTML | DOM onbeforeunload attribute</h3>      <p>Go to        <a href="https://ide.geeksforgeeks.org/">GeeksforGeeks </a>    ide</p>      <script>        window.onbeforeunload = function(event) {            event.returnValue = "This document is ready to load";        };    </script></body> </html>
Output: After loading the code:  
After clicking the text link:  
Example:In JavaScript, using the addEventListener() method:
HTML
<!DOCTYPE html><html> <head>    <title>HTML | DOM onbeforeunload attribute</title>    <style>        body {            text-align: center;        }                 h1 {            color: green;        }                 a {            text-decoration: none;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h3>HTML | DOM onbeforeunload attribute</h3>      <p>Go to        <a href="https://ide.geeksforgeeks.org/">GeeksforGeeks </a>    ide</p>      <script>        window.addEventListener("beforeunload", function(event) {            event.returnValue = "This document is ready to load";        });    </script></body> </html>
Output: After loading the code:
After clicking the text link:
Supported Browsers:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera 15.0
 
nidhi_biet
sweetyty
chhabradhanvi
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pointers to a Function in Go

19 Aug, 2021
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. You can also pass the pointers to the function like the variables. There are two ways to do this as follows:
In the below program we are taking a function ptf which have integer type pointer parameter which instructs the function to accept only the pointer type argument. Basically, this function changed the value of the variable x. At starting x contains the value 100. But after the function call, value changed to 748 as shown in the output. 
Go
// Go program to create a pointer// and passing it to the functionpackage main import "fmt" // taking a function with integer// type pointer as an parameterfunc ptf(a *int) {     // dereferencing    *a = 748} // Main functionfunc main() {     // taking a normal variable    var x = 100         fmt.Printf("The value of x before function call is: %d\n", x)     // taking a pointer variable    // and assigning the address    // of x to it    var pa *int = &x     // calling the function by    // passing pointer to function    ptf(pa)     fmt.Printf("The value of x after function call is: %d\n", x) }
Output:
The value of x before function call is: 100
The value of x after function call is: 748
Considering the below program, we are not creating a pointer to store the address of the variable x i.e. like pa in the above program. We are directly passing the address of x to the function call which works like the above-discussed method. 
Go
// Go program to create a pointer// and passing the address of the// variable to the functionpackage main import "fmt" // taking a function with integer// type pointer as an parameterfunc ptf(a *int) {     // dereferencing    *a = 748} // Main functionfunc main() {     // taking a normal variable    var x = 100         fmt.Printf("The value of x before function call is: %d\n", x)     // calling the function by    // passing the address of    // the variable x    ptf(&x)     fmt.Printf("The value of x after function call is: %d\n", x) }
Output:
The value of x before function call is: 100
The value of x after function call is: 748
Note: You can also use the short declaration operator(:=) to declare the variables and pointers in above programs. 
abhishek0719kadiyan
Golang
Golang-Pointers
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to concatenate two strings in Golang
time.Sleep() Function in Golang With Examples
strings.Contains Function in Golang with Examples
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Time Formatting in Golang
Interfaces in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
Matplotlib.axes.Axes.set_ylabel() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_ylabel() function in axes module of matplotlib library is used to set the label for the y-axis.
Syntax: Axes.set_ylabel(self, xlabel, fontdict=None, labelpad=None, **kwargs)
Parameters: This method accepts the following parameters.
ylabel : This parameter is the label text.
labelpad : This parameter is the spacing in points from the axes bounding box including ticks and tick labels.
Returns:This method does not returns any value.
Below examples illustrate the matplotlib.axes.Axes.set_ylabel() function in matplotlib.axes:
Example 1:
import matplotlib.pyplot as pltimport numpy as np   t = np.arange(0.01, 5.0, 0.01)s = np.exp(-t)   fig, ax = plt.subplots()   ax.plot(t, s)ax.set_ylim(1, 0)ax.set_ylabel('Display Y-axis Label',               fontweight ='bold')ax.grid(True)   ax.set_title('matplotlib.axes.Axes.set_ylabel() \Examples\n', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
#Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.cbook as cbook   with cbook.get_sample_data('goog.npz') as datafile:    price_data = np.load(datafile)['price_data'].view(np.recarray)      # get the most recent 250 # trading daysprice_data = price_data[-250:]     delta1 = np.diff(price_data.adj_close) / price_data.adj_close[:-1]   volume = (25 * price_data.volume[:-2] / price_data.volume[0])**(2.2)close = (0.03 * price_data.close[:-2] / 0.03 * price_data.open[:-2])**2   fig, ax = plt.subplots()ax.scatter(delta1[:-1], delta1[1:],           c=close, s=volume,           alpha=0.5)   ax.set_ylabel(r'Y-axis contains $\Delta_{i+1}$ values',              fontweight='bold')ax.grid(True)fig.suptitle('matplotlib.axes.Axes.set_ylabel() Examples\n',             fontsize=14, fontweight='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
SQL | ON Clause

13 May, 2018
The join condition for the natural join is basically an EQUIJOIN of all columns with same name. To specify arbitrary conditions or specify columns to join, the ON Clause is used.
The join condition is separated from other search conditions.The ON Clause makes code easy to understand.ON Clause can be used to join columns that have different names.We use ON clause to specify a join condition. This lets us specify join conditions separate from any search or filter conditions in the WHERE clause.
The join condition is separated from other search conditions.
The ON Clause makes code easy to understand.
ON Clause can be used to join columns that have different names.
We use ON clause to specify a join condition. This lets us specify join conditions separate from any search or filter conditions in the WHERE clause.
EXAMPLES:
We will apply the below mentioned commands on the following base tables:
Employees TableDepartments Table
Employees Table
Departments Table
QUERY 1: Write SQL query to find the working location of the employees. Also give their respective employee_id, last_name and department_id?
Input :SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);
Output : 

QUERY 1: Write SQL query to find the working location of the employees. Also give their respective employee_id, last_name and department_id?

Input :SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);
Output : 

Explanation: The example shown joins the DEPARTMENT_ID column in the EMPLOYEES and DEPARTMENTStables using ON Clause, and thus shows the required data.
We will apply the below mentioned commands on the following base tables:
Countries TableLocations Table
Countries Table
Locations Table
QUERY 2: Write SQL query to find the location_id, street_address, postal_code and their respective country name?

Input : SELECT l.location_id, l.street_address, l.postal_code, c.country_name
FROM locations l JOIN countries c
ON (l.country_id = c.country_id);
Output : 


Explanation: The example shown joins the COUNTRY_ID column in the LOCATIONS and COUNTRIEStables using the ON Clause, and thus shows the required details.
Oracle
SQL-Clauses
SQL
Oracle
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
How to print data of specific element from an array in java?

An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.
The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.
Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.
You can access an array element using an expression which contains the name of the array followed by the index of the required element in square brackets. To print it simply pass this method to the println() method.
 Live Demo
public class PrintingElement {
   public static void main(String args[]){
      int [] myArray = {23, 93, 56, 92, 39};
      System.out.println(myArray[2]);
   }
}
56
How to create an array with key value pairs in PHP?

25 Sep, 2019
PHP offers us a special type of array called an Associative Array that allows us to create an array with Key-Value pairs. The syntax for creating an Associative Array is as follows:
Syntax 1: Using array() constructor
$arrayVariable = array(
    key1  => value1,
    key2 => value2,
    key3 => value3,
    ...
    keyN => valueN,
);

Syntax 2: Using shorthand notation
$arrayVariable = [
    key1  => value1,
    key2 => value2,
    key3 => value3,
    ...
    keyN => valueN,
];

Note:
The comma after the last Key-Value pair is optional.The Key can be of either integer or string type.The Value can be of any valid type.If the type of Key is other that string or integer, it will be cast to string or integer depending on the type of Key.
The comma after the last Key-Value pair is optional.
The Key can be of either integer or string type.
The Value can be of any valid type.
If the type of Key is other that string or integer, it will be cast to string or integer depending on the type of Key.
Example 1: Using array() constructor
<?php$websites = array(    "Facebook" => "Facebook, Inc. is an online social media and social networking service company.",    "Twitter" => "Twitter is a microblogging and social networking service on which users post and interact with messages known as tweets.",    "LinkedIn" => "LinkedIn is a business and employment-oriented service that operates via websites and mobile apps.");      $websites["Instagram"] = "Instagram is a photo and video-sharing social networking service owned by Facebook, Inc.";foreach ($websites as $key => $value) {    echo "<p>$key: $value <p>";}?>
Output:
Example 2: Using shorthand notation
<?php$websites = [    "Facebook" => "Facebook, Inc. is an online social     media and social networking service company.",          "Twitter" => "Twitter is a microblogging and social networking service     on which users post and interact with messages known as tweets.",          "LinkedIn" => "LinkedIn is a business and     employment-oriented service that operates via websites and mobile apps."];      $websites[    "Instagram"] = "Instagram is a photo and video-sharing     social networking service owned by Facebook, Inc.";foreach ($websites as $key => $value) {    echo "<p>$key: $value <p>";}?>
Output:
Picked
PHP
Technical Scripter
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
Comparing two dates in PHP
How to receive JSON POST with PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to extract the whole JSON response as a string in Rest Assured?

We can extract the whole JSON as a string in Rest Assured. This is achieved with the help of the extract method. It shall extract the whole response as a string using the asString method.
We shall send a GET request via Postman on a mock API, observe the Response.
Using Rest Assured, we shall get the whole response in string format.
Code Implementation
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
public class NewTest {
   @Test
   public void getResponseAsString() {

      //base URL
      RestAssured.baseURI = "https://run.mocky.io/v3";

      String r = RestAssured.given().when()

      //get request
      .get("/cd3a7e12-9057-4b51-bf2d-a2d4e2ddad8d")

      //get response as string
      .then().extract().response().asString();

      System.out.println(r);
   }
}
SQL - SUM Function

SQL SUM function is used to find out the sum of a field in various records.
To understand SUM  function, consider an employee_tbl table, which is having the following records −
SQL> 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 calculate total of all the dialy_typing_pages, then you can do so by using the following command −
SQL> SELECT SUM(daily_typing_pages)
   -> FROM employee_tbl;
+-------------------------+
| SUM(daily_typing_pages) |
+-------------------------+
|                    1610 |
+-------------------------+
1 row in set (0.00 sec)
You can take sum of various records set using GROUP BY clause. Following example will sum up all the records related to a single person and you will have total typed pages by every person.
SQL> SELECT name, SUM(daily_typing_pages)
   -> FROM employee_tbl GROUP BY name;
+------+-------------------------+
| name | SUM(daily_typing_pages) |
+------+-------------------------+
| Jack |                     270 |
| Jill |                     220 |
| John |                     250 |
| Ram  |                     220 |
| Zara |                     650 |
+------+-------------------------+
5 rows in set (0.17 sec)

    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
What happens when you add a double value to a String in java?

The “+” operator with a String acts as a concatenation operator.
Whenever you add a String value to a double using the “+” operator, both values are concatenated resulting a String object.
In-fact adding a double value to String is the easiest way to convert a double value to Strings.
import java.util.Scanner;
   public class StringsExample {
      public static void main(String args[]){
         Scanner sc = new Scanner(System.in);
         System.out.println("Enter a double value: ");
         double d = sc.nextDouble();
         System.out.println("Enter a String value: ");
         String str = sc.next();
         //Adding double and String
         String result = str+d;
         System.out.println("Result of the addition "+result);
      }
   }
}
Enter a double value:
245.5474
Enter a String value:
test
Result of the addition test245.5474
Splitting and Merging Channels with Python-OpenCV - GeeksforGeeks

17 Oct, 2021
In this article, we will learn how to split a multi-channel image into separate channels and combine those separate channels into a multi-channel image using OpenCV in Python. 
To do this, we use cv2.split() and cv2.merge() functions respectively. 
Image Used:
cv2.split() is used to split coloured/multi-channel image into separate single-channel images. The cv2.split() is an expensive operation in terms of performance(time). The order of the output vector of arrays depends on the order of channels of the input image.
Syntax: cv2.split(m[, mv])
Parameters:
m: Input multi-channel array
mv: Output vector of arrays
Example:
Python3
# Python program to explain splitting of channels  # Importing cv2import cv2   # Reading the image using imread() functionimage = cv2.imread('img.jpg')  # Displaying the original BGR imagecv2.imshow('Original_Image', image)  # Using cv2.split() to split channels of coloured image b,g,r = cv2.split(image)  # Displaying Blue channel image# Blue colour is highlighted the mostcv2.imshow("Model Blue Image", b)  # Displaying Green channel image# Green colour is highlighted the mostcv2.imshow("Model Green Image", g)  # Displaying Red channel image# Red colour is highlighted the mostcv2.imshow("Model Red Image", r)  # Waits for user to press any keycv2.waitKey(0)
Output:
cv2.merge() is used to merge several single-channel images into a colored/multi-channel image.
Syntax: cv2.merge(mv[, dst])
Parameters:
mv: Input vector of matrices to be merged. All matrices must have same size.
dst: Output multi-channel array of size mv[0]. Number of channel will be equal to total no. of channel in matrix array.
Example: 
Python3
# Python program to explain Merging of Channels  # Importing cv2import cv2  # Reading the BGR image using imread() functionimage = cv2.imread("img.jpg")  # Splitting the channels first to generate different # single  # channels for merging as we don't have separate# channel imagesb, g, r = cv2.split(image)  # Displaying Blue channel imagecv2.imshow("Model Blue Image", b)  # Displaying Green channel imagecv2.imshow("Model Green Image", g)  # Displaying Red channel imagecv2.imshow("Model Red Image", r)  # Using cv2.merge() to merge Red, Green, Blue Channels  # into a coloured/multi-channeled imageimage_merge = cv2.merge([r, g, b])  # Displaying Merged RGB imagecv2.imshow("RGB_Image", image_merge)  # Waits for user to press any keycv2.waitKey(0)
Output:
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python