code-rag-bench/online-tutorials huggingface dataset:
Preprocessor output of cpp file - GeeksforGeeks

19 Jan, 2021
Preprocessing is a stage where preprocessor directives are expanded or processed before source code is sent to the compiler. The most common example of such directive is #include or #define. A preprocessor output has “.i” extension.
Two files are created here:
C++
MyHeader.h
// C++ program for the test.cpp#include "MyHeader.h"#include <iostream>using namespace std;#define VAL 9  // Driver Codeint main(){    // powerOfTwo function is defined    // in “MyHeader.h”    cout << powerOfTwo(VAL) << endl;      return 0;}
// Below is code for the header file// named as "MyHeader.h"#pragma once  // Function to find the value of 2^xsize_t powerOfTwo(const int x){      // return the value    return 1 << x;}
Now on command prompt, the output can be preprocessed in two ways:
Method 1 – inside cmd.exe: This method is not recommended.
g++ -E test.cpp
Here, output can’t be shown as header file iostream will expand up to 50000 lines. This will print all the data on the command prompt which might take a few moments as cout is quite slow in printing. Press any key to stop printing on prompt. The command prompt doesn’t retain all 50000 lines. It has its own limits after which earlier outputs can’t be seen.
Method 2 – Create an explicit file “.i”:
Use the below-given command to get hello.i
g++ -E test.cpp -o hello.i
Output:
Explanation: In the above output, there are only 26000 lines. It is normal as iostream is a big header file and also includes many other header files that do include others. #include directive just copies the content of respective header files.As noticed, the actual program lies at the very end at 26527 lines but still, it gives error messages for the correct line. Also, all content of multiple files is wrapped into hello.i but still error messages received for correct file context.
# 7 "MyHeader.h"
This is the line control directive. It will tell the compiler that the next line is the 7th line in the file MyHeader.h. If the above code is executed, then the function powerOfTwo() is defined at line number 7. Also, macro VAL is completely replaced by 9.
The preprocessor output file can be compiled using the below command:
g++ hello.i -o test.exe
Preprocessing of include directive :
// test.cpp
#include<iostream>

int main(){
  std::cout << "GeekForGeeks" << std::endl
  #include"MyHeader.h"
}
// MyHeader.h
;
In the above example, the semi-colon is copied and pasted from MyHeader.h to the line next to cout statement by #include directive. Hence, no error will generate here. Also, Myheader.h can be a text file, a python file, or HTML file no matter what, #include will just copy it.
CPP-Basics
CPP-Output
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
MongoDB - Bulk.insert() Method - GeeksforGeeks

