code-rag-bench/online-tutorials huggingface dataset:
watch command in Linux with Examples

27 May, 2019
watch command in Linux is used to execute a program periodically, showing output in fullscreen. This command will run the specified command in the argument repeatedly by showing its output and errors. By default, the specified command will run every 2 seconds and watch will run until interrupted.
Syntax:
watch [options] command

Options:
-d, –differences: This option highlights the differences between successive updates. The options will be going to read the optional argument which changes highlight to be permanent, allowing the user to see what has changed at least once since the first iteration.Example:watch -d  free -m
Example:
watch -d  free -m
-n, –interval seconds: This option will specify update interval. The command will not be going to allow quicker than the 0.1-second interval, in which the smaller values are getting converted.Example:watch -n 1 free -m
Example:
watch -n 1 free -m
-p, –precise: This option make watch attempt to run command every interval seconds.Example:watch -p free -m
Example:
watch -p free -m
-t, –no-title : This option is used to turn off the header showing the interval, command, and the current time at the top of the display. It will also turn off the following blank line..Example :watch -t free -m
Example :
watch -t free -m
-b, –beep: This option will give beep if the command has a non-zero exit.Example:watch -b free -m
Example:
watch -b free -m
-e, –errexit : This option will freeze the updates on command error, and exit after a key press.Example:watch -e free -m
Example:
watch -e free -m
-g, –chgexit : This option will exit when the output of command changes.
-c, –color : This option interprets ANSI color and style sequences.
-x, –exec : This option command given to sh -c which means that you may need to use extra quoting just to get the desired effect.
watch -h : This option will show the help message and exit.watch -h
watch -h
watch -v : This option will display the version information and exit.watch -v
watch -v
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Compiling with g++
UDP Server-Client implementation in C
touch command in Linux with Examples
echo command in Linux with Examples
nohup Command in Linux with Examples
Cat command in Linux with examples
date command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
How to enable CORS headers in your Django Project? - GeeksforGeeks

26 Nov, 2020
When site A wants to access content from another site B, it is called a Cross-Origin request. As it is disabled for security reasons, B sends an Access-Control-Allow-Origin header in the response. By default, a domain is not allowed to access an API hosted on another domain.  If we want to allow our REST API (say backend) hosted in our Django application to be accessed from other applications (say front-end) hosted on another server, we must enable CORS (Cross-Origin Resource Sharing).
1. Install django-cors-headers using PIP:
pip install django-cors-headers 
2. Add corsheaders to installed applications section in the settings.py file:
INSTALLED_APPS = [

   ...

   'corsheaders',

   ...

]
3. Add corsheaders.middleware.CorsMiddleware to middleware section in settings.py file:
MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  ...
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'corsheaders.middleware.CorsMiddleware',
]
4. If you want to allow access for all domains, set the following variable to TRUE in settings.py file:
CORS_ORIGIN_ALLOW_ALL = True
Alternatively, you can specify which domains you want to give access to by doing the following in settings.py file:
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000',
)
That’s all! Now your API is accessible to other applications hosted on other selected servers.
Python Django
Python Framework
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()
How to Add an Empty Column to DataFrame in R? - GeeksforGeeks

