code-rag-bench/online-tutorials huggingface dataset:
Functors in C++

The functors are the function objects in C++. The functor allows an instance object of some class to be called as if it were an ordinary function. Let us consider a function that takes one argument. We can use this function as function object to do some task on a set of data.
 Live Demo
#include <iostream>
#include <algorithm>
using namespace std;
int square(int x) {
   return x*x; //return square of x
}
int main() {
   int data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
   transform(data, data+10, data, square);
   for (int i = 0; i<10; i++)
      cout << data[i] << endl;
}
0
1
4
9
16
25
36
49
64
81
Execution of printf With ++ Operators in C - GeeksforGeeks

25 Nov, 2021
Consider the following statement in C and predict its output.
printf("%d %d %d", i, ++i, i++);
This statement invokes undefined behavior by referencing both ‘i’ and ‘i++’ in the argument list. It is not defined in which order the arguments are evaluated. Different compilers may choose different orders. A single compiler can also choose different orders at different times.
For example, below three printf() statements may also cause undefined behavior:
C
// C Program to demonstrate the three printf() statements// that cause undefined behavior#include <stdio.h>  // Driver Codeint main(){    volatile int a = 10;    printf("%d %d\n", a, a++);      a = 10;    printf("%d %d\n", a++, a);      a = 10;    printf("%d %d %d\n", a, a++, ++a);    return 0;}
11 10
10 10
12 11 11
Explanation: Usually, the compilers read parameters of printf() from right to left. So, ‘a++’  will be executed first as it is the last parameter of the first printf() statement. It will print 10. Although, now the value has been increased by 1, so the second last argument, i.e., will print 11. Similarly, the other statements will also get executed.
Note: In pre-increment, i.e., ++a, it will increase the value by 1 before printing, and in post-increment, i.e., a++, it prints the value at first, and then the value is incremented by 1.
Therefore, it is not recommended not to do two or more than two pre or post-increment operators in the same statement. This means that there’s absolutely no temporal ordering in this process. The arguments can be evaluated in any order, and the process of their evaluation can be intertwined in any way.
This article is contributed by Spoorthi Aman. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ArunSivaramakrishnanS
chhabradhanvi
anshikajain26
C-Operators
cpp-input-output
cpp-operator
C Language
C++
cpp-operator
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
How to create dot plots in Python | by Przemysław Jarząbek | Towards Data Science

Recently I looked at my IMDb account. Whoa, there is over 1100 rated titles! I decided to create a plot of movies I’ve seen every year and their ratings. Dot plot is a great way to visualize it, I always liked the plots like these created with ggplot2:
All right, it shouldn’t be a hard task in Python. I just need to get a .csv file with my ratings, write few lines of code using Matplotlib/Seaborn and voila! Quickly I realized that Matplotlib doesn’t support dot plots. Neither do Seaborn. I quickly checked MS Excel — also no dot plots!
After few minutes of googling I found one solution. However, creating a histogram of values and then mapping them on a scatterplot doesn’t solve the problem of different marker colors for ratings.
I liked the idea of tweaking standard scatterplot, so I decided to go that way. Instead of creating a grid of points I used a simple loop to add new variable responsible for movie count per year.
First, we create an empty array `movie_count`, which will store a vertical position on the chart for every movie. Then we loop over the year column using the `enumerate` function. For every movie we create a subset starting from first index until this exact movie. Now we count all movies in this subset and append the result to `movie_count`.
# Loop to create a new variable, which will turn scatterplot to a dot plotmovie_count = []for index, year in enumerate(ratings['Year']):    subset = ratings.iloc[:index + 1]  # Create subset starting at the beginning of dataset until the movie itself    count = len(subset[subset['Year'] == year])  # Count all movies from the same year in this subset    movie_count.append(count)  # Appended counts will be used as vertical values in the scatterplot,    # which will help to create a dot plot
For example, if we are looking at 20th movie in the dataset and it was released in 2018, we create a subset of the 20 movies and count all movies from 2018. Let’s say there are three of them, so we append that number to movie_count array on 20th position. If the next movie is also from 2018, it gets a count of 4 and so on. Every single movie in our dataset gets a unique pair of coordinates — release year and count.
This way we can create a scatterplot which will in fact be the dot plot. Now we just add hue as a parameter to get different colors for ratings and it should be working.
The basic idea works, but now we need to fix some issues:
1. The movies should be sorted by rating for better readability.
2. The dots need to be bigger.
3. Background color should be added for better contrast.
4. The legend is just bad. You cannot rate movie 0 or 12 on 1–10 scale. Also, for this kind of data smooth (or discrete, your choice) colormap would be better. There is a great post about creating colormaps over here.
After fixing these problems you can get a nice chart:
If you are interested in the full code used to create this dot plot, check my GitHub repository. Feel free to comment or report any improvements in the code, as I just use Python for data science tasks and I’m not an expert in optimization.
How to allow a MySQL user account to connect from any host?