21 Jul, 2021
In MongoDB, the Bulk.insert() method is used to perform insert operations in bulk. Or in other words, the Bulk.insert() method is used to insert multiple documents in one go. To use Bulk.insert() method the collection in which data has to be inserted must already exist. 
Syntax:
Bulk.insert(<document>);
Parameter:
document: The document that has to be inserted.
Examples:
In the following examples, we are working with:
Database: myDatabase
Collection: students
Now, let’s use the below commands to make an object of Bulk using initializeUnorderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeUnorderedBulkOp() method is used to generate an unordered list that MongoDB runs in bulk.
var bulk = db.students.initializeUnorderedBulkOp();
bulk.insert( { first_name: "Sachin", last_name: "Tendulkar" } );
bulk.insert( { first_name: "Virender", last_name: "Sehwag" } );
bulk.insert( { first_name: "Shikhar", last_name: "Dhawan" } );
bulk.insert( { first_name: "Mohammed", last_name: "Shami" } );
bulk.insert( { first_name: "Shreyas", last_name: "Iyer" } );
bulk.execute();
Let’s check the inserted documents using the below command:
db.students.find();
Now, let’s use the below commands to make an object of Bulk using initializeOrderedBulkOp() and use Bulk.insert() to insert multiple documents. Here, the initializeOrderedBulkOp() method is used to generate an ordered list that MongoDB runs in bulk.
var bulk = db.students.initializeOrderedBulkOp();
bulk.insert( { first_name: "Robin", last_name: "Marvin" } );
bulk.insert( { first_name: "John", last_name: "Hudson" } );
bulk.insert( { first_name: "Nancy", last_name: "Drew" } );
bulk.insert( { first_name: "Tom", last_name: "Wheeler" } );
bulk.insert( { first_name: "Anna", last_name: "Ryder" } );
bulk.execute();
Let’s check the inserted documents. Since we have inserted 5 more items into the collection, run the below command to get the last 5 items from the collection.
db.students.find().sort({'_id':-1}).limit(5).pretty()
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
MongoDB - sort() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB - Update() Method
MongoDB Cursor
MongoDB updateMany() Method - db.Collection.updateMany()
Matplotlib.figure.Figure.draw() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The draw() method figure module of matplotlib library is used to render the figure using matplotlib.backend_bases.RendererBase instance renderer.
Syntax: draw(self, renderer)
Parameters: This accept the following parameters that are described below:
renderer: This parameter is the matplotlib.backend_bases.RendererBase instance renderer.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.figure.Figure.draw() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt      fig, ax = plt.subplots()      def tellme(s):     ax.set_title(s, fontsize = 16)     fig.canvas.draw()    renderer = fig.canvas.renderer    fig.draw(renderer)   tellme('matplotlib.figure.Figure.draw() \function Example')   plt.show()
Output:
Example 2:
# Implementation of matplotlib function from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt        fig = plt.figure() ax = fig.add_subplot(111, projection ='3d')      X, Y, Z = axes3d.get_test_data(0.1) ax.plot_wireframe(X, Y, Z, rstride = 5,                    cstride = 5)      for angle in range(0, 90):     ax.view_init(30, angle)    fig.canvas.draw()    renderer = fig.canvas.renderer    fig.draw(renderer)     plt.pause(.001)      fig.suptitle('matplotlib.figure.Figure.draw() \    function Example')
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Instant toEpochMilli() method in Java with Examples - GeeksforGeeks

17 Feb, 2021
The toEpochMilli() method of an Instant class is used to convert this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z to a long value. This method returns that long value.Syntax:  
public long toEpochMilli()
Returns: This method returns number of milliseconds since the epoch of 1970-01-01T00:00:00Z.Exception: This method throws ArithmeticException if numeric overflow occurs.Below programs illustrate the Instant.toEpochMilli() method:Program 1:  
Java
// Java program to demonstrate// Instant.toEpochMilli() method import java.time.*; public class GFG {    public static void main(String[] args)    {         // create a Instant object        Instant instant            = Instant.parse("2018-12-30T19:34:50.63Z");         // get millisecond value using toEpochMilli()        long value = instant.toEpochMilli();         // print result        System.out.println("Millisecond value: "                           + value);    }}
Program 2:  
Java
// Java program to demonstrate// Instant.toEpochMilli() method import java.time.*; public class GFG {    public static void main(String[] args)    {         // create a Instant object        Instant instant = Instant.now();         // current Instant        System.out.println("Current Instant: "                           + instant);         // get millisecond value using toEpochMilli()        long value = instant.toEpochMilli();         // print result        System.out.println("Millisecond value: "                           + value);    }}
References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#toEpochMilli() 
arorakashish0911
Java - util package
Java-Functions
Java-Instant
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Internal Working of HashMap in Java
Comparator Interface in Java with Examples
Strings in Java
io.TeeReader() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The TeeReader() function in Go language is used to return a “Reader” that reads from the stated “r” and then writes it to the stated “w”. And here all the reads that are executed through the stated “r” are compared with the equivalent writes to the stated “w”. This method doesn’t require any internal buffering and the write is completed once the read completes. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func TeeReader(r Reader, w Writer) Reader

Here, “r” is the stated Reader and “w” is the stated Writer.
Return value: It returns a “Reader” that reads from the stated “r” and then writes it to the given “w”. However, any error faced while writing the content is returned as a read error.
Below examples illustrates the use of above method:
Example 1:
// Golang program to illustrate the usage of// io.TeeReader() function  // Including main packagepackage main  // Importing fmt, io, strings, bytes, and osimport (    "bytes"    "fmt"    "io"    "os"    "strings")  // Calling mainfunc main() {      // Defining reader using NewReader method    reader := strings.NewReader("GfG\n")      // Defining buffer    var buf bytes.Buffer      // Calling TeeReader method with its parameters    r := io.TeeReader(reader, &buf)      // Calling Copy method with its parameters    Reader, err := io.Copy(os.Stdout, r)      // If error is not nil then panics    if err != nil {        panic(err)    }      // Prints output    fmt.Printf("n: %v\n", Reader)}
Output:
GfG
n: 4