28 Nov, 2021
In this article, we will discuss how to add an empty column to the dataframe in R Programming Language.
Here we are going to add an empty column to the dataframe by assigning to column values as NA.
Syntax:
dataframe[ , 'column_name'] = NA
where,
dataframe  is the input dataframe
column_name is the new column name
Example: R program to create a dataframe with 3 columns and add an empty column
R
# create a dataframe with 4 rows and 3 columnsdata = data.frame(marks1=c('90', '78', '89', '76'),                  marks2=c('92', '68', '78', '96'),                  marks3=c('90', '78', '89', '76'))  # add an empty column named empty_columndata[, 'empty_column'] = NA  # displayprint(data)
Output:
We can add multiple columns with empty values in dataframe by passing column names in c() function
Syntax:
data[,c('column_name1',column_name2',............,'column_name n')]
Example: R program to add 4 empty columns
R
# create a dataframe with 4 rows and 3 columnsdata = data.frame(marks1=c('90', '78', '89', '76'),                  marks2=c('92', '68', '78', '96'),                   marks3=c('90', '78', '89', '76'))  # add 4 empty columnsdata[, c('empty1', 'empty2', 'empty3', 'empty4')] = NA  # displayprint(data)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
JavaScript | Window innerWidth and innerHeight Properties - GeeksforGeeks

14 Feb, 2019
The innerWidth property in JavaScript returns the width and innerHeight property returns the height of window content area.
Syntax:
window.innerWidth
window.innerHeight
Parameter: It doesn’t required any parameters.
Return Value: It Returns a number, Representing the Width and Height of the window’s content area.
Note: For IE 8 i.e (Internet Edg 8) or earlier, use clientWidth and clientHeight to get width and height of window.
Example:
<!DOCTYPE html><html>     <head>          <title>Browser Inner width and height</title>          <style>            body{                text-align:center;            }            .gfg {                font-size:40px;                font-weight:bold;                color:green;            }          </style>     </head>     <body>     <div class = "gfg">GeeksforGeeks</div>     <h2>Browser Window</h2>     <p id="demo"></p>     <script>          var Width, Height, result;            // height and width of Browser window          Width = window.innerWidth || document.documentElement.clientWidth                  || document.body.clientWidth;            Height = window.innerHeight || document.documentElement.clientHeight                  || document.body.clientHeight;          // Display Width and Height.          result = document.getElementById("demo");          result.innerHTML = "Browser inner width: " + Width +                              "<br>Browser inner height: " + Height;       </script></body></html>
Output:
javascript-basics
Web technologies
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 Open URL in New Tab using JavaScript ?
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Array.Clear() Method in C#

The Array.Clear() method in C# is used to clear the elements in an array and set them to its default. The elements are cleared in a range. The syntax is as follows −
public static void Clear (Array arr, int index, int len);
Here, arr is the array whose elements are to be cleared, the index is the beginning index of the elements to clear, and len is the count of elements to clear.
Let us now see an example to implement the Array.Clear() method −
using System;
public class Demo{
   public static void Main(){
      Console.WriteLine("Array elements...");
      int[] arr = { 20, 50, 100, 150, 200, 300, 400, 450, 500, 600, 800, 1000, 1500, 2000 };
      for (int i = 0; i < 14; i++){
         Console.Write("{0} ", arr[i]);
      }
      Console.WriteLine();
      Console.WriteLine("Clearing some elements in a range...");
      Array.Clear(arr, 5, 9);
      for (int i = 0; i < 14; i++){
         Console.Write("{0} ", arr[i]);
      }
      Console.WriteLine();
   }
}
This will produce the following output −
Array elements...
20 50 100 150 200 300 400 450 500 600 800 1000 1500 2000
Clearing some elements in a range...
20 50 100 150 200 0 0 0 0 0 0 0 0 0
Let us see another example −
using System;
public class Demo{
   public static void Main(){
      Console.WriteLine("Array elements...");
      int[,] arr = { {20, 50, 100, 120}, {150, 200, 300, 350}, {400, 450, 500, 550}, {600, 800, 1000, 1200} };
      for (int i = 0; i < 4; i++){
         for (int j = 0; j < 4; j++){
            Console.Write("{0} ", arr[i,j]);
         }
         Console.WriteLine();
      }
      Console.WriteLine();
      Console.WriteLine("Clearing some elements in a range...");
      Array.Clear(arr, 5, 9);
      for (int i = 0; i < 4; i++){
         for (int j = 0; j < 4; j++){
            Console.Write("{0} ", arr[i,j]);
         }
         Console.WriteLine();
      }
      Console.WriteLine();
   }
}
This will produce the following output −
Array elements...
20 50 100 120
150 200 300 350
400 450 500 550
600 800 1000 1200
Clearing some elements in a range...
20 50 100 120
150 0 0 0
0 0 0 0
0 0 1000 1200
Conversion Operators in C++

20 Dec, 2021
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading function in class.For example consider the following class, here, we are making a class for complex numbers. It has two data members: real and imaginary. 
C++
// CPP Program to demonstrate Conversion Operators#include <cmath>#include <iostream>using namespace std; class Complex {private:    double real;    double imag; public:    // Default constructor    Complex(double r = 0.0, double i = 0.0)        : real(r)        , imag(i)    {    }     // magnitude : usual function style    double mag() { return getMag(); }     // magnitude : conversion operator    operator double() { return getMag(); } private:    // class helper to get magnitude    double getMag()    {        return sqrt(real * real + imag * imag);    }}; int main(){    // a Complex object    Complex com(3.0, 4.0);     // print magnitude    cout << com.mag() << endl;    // same can be done like this    cout << com << endl;}
5
5
We are printing the magnitude of Complex objects in two different ways.Note that the compiler will have more control in calling an appropriate function based on type, rather than what the programmer expects. It will be good practice to use other techniques like class/object specific member function (or making use of C++ Variant class) to perform such conversions. At some places, for example in making compatible calls with the existing C library, these are unavoidable.
anshikajain26
sweetyty
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Correlation between two numeric columns in a Pandas DataFrame

We can use pandas.DataFrame.corr to compute pairwise correlation of columns, excluding NULL values. The correlation coefficient indicates the strength of the linear association between two variables. The coefficient ranges between -1 and 1.
To get the correlation between two numeric columns in a Pandas dataframe, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a Pandas dataframe of two-dimensional, size-mutable, potentially heterogeneous tabular data.
Compare the values of the two columns and compute the correlation coefficient using col1.corr(col2).
Print the correlation coefficient on the console.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

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

df = pd.DataFrame({'lab': [1, 2, 3], 'value': [3, 4, 5]})

col1 = df['lab']
col2 = df['value']

plt.plot(col1, col2)

print("The correlation coefficient is: ", col1.corr(col2))

plt.show()
It will produce the following output
The correlation coefficient is: 1.0

Here, the correlation coefficient is 1.0 which indicates perfect correlation. Hence, we get a straight line because all the points lie along a straight line.
How to Read JSON Files with Pandas? - GeeksforGeeks

22 Nov, 2021
In this article, we are going to see how to read JSON Files with Pandas.
To read the files, we use read_json() function and through it, we pass the path to the JSON file we want to read. Once we do that, it returns a “DataFrame”( A table of rows and columns) that stores data. If we want to read a file that is located on remote servers then we pass the link to its location instead of a local path.
Python3
import pandas as pd    df = pd.read_json("FILE_JSON.json")df.head()
Output:
   One  Two
0   60  110
1   60  117
2   60  103
3   45  109
4   45  117
5   60  102
Here we will create JSON data and then create a dataframe through it using pd.Dataframe() methods.
Python3
import pandas as pd  data = {    "One": {        "0": 60,        "1": 60,        "2": 60,        "3": 45,        "4": 45,        "5": 60    },    "Two": {        "0": 110,        "1": 117,        "2": 103,        "3": 109,        "4": 117,        "5": 102    }}  df = pd.DataFrame(data)  print(df)
Output:
   One  Two
0   60  110
1   60  117
2   60  103
3   45  109
4   45  117
5   60  102
Picked
Python pandas-io
Python-pandas
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?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Interactive Ruby (irb)

Interactive Ruby or irb is an interactive programming environment that comes with Ruby. It was written by Keiju Ishitsuka.
To invoke it, type irb at a shell or command prompt, and begin entering Ruby statements and expressions. Use exit or quit to exit irb.
$ irb[.rb] [options] [programfile] [arguments]

Here is a complete list of options −
-f
Suppress reading of the file ~/.irbrc.
-m
bc mode (load mathn library so fractions or matrix are available).
-d
Sets $DEBUG to true (same as ruby -d).
-r load-module
Same as ruby -r.
-I path
Specify $LOAD_PATH directory.
--inspect
Use inspect for output (default except for bc mode).
--noinspect
Don't use inspect for output.
--readline
Use Readline extension module.
--noreadline
Don't use Readline extension module.
--prompt prompt-mode (--prompt-mode prompt-mode)
Switch prompt mode. Predefined prompt modes are default, simple, xmp, and inf-ruby.
--inf-ruby-mode
Use prompt appropriate for inf-ruby-mode on Emacs. Suppresses --readline.
--simple-prompt
Simple prompt mode.
--noprompt
No prompt mode.
--tracer
Display trace for each execution of commands.
--back-trace-limit n
Display backtrace top n and tail n. The default value is 16.
--irb_debug n
Set internal debug level to n (not for popular use).
-v (--version).
Print the version of irb.
Here is a sample of irb evaluating a variety of expressions::
$ irb
irb(main):001:0> 23 + 27
=> 50
irb(main):002:0> 50 - 23
=> 27
irb(main):003:0> 10 * 5
=> 50
irb(main):004:0> 10**5
=> 100000
irb(main):006:0> x = 1
=> 1
irb(main):007:0> x + 59
=> 60
irb(main):005:0> 50 / 5
=> 10
irb(main):008:0> hi = "Hello, Mac!"
=> "Hello, Mac!"
You can also invoke a single program with irb. After running the program, irb exits. Let's call our hello.rb program −
$ irb hello.rb
hello.rb(main):001:0> #!/usr/bin/env ruby
hello.rb(main):002:0*
hello.rb(main):003:0* class Hello
hello.rb(main):004:1> def initialize( hello )
hello.rb(main):005:2> @hello = hello
hello.rb(main):006:2> end
hello.rb(main):007:1> def hello
hello.rb(main):008:2> @hello
hello.rb(main):009:2> end
hello.rb(main):010:1> end
=> nil
hello.rb(main):011:0>
hello.rb(main):012:0* salute = Hello.new( "Hello, Mac!" )
=> #<Hello:0x319f20 @hello = "Hello, Mac!">
hello.rb(main):013:0> puts salute.hello
Hello, Mac!
=> nil
hello.rb(main):014:0> $

    46 Lectures 
     9.5 hours 

 Eduonix Learning Solutions

    97 Lectures 
     7.5 hours 

 Skillbakerystudios

    227 Lectures 
     40 hours 

 YouAccel

    19 Lectures 
     10 hours 

 Programming Line

    51 Lectures 
     5 hours 

 Stone River ELearning

    39 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Get the QR factorization of a given NumPy array - GeeksforGeeks

29 Aug, 2020
In this article, we will discuss QR decomposition or QR factorization of a matrix. QR factorization of a matrix is the decomposition of a matrix say ‘A’ into ‘A=QR’ where Q is orthogonal and R is an upper-triangular matrix. We factorize the matrix using numpy.linalg.qr() function.
Syntax : numpy.linalg.qr(a, mode=’reduced’)
Parameters :
a : matrix(M,N) which needs to be factored.
mode : it is optional. It can be :
Below are some examples of how to use the above-described function :
Example 1: QR factorization of 2X2 matrix
Python3
# Import numpy packageimport numpy as np  # Create a numpy array arr = np.array([[10,22],[13,6]])  # Find the QR factor of arrayq, r =  np.linalg.qr(arr)  # Print the resultprint("Decomposition of matrix:")print( "q=\n", q, "\nr=\n", r)
Output :
Example 2: QR factorization of 2X4 matrix
Python3
# Import numpy packageimport numpy as np  # Create a numpy array arr = np.array([[0, 1], [1, 0], [1, 1], [2, 2]])  # Find the QR factor of arrayq, r =  np.linalg.qr(arr)  # Print the resultprint("Decomposition of matrix:")print( "q=\n", q, "\nr=\n", r)
Output :
Example 3: QR factorization of 3X3 matrix
Python3
# Import numpy packageimport numpy as np  # Create a numpy array arr = np.array([[5, 11, -15], [12, 34, -51],                [-24, -43, 92]], dtype=np.int32)  # Find the QR factor of arrayq, r = np.linalg.qr(arr)  # Print the resultprint("Decomposition of matrix:")print( "q=\n", q, "\nr=\n", r)
Output :
Python numpy-Linear Algebra
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
How to sort a boxplot by the median values in Pandas?

To sort a boxplot by the median values in Pandas, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a Pandas dataframe of two-dimensional, size-mutable, potentially heterogeneous tabular data, with three columns.
Create a Pandas dataframe of two-dimensional, size-mutable, potentially heterogeneous tabular data, with three columns.
Group the dataframe elements by marks and dob.
Group the dataframe elements by marks and dob.
Find the median of the dataframe.
Find the median of the dataframe.
Get the sorted values of the median.
Get the sorted values of the median.
Create a box plot from the DataFrame columns.
Create a box plot from the DataFrame columns.
To display the figure, use Show() method.
To display the figure, use Show() method.
import pandas as pd
import matplotlib.pyplot as plt

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

df = pd.DataFrame([
    [23, 'James', 12],
    [39, 'Jimmy', 27],
    [56, 'Jack', 69],
    [60, 'Tom', 96],
    [80, 'Tim', 79]
], columns=['marks', 'names', 'dob'])

g = df.groupby(["marks", "dob"])

df = pd.DataFrame({col: val['dob'] for col, val in g})

median = df.median()
median.sort_values(ascending=False, inplace=True)

df = df[median.index]
df.boxplot()

plt.show()
It will produce the following output −
Python 3 - String find() Method

The find() method determines if the string str occurs in string, or in a substring of string if the starting index beg and ending index end are given.
Following is the syntax for find() method −
str.find(str, beg = 0 end = len(string))

str − This specifies the string to be searched.
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the lenght of the string.
end − This is the ending index, by default its equal to the lenght of the string.
Index if found and -1 otherwise.
#!/usr/bin/python3

str1 = "this is string example....wow!!!"
str2 = "exam";

print (str1.find(str2))
print (str1.find(str2, 10))
print (str1.find(str2, 40))
When we run above program, it produces the following result −
15
15
-1


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
TypeScript | String replace() Method - GeeksforGeeks

18 Jun, 2020
The replace() is an inbuilt function in TypeScript which is used to find a match between a regular expression and a string, and replaces the matched substring with a new substring. Syntax:
string.replace(regexp/substr, newSubStr/function[, flags]);
Parameter: This method accept five parameter as mentioned above and described below: 
regexp: This parameter is a RegExp object.
substr: This parameter is a String that is to be replaced.
newSubStr: This parameter is a String that replaces the substring.
function: This parameter is a function to be invoked to create the new substring.
flags: This parameter is a String containing any combination of the RegExp flags.
Return Value: This method returns a new changed string. 
Below example illustrate the  String replace() method in TypeScriptJS:
Example 1: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks - Good Platform";       var re = /Good/gi;       // Use of String replace() Method    var newstr = str.replace(re, "Best");     console.log(newstr);</script>
Output: 
Geeksforgeeks - Best Platform

Example 2: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks TypeScript";       var re = /(\w+)\s(\w+)/;       // use of String replace() Method    var newstr = str.replace(re, "$2 $1");     console.log(newstr);</script>
Output: 
TypeScript Geeksforgeeks

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Merge two array fields in MongoDB?

To merge, use $setUnion operator. Let us first create a collection with documents −
> db.mergeTwoArrayFieldDemo.insertOne({"NaturalNumbers":[1,2,3,8,10,20,30],"WholeNumbers":[0,1,2,63,78,20,45]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd68e4057806ebf1256f11d")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.mergeTwoArrayFieldDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd68e4057806ebf1256f11d"),
   "NaturalNumbers" : [
      1,
      2,
      3,
      8,
      10,
      20,
      30
   ],
   "WholeNumbers" : [
      0,
      1,
      2,
      63,
      78,
      20,
      45
   ]
}
Following is the query to merge two array field in MongoDB.
> db.mergeTwoArrayFieldDemo.aggregate([
   { "$project": {
      "MergedArray": { "$setUnion": [ "$NaturalNumbers", "$WholeNumbers" ] }
   }}
]);
This will produce the following output −
{ "_id" : ObjectId("5cd68e4057806ebf1256f11d"), "MergedArray" : [ 0, 1, 2, 3, 8, 10, 20, 30, 45, 63, 78 ] }
How to pass JavaScript variables to PHP?

You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL.
<script>
   var res = "success";
</script>
<?php
   echo "<script>document.writeln(res);</script>";
?>
C Program for simple interest?

Simple Interest is the product of principal amount, rate of interest and the time duration (in years) by 100.
Example,
Input − p=5, r=4, t=5
Output − 1
Explanation: Simple Interest = (Principal Amount * Rate of Interest * Number of years) / 100
SI= 5*4*5/100 = 1
#include<iostream>
#include <stdio.h>
using namespace std;
int main() {
   //principle amount
   float p = 5;
   //time
   float r = 4;
   //rate in years
   float t = 5;
   // Simple interest
   float SI = 0;
   SI =(p * t * r) / 100;
   printf("Simple Interest = %f ",SI);
   return 0;
}
Simple Interest = 1.0000
C++ Iterator Library - reverse_iterator

It is an iterator adaptor that reverses the direction of a given iterator.
Following is the declaration for std::reverse_iterator.
template <class Iterator> class reverse_iterator;

Iterator − It is a bidirectional iterator type.
none
If x somehow throws while applying the unary operator& to it, this function never throws exceptions.
constant for random-access iterators.
The following example shows the usage of std::reverse_iterator.
#include <iostream>
#include <string>
#include <iterator>
 
int main() {
   std::string s = "tutorialspoint";
   std::reverse_iterator<std::string::iterator> r = s.rbegin();
   r[10] = 'O'; // replaces 'o' with 'O' 
   r += 10; // iterator now points at 'O'
   std::string rev(r, s.rend());
   std::cout << rev << '\n';
}
Let us compile and run the above program, this will produce the following result −
Otut

 Print
 Add Notes
 Bookmark this page
How to create a responsive image gallery with CSS

To create a responsive image gallery with CSS, you can try to run the following code
<!DOCTYPE html>
<html>
   <head>
      <style>
         div.myGallery {
            border: 2px solid orange;
         }
         div.myGallery:hover {
            border: 1px solid blue;
         }
         div.myGallery img {
            width: 100%;
            height: auto;
         }
         div.desc {
            padding: 20px;
            text-align: center;
         }
         .responsive {
            padding: 0 5px;
            float: left;
            width: 24.99999%;
         }
         @media only screen and (max-width: 700px) {
            .responsive {
               width: 49.99999%;
               margin: 5px 0;
            }
         }
         @media only screen and (max-width: 500px) {
            .responsive {
               width: 100%;
            }
         }
         .clearfix:after {
            content: "";
            display: table;
            clear: both;
         }
      </style>
   </head>
   <body>
      <div class = "responsive">
         <div class = "myGallery">
            <a target = "_blank" href="https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg">
               <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/3d_animation_online_training/380_course_211_image.jpg" alt="3D Animation Tutorial" width="600" height="500">
            </a>
            <div class = "mydiv">3D Animation Tutorial></div>
         </div>
      </div>
      <div class = "responsive">
         <div class = "myGallery">
            <a target = "_blank" href = "https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg">
               <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg" alt="Swift Video Tutorial" width="600" height="500">
            </a>
            <div class = "mydiv">Swift Video Tutorial</div>
         </div>
      </div>
      <div class = "responsive">
         <div class = "myGallery">
            <a target = "_blank" href = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg">
               <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg" alt="CSS Video Tutorial" width="600" height="500">
            </a>
            <div class="mydiv">CSS Tutorial</div>
         </div>
      </div>
      <div class = "clearfix"></div>
   </body>
</html>
C++ Memory Library - shared_ptr

It is an instrumental class and allows certain conversions that allow auto_ptr objects to be passed to and returned from functions.
Following is the declaration for std::shared_ptr function.
template <class T> class shared_ptr;
template <class T> class shared_ptr;
T − It is a managed object.
 Print
 Add Notes
 Bookmark this page
click() element method - Selenium Python - GeeksforGeeks

27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use click method in Selenium. click method is used to click on any element, such as an anchor tag, a link, etc.
element.click()
Example –
<a href="https://www.geeksforgeeks.org/" id="link" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_id("link")
Now one can click this element with
element.click()
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python. Here we click courses tab in navigation bar at geeksforgeeksProgram –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # click the elementelement.click()
Output-
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
How to Kill a Process by Name in Linux?

This article shows you how to use the Linux pkill command to kill running processes within Linux by using a name. Pkill (see pgrep) is a command-line utility while Solaris 7 process is running. pkill works on a currently active running process and lists down process ID’s which matches with the criteria.
To kill a process by name in Linux, use the following command –
pkill
To get a list of process in Linux, use the following command –
$ ps -A
The sample output should be like this –
PID TTY          TIME CMD
   1 ?           00:00:01 systemd
   2 ?           00:00:00 kthreadd
   3 ?           00:00:00 ksoftirqd/0
   5 ?           00:00:00 kworker/0:0H
   7 ?           00:00:17 rcu_sched
   8 ?           00:00:00 rcu_bh
   9 ?           00:00:00 migration/0
   10 ?          00:00:00 watchdog/0
   11 ?          00:00:00 watchdog/1
   12 ?          00:00:00 migration/1
   13 ?          00:00:00 ksoftirqd/1
   15 ?          00:00:00 kworker/1:0H
   16 ?          00:00:00 watchdog/2
   17 ?          00:00:00 migration/2
   18 ?          00:00:00 ksoftirqd/2
   20 ?          00:00:00 kworker/2:0H
   21 ?          00:00:00 watchdog/3
   22 ?          00:00:00 migration/3
   23 ?          00:00:00 ksoftirqd/3
   25 ?          00:00:00 kworker/3:0H
   26 ?          00:00:00 kdevtmpfs
   27 ?          00:00:00 netns
   28 ?          00:00:00 perf
   29 ?          00:00:00 khungtaskd
   30 ?          00:00:00 writeback
   31 ?          00:00:00 ksmd
   32 ?          00:00:00 khugepaged
   33 ?          00:00:00 crypto
   34 ?          00:00:00 kintegrityd
   35 ?          00:00:00 bioset
   36 ?          00:00:00 kblockd
   37 ?          00:00:00 ata_sff
   38 ?          00:00:00 md
   39 ?          00:00:00 devfreq_wq
   44 ?          00:00:00 kswapd0
   45 ?          00:00:00 vmstat
   46 ?          00:00:00 fsnotify_mark
   47 ?          00:00:00 ecryptfs-kthrea
   63 ?          00:00:00 kthrotld
   64 ?          00:00:00 acpi_thermal_pm
   65 ?          00:00:00 bioset
   66 ?          00:00:00 bioset
   67 ?          00:00:00 bioset
...............................................
To kill the process using name, use the following command –
$sudo pkill apache2
To verify the above command, use the following command –
$ ps -A
From the above, we have learnt about – How to Kill a Process by Name in Linux? We will come up with more Linux based tricks and tips. Keep reading!
Python pass Statement

It is used when a statement is required syntactically but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example) −
pass

#!/usr/bin/python

for letter in 'Python': 
   if letter == 'h':
      pass
      print 'This is pass block'
   print 'Current Letter :', letter

print "Good bye!"
When the above code is executed, it produces following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Java Enums

An enum is a special "class" that represents a group of 
constants (unchangeable variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate 
the constants with a comma. Note that they should be in uppercase letters:
enum Level {
  LOW,
  MEDIUM,
  HIGH
}

You can access enum constants with the dot syntax:
Enum is short for "enumerations", which means "specifically listed".
You can also have an enum inside a class:
public class Main {
  enum Level {
    LOW,
    MEDIUM,
    HIGH
  }

  public static void main(String[] args) {
    Level myVar = Level.MEDIUM; 
    System.out.println(myVar);
  }
}

The output will be:
Enums are often used in switch statements to check for corresponding values:
enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main {
  public static void main(String[] args) {
    Level myVar = Level.MEDIUM;

    switch(myVar) {
      case LOW:
        System.out.println("Low level");
        break;
      case MEDIUM:
         System.out.println("Medium level");
        break;
      case HIGH:
        System.out.println("High level");
        break;
    }
  }
}

The output will be:
The enum type has a values() method, which returns an array of all enum constants. This method is useful when you want to loop through the constants of an enum:
for (Level myVar : Level.values()) {
  System.out.println(myVar);
}

The output will be:
An enum can, just like a class, have attributes and methods. The only 
difference is that enum constants are public, static and final 
(unchangeable - cannot be overridden).
An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Lagrange’s Interpolation in C++

In this tutorial, we are going to write a program that finds the result for lagranges's interpolation formula.
You don't have write any logic for the program. Just convert the formula into code. Let's see the code.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
struct Data {
   int x, y;
};
double interpolate(Data function[], int xi, int n) {
   double result = 0;
   for (int i = 0; i < n; i++) {
      double term = function[i].y;
      for (int j = 0; j < n; j++) {
         if (j != i) {
            term = term * (xi - function[j].x) / double(function[i].x - function[j].x);
         }
      }
      result += term;
   }
   return result;
}
int main() {
   Data function[] = {{0,3}, {1,2}, {6,9}, {10,17}};
   cout << interpolate(function, 3, 5) << endl;
   return 0;
}
If you run the above code, then you will get the following result.
3
If you have any queries in the tutorial, mention them in the comment section.
GATE | GATE CS 1997 | Question 49 - GeeksforGeeks

22 Apr, 2020
For a database relation R(a,b,c,d), where the domains a, b, c, d include only atomic values, only the following functional dependencies and those that can be inferred from them hold:
{ a → c, b → d } 
This relation is(A) in first normal form but not in second normal form(B) in second normal form but not in first normal form(C) in third normal form(D) None of the aboveAnswer: (A)Explanation: Candidate Key of above relation is :- ab only.
a and b is partial attribute (part of the CK) that’s why the given FD is partially dependents.
In 2NF there must not be partially dependents FD and we know that every table is already in 1NF.Hence, this relation is in first normal form but not in second normal form.
Option (A) is correct.Quiz of this Question
ApurvaRaj
GATE CS 1997
GATE-GATE CS 1997
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Python - Change Keys Case in Dictionary - GeeksforGeeks

10 May, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform manipulation of cases of keys. This can have possible application in many domains including school programming and data domains. Lets discuss a way to solve this task.
Input : test_dict = {‘Gfg’ : {‘a’ : 5, ‘b’ : {‘best’ : 6}}}Output : {‘GFG’: {‘A’: 5, ‘B’: {‘BEST’: 6}}}
Input : test_dict = {‘Gfg’ : 6}Output : {‘GFG’: 6}
Method : Using isinstance() + toupper() + recursion + loopThe combination of above functions can also be used to solve this problem. In this, we use toupper() to perform upper case of keys, recursion is used to perform keys manipulation in nested keys as well. The isinstance() is used to check if nesting is dictionary.
# Python3 code to demonstrate working of # Change Keys Case in Dictionary# Using isinstance() + toupper() + recursion + loop  # helper functiondef keys_upper(test_dict):    res = dict()    for key in test_dict.keys():        if isinstance(test_dict[key], dict):            res[key.upper()] = keys_upper(test_dict[key])        else:            res[key.upper()] = test_dict[key]    return res  # initializing dictionarytest_dict = {'Gfg' : {'a' : 5, 'b' : 6}, 'is' : {'for' :2}, 'best': 3}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Change Keys Case in Dictionary# Using isinstance() + toupper() + recursion + loopres = keys_upper(test_dict)  # printing result print("The modified dictionary : " + str(res)) 
The original dictionary : {'is': {'for': 2}, 'Gfg': {'b': 6, 'a': 5}, 'best': 3}
The modified dictionary : {'GFG': {'A': 5, 'B': 6}, 'IS': {'FOR': 2}, 'BEST': 3}

 
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Pandas Series.str.match() - GeeksforGeeks

27 Mar, 2019
Series.str can be used to access the values of the series as strings and apply several methods to it. Pandas Series.str.match() function is used to determine if each string in the underlying data of the given series object matches a regular expression.
Syntax: Series.str.match(pat, case=True, flags=0, na=nan)
Parameter :pat : Regular expression pattern with capturing groups.case : If True, case sensitiveflags : A re module flag, for example re.IGNORECASE.na : default NaN, fill value for missing values
Returns : Series/array of boolean values
Example #1: Use Series.str.match() function to match the passed regular expressions with the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd  # importing re for regular expressionsimport re  # Creating the Seriessr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])  # Creating the indexidx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.match() function to match the passed regular expressions with the string in the underlying data of the given series object.
# match either 'Tokyo' or 'Paris'result = sr.str.match(pat = '(Tokyo)|(Paris)')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.match() function has returned a series of boolean values. It contains True for those values which successfully matches else it contains False.
Example #2 : Use Series.str.match() function to match the passed regular expressions with the string in the underlying data of the given series object.
# importing pandas as pdimport pandas as pd  # importing re for regular expressionsimport re  # Creating the Seriessr = pd.Series(['Mike', 'Alessa', 'Nick', 'Kim', 'Britney'])  # Creating the indexidx = ['Name 1', 'Name 2', 'Name 3', 'Name 4', 'Name 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.str.match() function to match the passed regular expressions with the string in the underlying data of the given series object.
# match groups having any capital letter# followed by 'i' and any other characterresult = sr.str.match(pat = '([A-Z]i.)')  # print the resultprint(result)
Output :
As we can see in the output, the Series.str.match() function has returned a series of boolean values. It contains True for those values which successfully matches else it contains False.
Python-pandas
Python-pandas-series-str
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()