It is quite possible to allow a user account to connect from any host. To do so we need to create the user with the help of ‘%’ wild card character after @ character. Its syntax would be as follows −
Use mysql;
CREATE USER user_name@’%’ IDENTIFIED BY password;
Here 
user_name is the name of the user we wish to make an account for.
Password is the password we wish to make for user_account. With the help of this password, MySQL server will identify this user.
In the given example we are creating a user ‘Gaurav’ by using ‘%’ character so that it can be connected to any host.
mysql> use mysql
Database changed

mysql> CREATE USER Gaurav@'%' IDENTIFIED BY 'password123';
Query OK, 0 rows affected (0.00 sec)
The query below will give us the privileges for the new user account Gaurav@’%’.
mysql> SHOW GRANTS FOR Gaurav@'%';
+------------------------------------+
| Grants for Gaurav@%                |
+------------------------------------+
| GRANT USAGE ON *.* TO 'Gaurav'@'%' |
+------------------------------------+
1 row in set (0.00 sec)
Writing a binary file in C++

To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. The file is extended if the put pointer is current at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data.
If any error has occurred during writing in the file, the stream is placed in an error state.
ostream& write(const char*, int);
Begin
   Create a structure Student to declare variables.
   Open binary file to write.
   Check if any error occurs in file opening.
   Initialize the variables with data.
   If file opens successfully, write the binary data using write method.
      Close the file for writing.
   Check if any error occurs.
   Print the data.
End.
Here is a sample example
 Live Demo
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
   int roll_no;
   string name;
};
int main() {
   ofstream wf("student.dat", ios::out | ios::binary);
   if(!wf) {
      cout << "Cannot open file!" << endl;
      return 1;
   }
   Student wstu[3];
   wstu[0].roll_no = 1;
   wstu[0].name = "Ram";
   wstu[1].roll_no = 2;
   wstu[1].name = "Shyam";
   wstu[2].roll_no = 3;
   wstu[2].name = "Madhu";
   for(int i = 0; i < 3; i++)
      wf.write((char *) &wstu[i], sizeof(Student));
   wf.close();
   if(!wf.good()) {
      cout << "Error occurred at writing time!" << endl;
      return 1;
   }
   cout<<"Student's Details:"<<endl;
   for(int i=0; i < 3; i++) {
      cout << "Roll No: " << wstu[i].roll_no << endl;
      cout << "Name: " << wstu[i].name << endl;
      cout << endl;
   }
   return 0;
}
Student’s Details:
Roll No: 1
Name: Ram
Roll No: 2
Name: Shyam
Roll No: 3
Name: Madhu
Difference between for loop in C and Python - GeeksforGeeks

31 May, 2021
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance.  However, there is a difference in working of c and python for loop, though both are used for iterations the working is different.
For loop in C starts from the initialized value, and then it is checked for condition. If the test expression turns out to be true the code under for is executed, and it is done without any abnormality the update expression equation increments or decrements the variable accordingly. 
Syntax:
for (initialization expr; test expr; update expr)
{    
    // body of the loop
    // statements we want to execute
}
Example 1:
for(int i=1;i<=10;i++)
{
  printf(“%d “,i);
}
OUTPUT
1 2 3 4 5 6 7 8 9 10
It stops executing the body of for loop whenever i becomes greater than 10.
Example 2:
for(int i=1;i<=10;i++)
{
i=i+1
printf(“%d “,i);
}
OUTPUT:
2 4 6 10
//because each time i is getting incremented by 1 in for body and whenever i>10 it stops the execution.
Program
C
//Program to show working of for loop in C #include <stdio.h> int main(){     // code    for (int i = 1; i <= 10; i++)    {      // it will have effect on termination      // condition      i=i+1;      printf("%d\n", i);    }    return 0;}
Output:
2
4
6
8
10
For loops in python works on the range given to it. The variable name given along with its declaration is changes its values starting from the initial value then being increment or decremented accordingly. The loop works for one less than the ending value.
Syntax
for val in range(x,y,z)
Where, 
x= initial value
y=final value
z=increment/ decrement
Example 1:
for i in range(1,11):
  print(i)