In the above example, Copy() method is used in order to return the “Reader”, NewReader() method of strings is used from where the content to be read is written and an external buffer is also used here.
Example 2:
// Golang program to illustrate the usage of// io.TeeReader() function  // Including main packagepackage main  // Importing fmt, io, strings, bytes, and osimport (    "bytes"    "fmt"    "io"    "os"    "strings")  // Calling mainfunc main() {      // Defining reader using NewReader method    reader := strings.NewReader("GeeksforGeeks\nis\na\nCS-Portal.\n")      // Defining buffer    var buf bytes.Buffer      // Calling TeeReader method with its parameters    r := io.TeeReader(reader, &buf)      // Calling Copy method with its parameters    Reader, err := io.Copy(os.Stdout, r)      // If error is not nil then panics    if err != nil {        panic(err)    }      // Prints output    fmt.Printf("n: %v\n", Reader)}
Output:
GeeksforGeeks
is
a
CS-Portal.
n: 30

Golang-io
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Time Durations in Golang
Strings in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang
How to create mat-button-toggle-group as read only mode in AngularJS ? - GeeksforGeeks

30 Nov, 2020
Angular Material is a UI component library developed by the Angular team to build design components for desktop and mobile web applications. 
In order to install it, we need to have angular installed in our project, once you have it, you can enter the below command and can download it.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatButtonToggleModule,’ from ‘@angular/material’ in the app.module.ts file.
Then use <mat-button-toggle-group> and </mat-button-toggle> tags to create angular button toggle group.
As the MatButtonToggleModule doesn’t consist of read-only property, we can use the disabled property to make it read-only.
Once done with the above steps then serve or start the project.
Code implementation:
app.module.ts:
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from     '@angular/platform-browser';import { FormsModule } from '@angular/forms';  import { AppComponent } from './app.component';  import { BrowserAnimationsModule } from     '@angular/platform-browser/animations';  import { MatButtonModule } from     '@angular/material/button';import { MatButtonToggleModule } from     '@angular/material/button-toggle';  @NgModule({  imports:      [ BrowserModule,                   FormsModule,                   BrowserAnimationsModule,                   MatButtonModule,                  MatButtonToggleModule ],  declarations: [ AppComponent ],  bootstrap:    [ AppComponent ]})export class AppModule { }
app.component.html:
HTML
<mat-button-toggle-group name="techno"     aria-label="technology">          <mat-button-toggle value="html">        HTML    </mat-button-toggle>          <mat-button-toggle disabled value="css">        CSS    </mat-button-toggle>          <mat-button-toggle value="javascript">        Javascript    </mat-button-toggle>          <mat-button-toggle value="jquery">        Jquery    </mat-button-toggle></mat-button-toggle-group>
Output:
Observation: If you clearly observe the above output, you can understand that you can’t select and it is the way how read-only property looks like.
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Java Program to Calculate Sum of Two Byte Values Using Type Casting - GeeksforGeeks

11 Nov, 2020
The addition of two-byte values in java is the same as normal integer addition. The byte data type is 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The Sum of two-byte values might cross the given limit of byte, this condition can be handled using storing the sum of two-byte numbers in an integer variable.
Example:
Input:  firstByte = 10, secondByte = 23
Output: Sum = 33

Input:  firstByte = 10, secondByte = 23
Output: Sum = 33

Type Casting: Typecasting is simply known as cast one data type, into another data type. For example, in this program, Byte values are cast into an integer.
Approach:
Declare and initialize the two-byte variable.
Declare one int variable.
Store the sum of the two-byte numbers into an int variable.
Below is the implementation of the above approach
Java
// Java Program to Calculate Sum of// Two Byte Values Using Type Casting  public class GFG {    public static void main(String[] args)    {        // create two variable of byte type        byte firstByte = 113;        byte secondByte = 123;          // create int variable to store result        int sum;          sum = firstByte + secondByte;        System.out.println("sum = " + sum);    }}
sum = 236


Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
#define vs #undef in C language - GeeksforGeeks

04 May, 2021
In this article, we will discuss the difference between #define and #undef pre-processor in C language.
Pre-Processor:
Pre-processor is a program that performs before the compilation.
It only notices the # started statement.
# is called preprocessor directive.
Each preprocessing directive must be on its own line.
The word after # is called the preprocessor command.
#define:
The #define directive defines an identifier and a character sequence (a set of characters) that will be substituted for the identifier each time it is encountered in the source file.
Syntax:
#define macro-name char-sequence.The identifier is referred to as a macro name and replacement process as a macro replacement.
Example:
#define PI 3.14Here. PI is the macro-name and 3.14 is the char-sequence.
Program 1:
Below is the C program illustrating the use of #define: 
C
// C program illustrating the use of// #define#include <stdio.h>#define PI 3.14  // Driver Codeint main(){    int r = 4;    float a;      a = PI * r * r;    printf("area of circle is %f", a);      return 0;}
area of circle is 50.240002

Explanation:
In this example, PI is the macro-name and the char-sequence is 3.14.
When the program runs the compiler will check the #define command first and assign the PI as 3.14.
Now in the entire program wherever the compiler sees the PI word it will replace it with 3.14.
Program 2:
 Below is the C program printing product of two numbers using #define:
C
// C program to find the product of// two numbers using #define  #include <stdio.h>#define PRODUCT(a, b) a* b  // Driver Codeint main(){    printf("product of a and b is "           "%d",           PRODUCT(3, 4));      return 0;}
product of a and b is 12

Explanation:
In this example, a macro-name as the product is defined and passes two arguments as a and b and gives the char-sequence as the product of these two arguments.
When the compiler sees the macro-name in the print statement, it replaces the macro-name with the product of a and b and gives the answer as their product.
#undef:
The #undef preprocessor directive is used to undefined macros. 
Syntax:
#undef macro-name
Program 3:
Below is the C program to illustrate the use of #undef in a program:
C
// C program to illustrate the use// of #undef in a program#include <stdio.h>#define PI 3.14#undef PI  // Driver Codeint main(){    int r = 6;    float a;    a = PI * r * r;      printf("area of circle is %f", a);      return 0;}
Output:
Explanation: In this example, when #undef is used, then it will delete the #define command and the macro will get undefined and the compiler will show the error. 
C-Macro & Preprocessor
Macro & Preprocessor
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
How to write a Python regular expression that matches floating point numbers?

The following code uses Python regex to match floating point numbers
import re
s = '234.6789'
match = re.match(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?',s)
print match.group()
s2 = '0.45'
match = re.match(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?',s2)
print match.group()
This gives the output
234.6789
0.45
C++ map having key as a user define data type

30 Mar, 2018
C++ map stores keys in ordered form (Note that it internally use a self balancing binary search tree). Ordering is internally done using operator ” < " So if we use our own data type as key, we must overload this operator for our data type.
Let us consider a map having key data type as a structure and mapped value as integer.
// key's structure
struct key
{
    int a;
};
// CPP program to demonstrate how a map can// be used to have a user defined data type// as key.#include <bits/stdc++.h>using namespace std;struct Test {    int id;};  // We compare Test objects by their ids.bool operator<(const Test& t1, const Test& t2){    return (t1.id < t2.id);}  // Driver codeint main(){    Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };      // Inserting above four objects in an empty map    map<Test, int> mp;    mp[t1] = 1;    mp[t2] = 2;    mp[t3] = 3;    mp[t4] = 4;      // Printing Test objects in sorted order    for (auto x : mp)        cout << x.first.id << " " << x.second << endl;    return 0;}
101 3
102 2
110 1
115 4

We can also make < operator a member of structure/class.
// With < operator defined as member method.#include <bits/stdc++.h>using namespace std;struct Test {    int id;      // We compare Test objects by their ids.    bool operator<(const Test& t) const    {        return (this->id < t.id);    }};  // Driver codeint main(){    Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };      // Inserting above four objects in an empty map    map<Test, int> mp;    mp[t1] = 1;    mp[t2] = 2;    mp[t3] = 3;    mp[t4] = 4;      // Printing Test objects in sorted order    for (auto x : mp)        cout << x.first.id << " " << x.second << endl;    return 0;}
101 3
102 2
110 1
115 4

What happens if we do not overload < operator?We get compiler error if we try to insert anything into the map.
#include <bits/stdc++.h>using namespace std;struct Test {    int id;};  // Driver codeint main(){    map<Test, int> mp;    Test t1 = {10};    mp[t1] = 10;    return 0;}
/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for 'operator<' (operand types are 'const Test' and 'const Test')
       { return __x < __y; }

cpp-map
cpp-operator-overloading
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Unordered Sets in C++ Standard Template Library
Pair in C++ Standard Template Library (STL)
std::string class in C++
Friend class and function in C++
Queue in C++ Standard Template Library (STL)
List in C++ Standard Template Library (STL)
Inline Functions in C++
vector insert() function in C++ STL
C# - Continue Statement

The continue statement in C# works somewhat like the break statement. Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control passes to the conditional tests.
The syntax for a continue  statement in C# is as follows −
continue;

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
         
         /* do loop execution */
         do {
            if (a == 15) {
               /* skip the iteration */
               a = a + 1;
               continue;
            }
            Console.WriteLine("value of a: {0}", a);
            a++;
         } 
         while (a < 20);
         Console.ReadLine();
      }
   }
} 
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Why “0” is equal to false in JavaScript ?