OUTPUT:
1 2 3 4 5 6 7 8 9 10
//as we can see it is iterating for 10 times ie(11-1)=10 times
Example 2:
for i in range(1,11):
   i=1+1;
   print(i)
OUTPUT:
2 3 4 5 6 7 8 9 10 11
//though we are incrementing i inside the for body still it is iterating  for 10 times.
Program
Python3
# program to show for loop in python for i in range(1, 11):       # it will have no effect in termination    # condition    i = i+1         # it will always iterate for 10 times as    # given in range    print(i)
Output
2
3
4
5
6
7
8
9
10
11
Difference between c and python for loop
simranarora5sos
C Language
Difference Between
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between var, let and const keywords in JavaScript
Difference Between == and .equals() Method in Java
What is void pointer in C language?

It is a pointer that can hold the address of any datatype variable (or) can point to any datatype variable.
The declaration for void pointer is as follows −
void *pointername;
For example − void *vp;
Accessing − Type cast operator is used for accessing the value of a variable through its pointer.
The syntax for void pointer is given below −
* ( (type cast) void pointer)
int i=10;
void *vp;
vp = &i;
printf ("%d", * ((int*) vp));
// int * type cast
Following is the C program for void pointer −
 Live Demo
#include<stdio.h>
main ( ){
   int i =10;
   float f = 5.34;
   void *vp;
   vp = &i;
   printf ("i = %d", * ((int*)vp));
   vp = &f;
   printf ( "f = %f", * ((float*) vp));
}
When the above program is executed, it produces the following result −
i = 10
f = 5.34
Given below is the C program for pointer arithmetic in void pointers −
 Live Demo
#include<stdio.h>
#define MAX 20
int main(){
   int array[5] = {12, 19, 25, 34, 46}, i;
   void *vp = array;
   for(i = 0; i < 5; i++){
      printf("array[%d] = %d\n", i, *( (int *)vp + i ) );
   }
   return 0;
}
When the above program is executed, it produces the following result −
array[0] = 12
array[1] = 19
array[2] = 25
array[3] = 34
array[4] = 46
Perl for Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in Perl programming language is −
for ( init; condition; increment ) {
   statement(s);
}

Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
#!/usr/local/bin/perl
 
# for loop execution
for( $a = 10; $a < 20; $a = $a + 1 ) {
   print "value of a: $a\n";
}
When the above code is 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: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
static_cast in C++

The static_cast is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coercion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. This can cast related type classes.
#include <iostream>
using namespace std;
int main() {
   float x = 4.26;
   int y = x; // C like cast
   int z = static_cast<int>(x);
   cout >> "Value after casting: " >> z;
}
Value after casting: 4
If the types are not same it will generate some error.
#include<iostream>
using namespace std;
class Base {};
class Derived : public Base {};
class MyClass {};
main(){
   Derived* d = new Derived;
   Base* b = static_cast<Base*>(d); // this line will work properly
   MyClass* x = static_cast<MyClass*>(d); // ERROR will be generated during
   compilation
}
[Error] invalid static_cast from type 'Derived*' to type 'MyClass*'
Get a dictionary from an Objects Fields