27 Jun, 2019
In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.
Example: This example illustrates why “0” equals to false.
<script>          // JavaScript code to demonstrate     // why “0” is equal to false          function GFG() {              // Print type of "0"        document.write(typeof "0" + "</br>");              // Test whether "0" equals to false        // or not. If "0" is equal to false        // then "0" == false i.e.        // false == false which return true        var result = ("0" == false);                  // Print result        document.write(result + "</br>");                  // Convert and print "0" to its numeric        // value        document.write(Number("0") + "</br>");                  // Convert and print false in numeric value        document.write(Number(false) + "</br>");                  // So both numeric value are same        // Therefore condition "0" == false        // evaluates to true        document.write("0" == false);        document.write("</br>");                  // Or this statement        document.write(Number("0") == Number(false));    }          // Driver code    GFG();      </script>
Output:
string
true
0
0
true
true

So, from above it is clear that “0” is equal to false and reason behind this behavior is also clear, but when “0” is tested in if condition then it evaluates to true.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
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 ?
PostgreSQL – Constants

28 Aug, 2020
Unlike variables, the value of constants cannot be changed once initialized. The main purpose of the use of constants in PostgreSQL are:
It makes the query more readable.
It reduces the maintenance efforts.
Syntax: constant_name CONSTANT data_type := expression;

Let’s analyze the above syntax:
First, specify the constant name. By convention, it is generally in the uppercase form.
Second, put the CONSTANT keyword and specify the data type that the constant is associated with.
Third, initialize a value for the constant.
Example 1:
The following example declares a constant named VAT for valued added tax and calculates the selling price from the net price:
DO $$ 
DECLARE
   VAT CONSTANT NUMERIC := 0.1;
   net_price    NUMERIC := 20.5;
BEGIN 
   RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );
END $$;

Output:
Now let’s attempt to change the constant as below:
DO $$ 
DECLARE
   VAT constant NUMERIC := 0.1;
   net_price    NUMERIC := 20.5;
BEGIN 
   RAISE NOTICE 'The selling price is %', net_price * ( 1 + VAT );
   VAT := 0.05;
END $$;

As expected it raises an error as shown below:
Example 2:
It is important to note that PostgreSQL evaluates the value for the constant when the block is entered at run-time, not compile-time as shown in the below example:
DO $$ 
DECLARE
   start_at CONSTANT time := now();
BEGIN 
   RAISE NOTICE 'Start executing block at %', start_at;
END $$;

Output:
PostgreSQL evaluates the NOW( ) function every time we call the block. To prove it, we execute the block again:
And got a different result.
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - REPLACE Function
PostgreSQL - INSERT
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - ROW_NUMBER Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - EXISTS Operator
PostgreSQL - LEFT JOIN
PostgreSQL - SELECT
Why the error Collection was modified; enumeration operation may not execute occurs and how to handle it in C#?

This error occurs when a looping process is being running on a collection (Ex: List) and the collection is modified (data added or removed) during the runtime.
 Live Demo