28 Jul, 2020
In this article, we will discuss how to get a dictionary from object’s field i.e. how to get the class members in the form of a dictionary. There are two approaches to solve the above problem:  
By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.By calling the in-built vars method, which is used to return __dict__ attribute of a module, class, class instance, or an object.
By using the __dict__ attribute on an object of a class and attaining the dictionary. All objects in Python have an attribute __dict__, which is a dictionary object containing all attributes defined for that object itself. The mapping of attributes with its values is done to generate a dictionary.
By calling the in-built vars method, which is used to return __dict__ attribute of a module, class, class instance, or an object.
#Method 1: To generate a dictionary from an arbitrary object using  __dict__attribute:
Python3
# class Animals is declaredclass Animals:          # constructor    def __init__(self):                  # keys are initialized with        # their respective values        self.lion = 'carnivore'        self.dog = 'omnivore'        self.giraffe = 'herbivore'      def printit(self):        print("Dictionary from the object fields\        belonging to the class Animals:")    # object animal of class Animalsanimal = Animals()  # calling printit methodanimal.printit()# calling attribute __dict__ on animal# object and printing itprint(animal.__dict__)
Output:
Dictionary from the object fields belonging to the class Animals:{‘lion’: ‘carnivore’, ‘dog’: ‘omnivore’, ‘giraffe’: ‘herbivore’}
#Method 2: To generate a dictionary from an arbitrary object using an in-built vars method:
Python3
# class A is declaredclass A:          # constructor    def __init__(self):                  # keys are initialized with         # their respective values        self.A = 1        self.B = 2        self.C = 3        self.D = 4  # object obj of class Aobj = A()  # calling vars method on obj objectprint(vars(obj))
Output:
{'A': 1, 'B': 2, 'C': 3, 'D': 4}

python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Matplotlib - Three-dimensional Plotting

Even though Matplotlib was initially designed with only two-dimensional plotting in mind, some three-dimensional plotting utilities were built on top of Matplotlib's two-dimensional display in later versions, to provide a set of tools for three-dimensional data visualization. Three-dimensional plots are enabled by importing the mplot3d toolkit, included with the Matplotlib package.
A three-dimensional axes can be created by passing the keyword projection='3d' to any of the normal axes creation routines.
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)
ax.plot3D(x, y, z, 'gray')
ax.set_title('3D line plot')
plt.show()
We can now plot a variety of three-dimensional plot types. The most basic three-dimensional plot is a 3D line plot created from sets of (x, y, z) triples. This can be created using the ax.plot3D function.
3D scatter plot is generated by using the ax.scatter3D function.
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
z = np.linspace(0, 1, 100)
x = z * np.sin(20 * z)
y = z * np.cos(20 * z)
c = x + y
ax.scatter(x, y, z, c=c)
ax.set_title('3d Scatter plot')
Designing Finite Automata from Regular Expression (Set 6)

20 Nov, 2019
Prerequisite: Finite automata, Regular expressions, grammar and language, Designing finite automata from Regular expression (Set 5)
In the below article, we shall see some Designing of Finite Automata form the given Regular Expression-
Regular Expression 1: Regular language,
L1 = a(a+b)* 
The language of the given RE is,
{aaa, aba, baa, bba} 
Strings always start with ‘a’.Its finite automata will be like below-In the above transition diagram, as we can see that initial state ‘Y’ on getting ‘a’ as the input it transits to afinal state ‘Z’ and so on for the remaining states. Thus this FA accepting all the strings of the given RE language.
Regular Expression 2: Regular language,
L2 = (a+b)*a 
The language of the given RE is,
{aaa, aba, baa, bba} 
Strings always end with ‘a’.Its finite automata will be like below-In the above transition diagram, as we can see that initial state ‘Y’ on getting ‘a’ as the input it transits to a final state ‘Z’ and on getting ‘b’ as the input it remains in the state of itself and so on for the remaining states. Thus this FA accepting all the strings of the given RE language.
Regular Expression 3: Regular language,
L3 = (a+b)*a(a+b)* 
The language of the given RE is,
{aaa, aba, baa, bba} 
Strings containing ‘a’ as the alphabet.Its finite automata will be like below-In the above transition diagram, as we can see that initial state ‘Y’ on getting ‘b’ as the input it remains in the state of itself and on getting ‘a’ as the input it transits to a final state ‘Z’ and so on for the remaining states. Thus this FA accepting all the strings of the given RE language.
Regular Expression 4: Regular language,
L4 = (a(a+b)*b)+(b(a+b)*a) 
The language of the given RE is,
{aab, abb, baa, bba} 
Strings start and end with different symbols.Its finite automata will be like below-In the above transition diagram, as we can see that initial state ‘V’ on getting ‘a’ as the input it transits to a state ‘W’ and so on for the remaining states. Thus this FA accepting all the strings of the given RE language.
Regular Expression 5: Regular language,
L5 = (a(a+b)*a)+(b(a+b)*b)+a+b+ε 
The language of the given RE is,
{&epsilon, a, b, aba, bab, bbab} 
Strings start and end with same symbols.Its finite automata will be like below-In the above transition diagram, as we can see that initial and final state ‘V’ on getting ‘a’ as the input it transits to another final state ‘W’ and so on for the remaining states. Thus this FA accepting all the strings of the given RE language.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
Differences between TCP and UDP
Introduction of Operating System - Set 1
Cache Memory in Computer Organization
Difference between DFA and NFA
Turing Machine in TOC
Boyer-Moore Majority Voting Algorithm
Introduction of Pushdown Automata
Difference between Mealy machine and Moore machine
Find the number of weekdays of a given month using NumPy - GeeksforGeeks