using System;
using System.Collections.Generic;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         try {
            var studentsList = new List<Student> {
               new Student {
                  Id = 1,
                  Name = "John"
               },
               new Student {
                  Id = 0,
                  Name = "Jack"
               },
               new Student {
                  Id = 2,
                  Name = "Jack"
               }
            };
            foreach (var student in studentsList) {
               if (student.Id <= 0) {
                  studentsList.Remove(student);
               }
               else {
                  Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
               }
            }
         }
         catch(Exception ex) {
            Console.WriteLine($"Exception: {ex.Message}");
            Console.ReadLine();
         }
      }
   }
   public class Student {
      public int Id { get; set; }
      public string Name { get; set; }
   }
}
The output of the above code is
Id: 1, Name: John
Exception: Collection was modified; enumeration operation may not execute.
In the above example, the foreach loop is executed on the studentsList. When the Id of the student is 0, the item will be removed from the studentsList. Because of this change the studentsList gets modified (resized) and an exception is being thrown during the runtime.
To overcome the above issue, perform a ToList() operation on the studentsList before the start of each iteration.
foreach (var student in studentsList.ToList())
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         var studentsList = new List<Student> {
            new Student {
               Id = 1,
               Name = "John"
            },
            new Student {
               Id = 0,
               Name = "Jack"
            },
            new Student {
               Id = 2,
               Name = "Jack"
            }
         };
         foreach (var student in studentsList.ToList()) {
            if (student.Id <= 0) {
               studentsList.Remove(student);
            }
            else {
               Console.WriteLine($"Id: {student.Id}, Name: {student.Name}");
            }
         }
         Console.ReadLine();
      }
   }
   public class Student {
      public int Id { get; set; }
      public string Name { get; set; }
   }
}
The output of the above code is
Id: 1, Name: John
Id: 2, Name: Jack
PostgreSQL – EXCEPT Operator

28 Aug, 2020
In PostgreSQL, the EXCEPT operator is used to return distinct rows from the first (left) query that are not in the output of the second (right) query while comparing result sets of two or more queries.
Syntax:
SELECT column_list
FROM A
WHERE condition_a
EXCEPT 
SELECT column_list
FROM B
WHERE condition_b;
The below rules must be obeyed while using the EXCEPT operator:
The number of columns and their orders must be the same in the two queries.
The data types of the respective columns must be compatible.
The below Venn diagram illustrates the result of EXCEPT operator:
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.Example 1:Here we will query for films that are not in the inventory using EXCEPT operator from data of the “film” and “inventory” tables of our sample database and sort them using ORDER BY clause based on the film title.
SELECT
    film_id,
    title
FROM
    film
EXCEPT
    SELECT
        DISTINCT inventory.film_id,
        title
    FROM
        inventory
    INNER JOIN film ON film.film_id = inventory.film_id
ORDER BY title;
Output:
Example 2:Here we will query for films that are only in the English Language (ie, language_id = 1) using EXCEPT operator from data of the “film” and “language” tables of our sample database and sort them using the ORDER BY clause based on the film title.
SELECT
    language_id,
    title
FROM
    film
WHERE
        language_id = 1
EXCEPT
    SELECT
        DISTINCT language.language_id,
        name
    FROM
        language
    INNER JOIN film ON film.language_id = language.language_id
ORDER BY title;;
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect multiple MySQL databases on a single webpage ?