26 Nov, 2020
In NumPy we can find the number of weekdays in a given month with the help of busday_count() In this pass the given month is the first parameter and next month as the second parameter. It will return the total number of weekdays in a given month.
Syntax:
numpy.busday_count(begindates, enddates, weekmask)
Parameters:
begindates: The array of the first dates for counting.
enddates: The array of the end dates for counting, which are excluded from the count themselves.
weekmask: Select the days
Weekdays are from Monday to Friday only.
Example #1:
Python3
import numpy as np  # Number of weekdays in july 2020print("Number of weekdays in july 2020:",      np.busday_count('2020-07', '2020-08'))
Output:
Number of weekdays in july 2020: 23

Example #2: We can count the number of Sat with this weekmask.
Python3
import numpy as np  # Number of weekdays in August 2020print("Number of saturday in november 2020:",      np.busday_count('2020-11', '2020-12',                      weekmask='Sat'))
Output:
Number of saturday in november 2020: 4

 Example #3: Count the number of Sunday.
Python3
import numpy as np  # Number of weekdays in August 2020print("Number of Sunday in november 2020:",      np.busday_count('2020-11', '2020-12',                      weekmask='Sun'))
Output:
Number of Sunday in november 2020: 5

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

We have already seen the configuration used to draw this chart in Highcharts Configuration Syntax chapter. Let us now consider the following example to further understand a basic line chart.
app.component.ts
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   highcharts = Highcharts;
   chartOptions = {   
      chart: {
         type: "spline"
      },
      title: {
         text: "Monthly Average Temperature"
      },
      subtitle: {
         text: "Source: WorldClimate.com"
      },
      xAxis:{
         categories:["Jan", "Feb", "Mar", "Apr", "May", "Jun",
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
      },
      yAxis: {          
         title:{
            text:"Temperature °C"
         } 
      },
      tooltip: {
         valueSuffix:" °C"
      },
      series: [{
         name: 'Tokyo',
         data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,26.5, 23.3, 18.3, 13.9, 9.6]
      },
      {
         name: 'New York',
         data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8,24.1, 20.1, 14.1, 8.6, 2.5]
      },
      {
         name: 'Berlin',
         data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
      },
      {
         name: 'London',
         data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
      }]
   };
}
Verify the result.

    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
JavaScript | fetch() Method - GeeksforGeeks

18 Jun, 2020
The fetch() method in JavaScript is used to request to the server and load the information in the webpages. The request can be of any APIs that returns the data of the format JSON or XML. This method returns a promise.
Syntax:
fetch( url, options )

Parameters: This method accept two parameters as mentioned above and described below:
URL: It is the URL to which the request is to be made.
Options: It is an array of properties. It is an optional parameter.
Return Value: It returns a promises whether it is resolved or not. The return data can be of the format JSON or XML.It can be the array of objects or simply a single object.
Example 1:
NOTE: Without options Fetch will always act as a get request.
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=    "width=device-width, initial-scale=1.0">      <title>JavaScript | fetch() Method</title></head>  <body>    <script>          // API for get requests        let fetchRes = fetch("https://jsonplaceholder.typicode.com/todos/1");          // fetchRes is the promise to resolve        // it by using.then() method        fetchRes.then(res =>            res.json()).then(d => {                console.log(d)            })    </script></body>  </html>
Output:
Making Post Request using Fetch: Post requests can be made using fetch by giving options as given below:
let options = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(data)
}