15 Jul, 2021
This article explains how to connect multiple MySQL databases into a single webpage. It is useful to access data from multiple databases. 
There are two methods to connect multiple MySQL databases into a single webpage which are: 
Using MySQLi (Improved version of MySQL)
Using PDO (PHP Data Objects)
Syntax:  
MySQLi Procedural syntax:
$link = mysqli_connect( “host_name”, “user_name”, “password”, “database_name” );
MySQLi Object Oriented syntax:
$link = new mysqli( “host_name”, “user_name”, “password”, “database_name” );
PDO (PHP Data Objects) syntax:
$pdo = new PDO( “mysql:host=host_name; dbname=database_name”, “user_name”, “password” );
Program: This program uses MySQLi to connect multiple databases on a single webpage.  
PHP
<?php// PHP program to connect multiple MySQL database// into single webpage // Connection of first database// Database name => database1// Default username of localhost => root// Default password of localhost is '' (none)$link1 = mysqli_connect("localhost", "root", "", "database1"); // Check for connectionif($link1 == true) {    echo "database1 Connected Successfully";}else {    die("ERROR: Could not connect " . mysqli_connect_error());} echo "<br>"; // Connection of first database// Database name => database1$link2 = mysqli_connect("localhost", "root", "", "database2"); // Check for connectionif($link2 == true) {    echo "database2 Connected Successfully";}else {    die("ERROR: Could not connect " . mysqli_connect_error());} echo "<br><br>Display the list of all Databases:<br>"; // Connection of databases$link = mysqli_connect('localhost', 'root', ''); // Display the list of all database name$res = mysqli_query($link, "SHOW DATABASES"); while( $row = mysqli_fetch_assoc($res) ) {    echo $row['Database'] . "<br>";} ?>
Output: 
 
sweetyty
mysql
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Math.Sin() Method

31 Jan, 2019
Math.Sin() is an inbuilt Math class method which returns the sine of a given double value argument(specified angle).
Syntax:
public static double Sin(double num)
Parameter:
num: It is the angle(measured in radian) whose sine is to be returned and the type of this parameter is System.Double.
Return Value: Returns the sine of num of type System.Double. If num is equal to NegativeInfinity, PositiveInfinity, or NaN, then this method returns NaN.
Below are the programs to illustrate the Math.Sin() method.
Program 1: To show the working of Math.Sin() method.
// C# program to demonstrate working// Math.Sin() methodusing System;   class Geeks {       // Main Method    public static void Main(String []args)    {        double a = 30;                   // converting value to radians        double b = (a * (Math.PI)) / 180;           // using method and displaying result        Console.WriteLine(Math.Sin(b));        a = 45;                   // converting value to radians        b = (a * (Math.PI)) / 180;           // using method and displaying result        Console.WriteLine(Math.Sin(b));        a = 60;                   // converting value to radians        b = (a * (Math.PI)) / 180;          // using method and displaying result        Console.WriteLine(Math.Sin(b));        a = 90;                   // converting value to radians        b = (a * (Math.PI)) / 180;           // using method and displaying result        Console.WriteLine(Math.Sin(b));    }}
0.5
0.707106781186547
0.866025403784439
1

 
Program 2: To show the working of Math.Sin() method when the argument is NaN or infinity.
// C# program to demonstrate working// Math.Sin() method in infinity caseusing System;  class Geeks {          // Main Method    public static void Main(String []args)    {          double positiveInfinity = Double.PositiveInfinity;                         double negativeInfinity = Double.NegativeInfinity;                                          double nan = Double.NaN;        double result;          // Here argument is negative infinity,        // output will be NaN         result = Math.Sin(negativeInfinity);         Console.WriteLine(result);          // Here argument is positive infinity,        // output will also be NaN        result = Math.Sin(positiveInfinity);        Console.WriteLine(result);          // Here argument is NaN, output will be NaN        result = Math.Sin(nan);        Console.WriteLine(result);    }}
NaN
NaN
NaN

CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
How to set “value” to input web element using selenium?

We can set value to input webelement using Selenium webdriver. We can take the help of the sendKeys method to enter text to the input field. The value to be entered is passed as an argument to the method.
driver.findElement(By.id("txtSearchText")).sendKeys("Selenium");
We can also perform web operations like entering text to the edit box with Javascript Executor in Selenium. We shall use the executeScript method and pass argument index.value='<value to be entered>' and webelement as arguments to the method.
WebElement i = driver.findElement(By.id("id"));
JavascriptExecutor j = (JavascriptExecutor)driver;
j.executeScript("arguments[0].value='Selenium';", i);
Code Implementation
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
public class SetValue{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
      l.sendKeys("Selenium");
      // obtain the value entered with getAttribute method
      System.out.println("Value entered is: " +l.getAttribute("value"));
      driver.close();
   }
}
Code Implementation with Javascript Executor.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetValueJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement l=driver.findElement(By.cssSelector("input[id*='id']"));
      // Javascript Executor class with executeScript method
      JavascriptExecutor j = (JavascriptExecutor)driver;
      j.executeScript("arguments[0].value='Selenium';", l);
      System.out.println("Value entered is: " +l.getAttribute("value"));
      driver.close();
   }
}
How to find an element using the attribute “id” in Selenium?