Example:2
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <title>JavaScript | fetch() Method</title></head>  <body>    <script>        user = {             "name": "Geeks for Geeks",             "age": "23"         }                  // Options to be given as parameter         // in fetch for making requests        // other then GET        let options = {            method: 'POST',            headers: {                'Content-Type':                     'application/json;charset=utf-8'            },            body: JSON.stringify(user)        }          // Fake api for making post requests        let fetchRes = fetch("http://dummy.restapiexample.com/api/v1/create",                                         options);        fetchRes.then(res =>            res.json()).then(d => {                console.log(d)            })    </script></body>  </html>
Output:
javascript-functions
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
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
VBScript UCase Function

The UCase Function returns the string after converting the entered string into UPPER case letters.
UCase(String)

<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "Microsoft VBScript"
         document.write("Line 1 : " & UCase(var) & "<br />")
         
         var = "MS VBSCRIPT"
         document.write("Line 2 : " & UCase(var) & "<br />")
         
         var = "microsoft"
         document.write("Line 3 : " & UCase(var) & "<br />")
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : MICROSOFT VBSCRIPT
Line 2 : MS VBSCRIPT
Line 3 : MICROSOFT


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
AbstractCollection add() Method in Java with Examples - GeeksforGeeks

26 Nov, 2018
The add() method in Java AbstractCollection is used to add a specific element into a Collection. This method will add the element only if the specified element is not present in the Collection else the function will return False if the element is already present in the Collection.
Syntax:
AbstractCollection.add(Object element)
Parameters: The parameter element is of the object type and refers to the element to be added to the Collection.
Return Value: The function returns True if the element is not present in the Collection otherwise False if the element is already present in the Collection.
Below programs illustrate the AbstractCollection.add() method:
Program 1: Adding String elements into the Collection of ArrayList.
// Java code to illustrate add(Object o)  import java.util.*;import java.util.AbstractCollection;  public class AbstractCollectionDemo {    public static void main(String[] args)    {          // Create an empty collection        AbstractCollection<Object>            abs = new ArrayList<Object>();          // Use add() method to add        // elements in the collection        abs.add("Welcome");        abs.add("To");        abs.add("Geeks");        abs.add("4");        abs.add("Geeks");          // Displaying the Collection        System.out.println("AbstractCollection: "                           + abs);    }}
AbstractCollection: [Welcome, To, Geeks, 4, Geeks]

Program 2: Adding Integer elements into the Collection of LinkedList.
// Java code to illustrate add(Object o)  import java.util.*;import java.util.AbstractCollection;  public class AbstractCollectionDemo {    public static void main(String[] args)    {          // Create an empty collection        AbstractCollection<Object>            abs = new LinkedList<Object>();          // Use add() method to add        // elements in the collection        abs.add(15);        abs.add(20);        abs.add(25);        abs.add(30);        abs.add(35);          // Displaying the Collection        System.out.println("AbstractCollection: "                           + abs);    }}
AbstractCollection: [15, 20, 25, 30, 35]

Java - util package
Java-AbstractCollection
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
Set Window Icon Text in PyQt5 | setWindowIconText() method

16 Aug, 2021
PyQt5 allows us to set the icon of window using setWindowIcon() method, on the other hand setWindowIconText() method is also present in it which allows us to set the text the icon. 
Although, it is not recommended to use as it has not any use, there was use in previous i.e old versions. It is now used to make the old source codes working. It was used by the window manager now it is not used anymore.
Syntax : self.setWindowIconText(“text”)Argument : It takes string as argument.Return : If no icon is set it will return NULL string else return the text set before.
Code :  
Python3
# importing the required libraries from PyQt5.QtCore import *from PyQt5.QtGui import *from PyQt5.QtWidgets import *import sys  class Window(QMainWindow):      def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Python")                 # setting window icon        self.setWindowIcon(QIcon("logo.png"))                 # setting icon text        self.setWindowIconText("logo")           # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)         # creating a label widget        self.label_1 = QLabel("icon text ", self)        # moving position        self.label_1.move(100, 100)         self.label_1.adjustSize()         # show all the widgets        self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output : 
Note: This method is not recommended to use in codes, as it is of no use for modern systems. 
kalrap615
abhishek0719kadiyan
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <img> border Attribute

21 Jan, 2022
The <img> border attribute is used to specify the border width around the image. The default value of <img> border attribute is 0.It is not supported by HTML 5. Use CSS instead of this attribute.
Syntax:
<img border="pixels">
Attribute Values: It contains single value pixels which specify the width of the border.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML img border Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML img border Attribute</h2>      <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"          alt="GeeksforGeeks logo"          border="5"></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <img> border attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy np.multivariate_normal() method

13 Oct, 2019
With the help of np.multivariate_normal() method, we can get the array of multivariate normal values by using np.multivariate_normal() method.
Syntax : np.multivariate_normal(mean, matrix, size)Return : Return the array of multivariate normal values.
Example #1 :In this example we can see that by using np.multivariate_normal() method, we are able to get the array of multivariate normal values by using this method.
# import numpyimport numpy as np  mean = [1, 2]matrix = [[5, 0], [0, 5]]# using np.multinomial() methodgfg = np.random.multivariate_normal(mean, matrix, 10)  print(gfg)
Output :
[[ 6.24847794 6.57894103][ 1.24114594 3.22013831][ 3.0660329 2.1442572 ][ 0.3239289 2.79949784][-1.42964186 1.11846394][-0.08521476 0.74518872][ 1.42307847 3.27995017][ 3.08412374 0.45869097][ 2.2158498 2.97014443][ 1.77583875 0.57446964]]
Example #2 :
# import numpyimport numpy as np  mean = [0, 0, 0]matrix = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]# using np.multinomial() methodgfg = np.random.multivariate_normal(mean, matrix, 5)  print(gfg)
Output :
[[-2.21792571 -1.04526811 -0.4586839 ][ 0.15760965 0.83934119 -0.52943583][-0.9978205 0.79594411 -0.00937 ][-0.16882821 0.1727549 0.14002367][-1.34406079 1.03498375 0.17620708]]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Introduction To PYTHON
Python Classes and Objects
Python - Pytorch randn() method
Python OOPs Concepts
Node.js fs.rmSync() Method

03 Feb, 2021
The fs.rmSync() method is used to synchronously delete a file at the given path. It can also be used recursively to remove the directory by configuring the options object. It returns undefined.
Syntax:
fs.rmSync( path, options );
Parameters: This method accepts two parameters as mentioned above and described below:
path: It holds the path of the file that has to be removed. It can be a String, Buffer, or URL.
options: It is an object that can be used to specify optional parameters that will affect the operation as follows:force: It is a boolean value. Exceptions will be ignored if the path does not exist.recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
force: It is a boolean value. Exceptions will be ignored if the path does not exist.
recursive: It is a boolean value which specifies if recursive directory removal is performed. In this mode, errors are not reported if the specified path is not found and the operation is retried on failure. The default value is false.
Below examples illustrate the fs.rmSync() method in Node.js:
Example 1: This example uses fs.rmSync() method to delete a file.
Filename: index.js
Javascript
// Import necessary moduleslet fs = require('fs');  // List files before deletinggetCurrentFilenames();  fs.rmSync('./dummy.txt');  // List files after deletinggetCurrentFilenames();  // This will list all files in current directoryfunction getCurrentFilenames() {     console.log("\nCurrent filenames:");     fs.readdirSync(__dirname).forEach(file => {         console.log(file);     });     console.log(""); }
Run the index.js file using the following command:
node index.js
Output:
Current filenames:
dummy.txt
index.js
node_modules
package-lock.json
package.json


Current filenames:
index.js
node_modules
package-lock.json
package.json
Example 2: This example uses fs.rmSync() method with the recursive parameter to delete directories.
Filename: index.js
Javascript
// Import the filesystem module const fs = require('fs');     // List the files in current directory getCurrentFilenames();   // Using the recursive option to delete directory fs.rmSync("./build", { recursive: true });  // List files after delete getCurrentFilenames();     // List all files in current directoryfunction getCurrentFilenames() {   console.log("\nCurrent filenames:");   fs.readdirSync(__dirname).forEach(file => {     console.log(file);   });   console.log("\n"); }
Run the index.js file using the following command:
node index.js
Output:
Current filenames:
build
index.js
node_modules     
package-lock.json
package.json

Current filenames:
index.js
node_modules
package-lock.json
package.json
Reference:https://nodejs.org/api/fs.html#fs_fs_rmsync_path_options
Node.js-fs-module
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | delete() Function

25 Jun, 2019
Delete() in Perl is used to delete the specified keys and their associated values from a hash, or the specified elements in the case of an array. This operation works only on individual elements or slices.
Syntax: delete(LIST)
Parameters:LIST which is to be deleted
Returns:undef if the key does not exist otherwise it returns the value associated with the deleted key
Example 1: Implementing delete() on a Hash
#!/usr/bin/perl  # Initializing hash %hash1 = ('Geeks' => 45, 'for' => 30, 'Now' => 40);   # To delete the List passed as parameter$deleted_element = delete($hash1{'for'});  # Printing elements of Hash print "$hash1{'Geeks'}\n"; print "$hash1{'for'}\n"; print "$hash1{'Now'}\n";   # Printing the deleted elementprint "Deleted element: $deleted_element";
Output:
45

40
Deleted element: 30
Example 2: Implementing delete() on an Array
#!/usr/bin/perl  # Initializing array@array1 = (10, 20, 30, 40, 50, 60);   # To delete the array element at index 2$deleted_element = delete(@array1[2]);  # Printing elements of Array print "Updated Array: @array1";  # Printing the deleted elementprint "\nDeleted element: $deleted_element";
Output:
Updated Array: 10 20  40 50 60
Deleted element: 30
Perl-function
Perl-Hash-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Use of print() and say() in Perl
Perl | Subroutines or Functions
Perl | length() Function
Perl | Boolean Values
Introduction to Perl
Hello World Program in Perl
Initialization of data members

09 Jun, 2017
In C++, class variables are initialized in the same order as they appear in the class declaration.
Consider the below code.
#include<iostream>  using namespace std;  class Test {  private:        int y;    int x;      public:    Test() : x(10), y(x + 10) {}    void print();};  void Test::print(){    cout<<"x = "<<x<<" y = "<<y; }  int main(){    Test t;    t.print();    getchar();    return 0;    }
The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.
So one of the following two versions can be used to avoid the problem in above code.
// First: Change the order of declaration.class Test {  private:        int x;        int y;  public:    Test() : x(10), y(x + 10) {}    void print();};
// Second: Change the order of initialization.class Test {  private:        int y;    int x;      public:    Test() : x(y-10), y(20) {}    void print();};
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Different Methods to Reverse a String in C++
Left Shift and Right Shift Operators in C/C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
How to clear all div’s content inside a parent div ?

23 Jul, 2020
Given an HTML document containing div elements and the task is to remove the existing HTML elements using jQuery. To remove elements and its content, jQuery provides two methods:
remove(): It removes the selected element with its child elements.
empty(): It removes the child element from the selected elements.
Example:
<div id="Parent">
   <div id="child1">child 1</div>
   <div id="child2">child 2</div>
   <div id="child3">child 3</div>
</div>
Syntax: The following function clears the parent “div”
$('#parent').empty();
The following function clears all the child “divs”, but leaves the parent intact.
$('#parent div').empty()
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script></head>  <body>    <div id="parent">        Parent div        <div id="child1">Child 1</div>        <div id="child2">Child 2</div>        <div id="child3">Child 3</div>    </div>          <button onclick=myFunc()>Click me</button>      <Script>        function myFunc() {            $('#parent div').empty()        }    </Script></body>  </html>
Output:
Before clicking the button:
After clicking the button:
CSS-Misc
HTML-Misc
JavaScript-Misc
jQuery-Misc
Picked
CSS
HTML
JavaScript
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type