We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@id='value']. Then, we have to use the method By.xpath to locate it. To locate an element with locator id, we have to use the By.id method.
Let us look at the html code of an element with id attribute −
WebElement e = driver. findElement(By.id("session_key"));
WebElement m = driver. findElement(By.xpath("//input[@id=' session_key']"));
WebElement n =
driver. findElement(By.cssSelector("input[id=' session_key']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorId{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.linkedin.com/");
      // identify element with Id
      WebElement l = driver.findElement(By.id("session_key"));
      l.sendKeys("Java");
      //identify element with css
      WebElement m = driver.
      findElement(By.cssSelector("input[id='session_key']"));
      String s = m.getAttribute("value");
      System.out.println("Attribute value: " + s);
      //identify element with xpath
      WebElement n = driver.
      findElement(By.xpath("//input[@id='session_key']"));
      n.clear();
      driver.quit();
   }
}
How to create a borderless fullscreen application using Python-3 Tkinter?

In order to make a Tkinter window borderless and full-screen, we can use the utility method attributes(‘-fullscreen’, True). Tkinter windows can be configured using functions and methods defined in the Tkinter library.
Another similar method Tkinter provides to make the application window full-screen is, overrideredirect(True). This method can be invoked only if the application needs to resize in its defined width and height only.
#Import the required Libraries
from tkinter import *
#Create an instance of Tkinter frame
win= Tk()
#Set the Geometry
win.geometry("750x250")
#Full Screen Window
win.attributes('-fullscreen', True)
def quit_win():
   win.destroy()
#Create a Quit Button
button=Button(win,text="Quit", font=('Comic Sans', 13, 'bold'), command= quit_win)
button.pack(pady=20)
win.mainloop()
Running the above code will display a full-screen window.
Click the "Quit" button to close the full-screen window.
D3.js axis.tickFormat() Function - GeeksforGeeks

05 Aug, 2020
The d3.axis.tickFormat() Function in D3.js is used to control which ticks are labelled. This function is used to implement your own tick format function.
Syntax:
axis.tickFormat([format])
Parameters: This function accepts the following parameter.
format: These parameters are format to set the tick format function.
Return Value: This function returns the currently set tick format function, which defaults to null.
Below programs illustrate the d3.axis.tickFormat() function in D3.js:
Example 1:
<!DOCTYPE html> <html>   <head>     <title>         D3.js | D3.axis.tickFormat() Function     </title>     <script type="text/javascript"        src="https://d3js.org/d3.v4.min.js">     </script>           <style>         svg text {             fill: green;             font: 15px sans-serif;             text-anchor: center;         }     </style> </head>   <body>     <script>         var width = 400, height = 400;         var svg = d3.select("body")             .append("svg")             .attr("width", width)             .attr("height", height);           var yscale = d3.scaleLinear()             .domain([0, 1])             .range([height - 50, 0]);           var y_axis = d3.axisLeft().scale(yscale)        .tickValues([0, .2, .5, .70, 1])        .tickFormat((d, i) => ['a', 'e', 'i', 'o', 'u'][i]);             svg.append("g")             .attr("transform", "translate(100, 20)")             .call(y_axis)     </script></body> </html>
Output:
Example 2:
<!DOCTYPE html> <html>   <head>     <title>         D3.js | D3.axis.tickFormat() Function     </title>     <script type="text/javascript"        src="https://d3js.org/d3.v4.min.js">     </script>           <style>         svg text {             fill: green;             font: 15px sans-serif;             text-anchor: center;         }     </style> </head>   <body>     <script>         var width = 600, height = 400;         var svg = d3.select("body")             .append("svg")             .attr("width", width)             .attr("height", height);           var xscale = d3.scaleLinear()             .domain([0, 10])             .range([0, width - 100]);           var x_axis = d3.axisBottom(xscale).ticks(4)        .tickFormat(x => `(${x.toFixed(1)})`);           var xAxisTranslate = height / 2;           svg.append("g")             .attr("transform", "translate(50, "             + xAxisTranslate + ")")             .call(x_axis)     </script> </body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript