code-rag-bench/online-tutorials huggingface dataset:
Increase and decrease the brightness of an image in MATLAB - GeeksforGeeks

22 Sep, 2021
The degree of the illuminance of the image is called brightness. How much light is coming out of an object defines the brightness of that object. If an object is placed in a dark room then very less light will be emitted by that object thus we can’t see the object properly. Now, what do we mean by brightness in the context of a digital image? It is defined as the intensity level of the pixels of the image. We know, 0 intensity means dark pixel and 1 intensity means white pixel. Therefore, brightness can be said as the average intensity value of all the pixels of an image.
Syntax: 
image_var = imread(“path of image”);
image = image – C; where C is constant, like 50.
image = image + C; where C is constant, like 50.
imtool(image_var, [ ]);
Example 1:
Matlab
% MATLAB code for read the image % and convert into dark and bright images.org_image=imread("lady_with_hat.jfif");dark_image=uint8(org_image-50);bright_image=uint8(org_image+50);  % Bring the all three images to see% the difference in brightness.imtool(org_image, []);imtool(dark_image, []);imtool(bright_image, []);
Output:
Example 2:
Matlab
% MATLAB code for read the colored image% and convert into dark and bright images.org_image=imread("logo.png"); dark_image=uint8(org_image-50);bright_image=uint8(org_image+50);  % Bring the all three images to see % the difference in brightness.imtool(org_image, []);imtool(dark_image, []);imtool(bright_image, []);
Output: 
To increase the brightness we have to increase the intensity of each pixel. Image is a collection of pixel values. So, they are additive in nature. We can just add a constant to every pixel value. To decrease the brightness we can just decrease a constant value from all the pixels of the image.
MATLAB image-processing
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Forward and Inverse Fourier Transform of an Image in MATLAB
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
How to Remove Salt and Pepper Noise from Image Using MATLAB?
Classes and Object in MATLAB
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
Double Integral in MATLAB
Automated File Organizer using Tkinter in Python - GeeksforGeeks

27 Dec, 2021
Prerequisites: Tkinter
File organization is helpful when you are trying to find a specific one in a pool of files and directories. It seems time-consuming and exhausting to check each file. In cases where the number of files are way too many and you have no idea where to find it exactly, file organization is a saviour.
This article discusses how this can be done using Tkinter. This module will create a GUI that will make the task of searching for a file not just fast but also interactive and simple.
Tkinter : For creating graphical user interface
Os : To interact with folders and files
Shutil : To move files to specific folder
Import module
Create program window
Select folder to be organized. This function will pop up a window where user will select the desired folder.
Create button to start organizing files
Add feedback message, so that the user has a clue what is going on
Set criteria for files to be selected. This article organizes files using their extension.
Create main
Call function loop to GUI
Python3
from tkinter import *from tkinter import filedialogimport osimport shutil  class GUI(Tk):    def __init__(self):        super().__init__()        self.geometry('500x500')     def gettingPath(self):        self.path = filedialog.askdirectory()        return self.path     def startButton(self, path_value):        self.button_Frame = Frame(self)        self.button_Frame.pack()        self.start_Button = Button(self.button_Frame, text='Start', command=lambda: self.startOperation(            path_value)).grid(row=0, column=0)     def startOperation(self, path_value):        count = 0        os.chdir(path_value)        self.file_list = os.listdir()        no_of_files = len(self.file_list)        if len(self.file_list) == 0:            self.error_label = Label(text="Error empty folder").pack()            exit()        for file in self.file_list:            if file.endswith(".png"):                self.dir_name = "PngFiles"                self.new_path = os.path.join(path_value, self.dir_name)                self.file_list = os.listdir()                if self.dir_name not in self.file_list:                    os.mkdir(self.new_path)                shutil.move(file, self.new_path)             elif file.endswith(".txt"):                self.dir_name = "TextFiles"                self.new_path = os.path.join(path_value, self.dir_name)                self.file_list = os.listdir()                if self.dir_name not in self.file_list:                    os.mkdir(self.new_path)                shutil.move(file, self.new_path)            count = count+1         if(count == no_of_files):            success = Label(text="Operation Successful!").pack()        else:            error = Label(text="Failed").pack()  if __name__ == '__main__':    object = GUI()    path = object.gettingPath()    object.startButton(path)    object.mainloop()
Output:
rkbhola5
Python Tkinter-exercises
Python-tkinter
Technical Scripter 2020
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Fill empty column - Pandas - GeeksforGeeks

25 Feb, 2021
Sometimes the dataframe contains an empty column and may pose a real problem in the real life scenario. Missing Data can also refer to as NA(Not Available) values in pandas. In DataFrame sometimes many datasets simply arrive with missing data, either because it exists and was not collected or it never existed. In this article, let’s see how to fill empty columns in dataframe using pandas.
Note: Link of csv file here.
Fill empty column:
Python3
import pandas as pddf = pd.read_csv("Persons.csv")df
First, we import pandas after that we load our CSV file in the df variable. Just try to run this in jupyter notebook or colab.
Output:
Python3
df.set_index('Name ', inplace=True)df
This line used to remove index value, we don’t want that, so we remove it.
Output:
There are several methods used to fill the empty columns.we going to saw it one by one
Method 1:
In this method, we will use “df.fillna(0)” which replace all NaN elements with 0s.
Example:
Python3
df1 = df.fillna(0)df1
Output:
Method 2:
In this method, we will use “df.fillna(method=’ffill’)” , which is used to propagate non-null values forward or backward.
Syntax: DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None) 
Python3
df2 = df.fillna(method='ffill')df2
Output:
Method 3:
In this method we will use “df.interpolate()” 
Syntax: DataFrame.interpolate(method=’linear’, axis=0, limit=None, inplace=False, limit_direction=None, limit_area=None, downcast=None, **kwargs)
Python3
df3 = df.interpolate()df3
Output:
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Bar Plot in Matplotlib
HTML | <table> bgcolor Attribute - GeeksforGeeks

09 Mar, 2022
The HTML <table> bgcolor Attribute is use to specify the background color of a table.Syntax:  
<table bgcolor="color_name | hex_number | rgb_number">
Attribute Values:  
color_name: It sets the text color by using the color name. For example “red”.
hex_number: It sets the text color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the text color by using the rgb code. For example: “RGB(0, 153, 0)” .
Note: The <table> bgcolor Attribute is not supported by HTML 5 instead of using this we can use CSS background-color property. .Example:  
html
<!DOCTYPE html><html> <head>    <title>        HTML table bgcolor Attribute    </title></head> <body>    <h1>GeeksforGeeks</h1>     <h2>HTML table bgcolor Attribute</h2>     <table border="1"           bgcolor="green">        <caption>          Author Details      </caption>         <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>        <tr>            <td>RAM</td>            <td>21</td>            <td>ECE</td>        </tr>    </table></body> </html>
Output:  
Supported Browsers: The browser supported by HTML <table> bgcolor Attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
rajeev0719singh
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
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 ?
Difference between var, let and const keywords in JavaScript
Go Arrays

Arrays are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value.
In Go, there are two ways to declare an array:
Note: The length specifies the number of elements 
  to store in the array. In Go, arrays have a fixed length. The length of the 
  array is either defined by a number or is inferred 
(means that the compiler decides the length of the array, based on the number of
  values).
This example declares two arrays (arr1 and arr2) with defined lengths:
Result:
This example declares two arrays (arr1 and arr2) with inferred lengths:
Result:
This example declares an array of strings:
Result:
You can access a specific array element by referring to the index number.
In Go, array indexes start at 0. That means that [0] is the first element, [1] is the second element, etc.
This example shows how to access the first and third elements in the 
  prices array:
Result:
You can also change the value of a specific array element by referring to the index number.
This example shows how to change the value of the third element in the 
  prices array: 
Result:
 If an array or one of its elements has not been initialized in the code, it 
is assigned the default value of its type.
 Tip: The default value for int is 0, and the default value 
for string is "".
Result:
It is possible to initialize only specific elements in an array.
This example initializes only the second and third elements of the array: 
Result:
 The array above has 5 elements.
1:10 means: assign 
10 to array index 1 (second element).
2:40 means: assign 40 to 
array index 
2 (third element).
The len() function is used to find the length of an array:
Result:
Create an array, named cars, of type string:
package main   
import ("fmt") 
func main() {
  var  = [4]{"Volvo", "BMW", "Ford", "Mazda"}
  fmt.Print()
}

Start the Exercise
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.
CSS - margin-left

The margin-left property sets the width of the margin on the left of an element.
length − Any length value.
length − Any length value.
percentage − The margin's width is calculated with respect to the width of the element's containing block.
percentage − The margin's width is calculated with respect to the width of the element's containing block.
auto − Default, Let the browsers automatically set the margin.
auto − Default, Let the browsers automatically set the margin.
All the HTML elements.
object.style.marginLeft = "5px"

Here is the example −
<html>
   <head>
   </head>

   <body>
      <p style = "margin-left: 15px; border:1px solid black;">
         This is a paragraph with a specified left margin
      </p>
      
      <p style = "margin-left: 5%; border:1px solid black;">
         This is another paragraph with a specified top margin in percent
      </p>
   </body>
</html> 
This will produce following result −

   This is a paragraph with a specified left margin


   This is another paragraph with a specified top margin in percent


    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
C library function - ldiv()

The C library function div_t div(long int numer, long int denom) divides numer (numerator) by denom (denominator).
Following is the declaration for ldiv() function.
div_t div(long int numer, long int denom)
numer − This is the numerator.
numer − This is the numerator.
denom − This is the denominator.
denom − This is the denominator.
This function returns the value in a structure defined in <cstdlib>, which has two members. For ldiv_t:long quot; long rem;
The following example shows the usage of ldiv() function.
#include <stdio.h>
#include <stdlib.h>

int main () {
   ldiv_t output;

   output = ldiv(100000L, 30000L);

   printf("Quotient = %ld\n", output.quot);

   printf("Remainder = %ld\n", output.rem);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Quotient = 3
Remainder = 10000


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
GATE | GATE CS 2013 | Question 65 - GeeksforGeeks

11 Oct, 2021
What is the logical translation of the following statement?
  "None of my friends are perfect." 
(A) A(B) B(C) C(D) DAnswer: (D)Explanation: 
F(x) ==> x is my friend
P(x) ==> x is perfect

D is the correct answer.

A. There exist some friends which are not perfect

B. There are some people who are not my friend and are perfect

C. There exist some people who are not my friend and are not perfect.

D. There doesn't exist any person who is my friend and perfect 
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersLogical Equivalences involving Predicates and Quantifiers with Sakshi SinghalWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0037:17 / 41:28•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=SSCArIsewXw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
C/C++ Ternary Operator

Syntax of ternary operator is −
(expression-1) ? expression-2 : expression-3
This operator returns one of two values depending on the result of an expression. If "expression-1" is evaluated to Boolean true, then expression-2 is evaluated and its value is returned as a final result otherwise expression-3 is evaluated and its value is returned as a final result.
Let us write a program to find maximum of two numbers using ternary operator.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a = 10;
   int b = 20;
   int max = a > b ? a : b;
   cout << "Maximum value = " << max << "\n";
   return 0;
}
If we compare syntax of ternary operator with above example, then −
expression-1 is (a > b)
expression-2 is a
expression-3 is b
First, expression a > b is evaluated, which evaluates to Boolean false as value of variable 'a' is smaller than value of variable 'b'. Hence value of variable 'b' i.e. '20' is returned which becomes final result and gets assigned to variable 'max'.
When you compile and execute above code it will generate following output −
Maximum value = 20
C Program for n-th odd number

Given a number N we have to find the N-th odd number.
Odd numbers are the numbers which are not completely divided by 2 and their remainder is not zero. Like 1, 3, 5, 7, 9,....
If we closely observe the list of even numbers we can also represent them as
(2*1)-1=1, (2*2)-1=3,( 2*3)-1=5, (2*4)-1=7,....(2*N)-1.
So, to solve the problem we can simply multiply the number N with 2 and subtract 1 from the result, that makes up an odd number.
Input: 4
Output: 7
The 4th odd number is 1, 3, 5, 7..
Input: 10
Output: 19
START
   STEP 1 -> Declare and assign an integer ‘n’.
   STEP 2 -> Print n*2-1(odd number).
STOP
#include <stdio.h>
int main(int argc, char const *argv[]){
   int n = 10;
   //for odd numbers we can simply subtract 1 to the even numbers
   printf("Nth odd number = %d", n*2-1);
   return 0;
}
Nth odd number = 19
Sorting a HashMap according to values in Java

As we know that Hash map in Java does not maintain insertion order either by key or by order.Also it does not maintain any other order while adding entries to it.
Now in order to sort a hash map according to the values mapped to its corresponding keys we first need to get all values of map considering that hash map has unique values only.Now put all the values in a list and sort this list with the comparator or comparable interface of Java.


As we get sorted list of unique values now get corresponding keys from the map and put the value key pair in new tree map so that again the insertion order is maintained according to the values.After insertion we would transverse same tree map which is sorted and is our resultant sorted map.
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class HashMapSortByValue {
   public static void main(String[] args) {
      HashMap<String, String> hMap = new HashMap<>();
      LinkedHashMap<String, String> sortedMap = new LinkedHashMap<>();
      ArrayList<String> list = new ArrayList<>();
      hMap.put("5", "Akshay");
      hMap.put("8", "Veer");
      hMap.put("3", "Guang");
      hMap.put("7", "Bakshi");
      hMap.put("2", "TomTom");
      hMap.put("10", "Chang");
      hMap.put("1", "Sandy");
      for (Map.Entry<String, String> entry : hMap.entrySet()) {
         list.add(entry.getValue());
      }
      Collections.sort(list, new Comparator<String>() {
         public int compare(String str, String str1) {
            return (str).compareTo(str1);
         }
      });
      for (String str : list) {
         for (Entry<String, String> entry : hMap.entrySet()) {
            if (entry.getValue().equals(str)) {
               sortedMap.put(entry.getKey(), str);
            }
         }
      }
      System.out.println(sortedMap);
   }
}
{5 = Akshay, 7 = Bakshi, 10 = Chang, 3 = Guang, 1 = Sandy, 2 = TomTom, 8 = Veer}
JavaScript | RegExp g Modifier - GeeksforGeeks

22 Apr, 2019
The RegExp g Modifier in JavaScript is used to find all the occurrences of the pattern instead of stopping after the first match i.e it performs global match.
Syntax:
/regexp/g 
or
new RegExp("regexp", "g")
Example 1: This example searches the word “geeks” in the whole string.
<!DOCTYPE html><html>  <head>    <title>        JavaScript RegExp g Modifier    </title></head>  <body style="text-align:center">          <h1 style="color:green">        GeeksforGeeks    </h1>          <h2>RegExp g Modifier</h2>          <p>        geeksforgeeks is the computer         science portal for geeks.    </p>          <button onclick="geek()">        Click it!    </button>          <p id="app"></p>          <script>        function geek() {        var str1 = "geeksforgeeks is the computer "                 + "science portal for geeks.";        var regex4 = /geeks/g;        var match4 = str1.match(regex4);          document.getElementById("app").innerHTML =                     "Found " + match4.length                    + " matches: " + match4;        }    </script></body>  </html>                    
Output:Before Clicking the button:After Clicking the button:
Example 2: This example searches the word “portal” in the whole string and replaces it with “PORTAL”.
<!DOCTYPE html><html>  <head>    <title>        JavaScript RegExp g Modifier    </title></head>  <body style="text-align:center">          <h1 style="color:green">        GeeksforGeeks    </h1>          <h2>RegExp g Modifier</h2>          <p>        geeksforgeeks is the computer         science portal for geeks.    </p>          <button onclick="geek()">        Click it!    </button>          <p id="app"></p>          <script>        function geek() {        var str1 = "geeksforgeeks is the computer "                 + "science portal for geeks.";        var regex4 = new RegExp("portal", "g");                 var replace = "PORTAL";        var match4 = str1.replace(regex4, replace);            document.getElementById("app").innerHTML =             " New string: " + match4;        }    </script></body>  </html>                    
Output:Before Clicking the button:After Clicking the button:
Supported Browsers: The browsers supported by RegExp g Modifier are listed below:
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
JavaScript-RegExp
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
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
DAX Text - MID function

Returns a string of characters from the middle of a text string, given a starting position and length.
MID (<text>, <start_num>, <num_chars>) 

text
The text string from which you want to extract the characters, or a column that contains text.
start_num
A whole number representing the position of the first character you want to extract. The numbers start from 1 at the beginning of the text.
num_chars
The number of characters to return.
A text string.
DAX uses Unicode and stores all characters with the same length.
= MID ([Product], 1, 5), and 
= LEFT ([Product], 5) return the same characters. 
However, you can use DAX MID function to extract text from the middle of the input string.
= MID ([Product],5,5) returns 5 characters starting from the 5th character. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to part DATE and TIME from DATETIME in MySQL?

To part DATE and TIME from DATETIME, you can use the DATE_FORMAT() method from MySQL. The syntax is as follows −
SELECT DATE_FORMAT(yourColumnName, '%Y-%m-%d') VariableName, DATE_FORMAT(yourColumnName,'%H:%i:%s') VariableName from yourTableName;
To understand the above method DATE_FORMAT(), let us create a table with data type “datetime”.
Creating a table −
mysql> create table DateAndTimePartDemo
   -> (
   -> YourDateandtime datetime
   -> );
Query OK, 0 rows affected (0.56 sec)
Now, I am inserting current date and time using now(). The query is as follows −
mysql> insert into DateAndTimePartDemo values(now());
Query OK, 1 row affected (0.37 sec)
Display the record with the help of select statement. The query is as follows −
mysql> select *from DateAndTimePartDemo;
The following is the output that displays current date and time −
+---------------------+
| YourDateandtime     |
+---------------------+
| 2018-11-24 13:40:36 |
+---------------------+
1 row in set (0.00 sec)
Let us now part the above datetime with the help of DATE_FORMAT() function.
The query is as follows −
mysql> SELECT DATE_FORMAT(YourDateandtime, '%Y-%m-%d') OnlyYourDate,
-> DATE_FORMAT(YourDateandtime,'%H:%i:%s') OnlyYourTime from DateAndTimePartDemo;
The following is the output −
+--------------+--------------+
| OnlyYourDate | OnlyYourTime |
+--------------+--------------+
| 2018-11-24   | 13:40:36     |
+--------------+--------------+
1 row in set (0.03 sec)
Returning multiple values from a function using Tuple and Pair in C++

In C or C++, we cannot return more than one value from a function. To return multiple values, we have to provide output parameter with the function. Here we will see another approach to return multiple value from a function using tuple and pair STL in C++.
The Tuple is an object capable to hold a collection of elements, where each element can be of different types.
The pair can make a set of two values, which may be of different types. The pair is basically a special type of tuple, where only two values are allowed.
Let us see one example, where we will see how to tuple and pairs are working.
#include<iostream>
#include<tuple>
#include<utility>
using namespace std;
tuple<int, string, char> my_function_tuple(int x, string y) {
   return make_tuple(x, y, 'A'); // make tuples with the values and return
}
std::pair<int, string> my_function_pair(int x, string y) {
   return std::make_pair(x, y); // make pair with the values and return
}
main() {
   int a;
   string b;
   char c;
   tie(a, b, c) = my_function_tuple(48, "Hello"); //unpack tuple
   pair<int, string> my_pair = my_function_pair(89,"World"); //get pair from function
   cout << "Values in tuple: ";
   cout << "(" << a << ", " << b << ", " << c << ")" << endl;
   cout << "Values in Pair: ";
   cout << "(" << my_pair.first << ", " << my_pair.second << ")" << endl;
}
Values in tuple: (48, Hello, A)
Values in Pair: (89, World)
So what is the problem in the above program? The NULL is typically defined as (void*)0. We are allowed to convert NULL to integral type. So the function call of my_func(NULL) is ambiguous.
If we use the nullptr in the place of NULL, we will get the result like below −
#include<iostream>
using namespace std;
int my_func(int N) { //function with integer type parameter
   cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
   cout << "calling function my_func(char *)";
}
int main() {
   my_func(nullptr); //it will call my_func(char *), but will generate compiler error
}
calling function my_func(char *)
We can use the nullptr at all places where NULL is expected. Like the NULL, the nullptr also can be converted into any pointer type. But this is not implicitly convertible to integral type like NULL.
C# Program to create a Simple Thread

To create a thread, I have created a function −
public void myThread() {
   for (int i = 0; i < 3; i++) {
      Console.WriteLine("My Thread");
   }
}
The above function is called to create a thread and a new ThreadStart delegate is created −
Demo d = new Demo();
Thread thread = new Thread(new ThreadStart(d.myThread));
Create a simple thread using the following code.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
class Demo {
   public void myThread() {
      for (int i = 0; i < 3; i++) {
         Console.WriteLine("My Thread");
      }
   }
}
class NewThread {
   public static void Main() {
      Demo d = new Demo();
      Thread thread = new Thread(new ThreadStart(d.myThread));
      thread.Start();
      Console.Read();
   }
}
My Thread
My Thread
My Thread
How do I verify that an element does not exist in Selenium 2?

We can verify if an element does not exist in Selenium webdriver. To achieve this, we shall use the method getPageSource which gets the entire page source. So we can obtain a complete page source and check if the text of the element exists.
We also use the findElements method and utilize any locators like xpath, CSS, and so on to identify the matching elements. The findElements gives an elements list.
We shall count the number of elements returned by the list with the help of the size method. If the value of size is greater than 0, then the element exists and if it is lesser than 0, then the element does not exist.
Let us verify if the highlighted text is present on the page −
Code Implementation with findElements().
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ExistElements{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      String str = "You are browsing the best resource for Online Education";
      // identify elements
      List<WebElement> m= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
      // verify size
      if ( m.size() > 0){
         System.out.println("Text: " + str + " is present. ");
      }
      else{
         System.out.println("Text: " + str+ " is not present. ");
      }
      driver.quit();
   }
}
Code Implementation with getPageSource.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ElementExistPgSource{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      String str = "You are browsing the best resource for Online Education";
      //get page source
      if ( driver.getPageSource().contains("You are browsin")){
         System.out.println("Text: " + str + " is present. ");
      }
      else{
         System.out.println("Text: " + str + " is not present. ");
      }
      driver.quit();
   }
}
Python VLC Instance – Setting Application Name

29 Aug, 2020
In this article we will see how we can set the application name from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can create media player, list player or any other player available in VLC. Instance class the base classed used in VLC to create various objects. LibVLC passes name as the user agent string when a protocol requires it.
In order to do this we will use set_user_agent method with the Instance object
Syntax : instance.set_user_agent(name, http)
Argument : It takes name and http agent as argument
Return : It returns None
Below is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating Instance class objectplayer = vlc.Instance()  # setting application nameplayer.set_user_agent("GFG", "GFG / Python / 3.6")    # creating a new media listmedia_list = player.media_list_new()  # creating a media player objectmedia_player = player.media_list_player_new()  # creating a new mediamedia = player.media_new("death_note.mkv")  # adding media to media listmedia_list.add_media(media)  # setting media list to the mediaplayermedia_player.set_media_list(media_list)    # start playing videomedia_player.play()    # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output :
Another exampleBelow is the implementation
# importing vlc moduleimport vlc  # importing time moduleimport time  # creating Instance class objectplayer = vlc.Instance()  # setting application nameplayer.set_user_agent("GFG-2", "GFG-2 / Python / 3.6")    # creating a new media listmedia_list = player.media_list_new()  # creating a media player objectmedia_player = player.media_list_player_new()  # creating a new mediamedia = player.media_new("1.mp4")  # adding media to media listmedia_list.add_media(media)  # setting media list to the mediaplayermedia_player.set_media_list(media_list)    # start playing videomedia_player.play()    # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output :
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is isELIgnored Attribute in JSP?

The isELIgnored attribute gives you the ability to disable the evaluation of Expression Language (EL) expressions which has been introduced in JSP 2.0.
The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.
Following directive sets an expression not to be evaluated −
<%@ page isELIgnored = "false" %>
Python – Remove words containing list characters

01 Mar, 2020
Sometimes, in the process of data filtering we have a problem in which we need to remove words which are composite of certain letters. This kind of application is common in data science domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using all() + list comprehensionThe combination of above methods can be used to perform this task. In this, we just check for all list characters using all() in each list and filters out string which has any one of characters.
# Python3 code to demonstrate # Remove words containing list characters# using list comprehension + all()from itertools import groupby  # initializing list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # initializing char list char_list = ['g', 'o']  # printing original listprint ("The original list is : " + str(test_list))  # printing character listprint ("The character list is : " + str(char_list))  # Remove words containing list characters# using list comprehension + all()res = [ele for ele in test_list if all(ch not in ele for ch in char_list)]  # printing result print ("The filtered strings are : " + str(res))
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
The character list is : ['g', 'o']
The filtered strings are : ['is', 'best']

 
Method #2 : Using loopThis is brute method in which this task can be performed. In this we use loop and conditional statements to perform this task.
# Python3 code to demonstrate # Remove words containing list characters# using loopfrom itertools import groupby  # initializing list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # initializing char list char_list = ['g', 'o']  # printing original listprint ("The original list is : " + str(test_list))  # printing character listprint ("The character list is : " + str(char_list))  # Remove words containing list characters# using loopres = []flag = 1for ele in test_list:    for idx in char_list:        if idx not in ele:            flag = 1        else:            flag = 0              break    if(flag == 1):        res.append(ele)    # printing result print ("The filtered strings are : " + str(res))
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
The character list is : ['g', 'o']
The filtered strings are : ['is', 'best']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Multidimensional Arrays in Scala

10 Mar, 2019
Multidimensional Array is basically an array storing the data in matrix format. For, matrices and table we need multidimensional array. We can create multidimensional array by using Array.ofDim and Array of Array method. Syntax
val arrayname = Array.ofDim[data_type](number of rows, number of cols)orvar arrayname = Array(Array(elements), Array(elements))
 
Scala has a method Array.ofDim to create a multidimensional array. This approach can be used to create arrays of up to five dimensions. Required we need to know the number of rows and columns at creation time. After declaring the array, we add elements to it .Example:
// Scala Program of Multidimensional array // using Array.ofDimobject MultiArr{    def main(args: Array[String])    {        //creating the array of 2 rows and 2 columns        val mymultiarr= Array.ofDim[Int](2, 2)               //Assigning the values        mymultiarr(0)(0) = 2                         mymultiarr(0)(1) = 7        mymultiarr(1)(0) = 3        mymultiarr(1)(1) = 4              for(i<-0 to 1; j<-0 until 2)        {            print(i, j)                     //Accessing the elements           println("=" + mymultiarr(i)(j))             }    }}
Output
(0,0)=2
(0,1)=7
(1,0)=3
(1,1)=4
 
This gives more control of the process and lets us create “ragged” arrays (where each contained array may be a different size). We can also create a multidimensional array by using Array of Array. In the example below, we have created a multidimensional array using Array of Array.
Example:
// Scala Program of Multidimensional array // using Array of Arrayobject MultiArr{    def main(args: Array[String])    {        // Creating and assigning the values         // to the array        var arr= Array(Array(0, 2, 4, 6, 8),                    Array(1, 3, 5, 7, 9))           for(i<-0 to 1)        {            for(j<- 0 to 4)            {                // Accessing the values                print(" "+arr(i)(j))             }            println()        }    }}
Output:
 0 2 4 6 8
 1 3 5 7 9
Now, let us consider an example showing the element with (row, column)Example:
// Scala Program of Multidimensional array // using Array of Arrayobject Mad{    def main(args: Array[String])    {              // Creating and assigning the values to the array        var arr= Array(Array(0, 2, 4, 6, 8),                     Array(1, 3, 5, 7, 9))               for(i<-0 to 1; j<-0 until 5)        {            print(i, j)                          //Accessing the elements            println("=" + arr(i)(j))         }    }}
Output:
(0,0)=0
(0,1)=2
(0,2)=4
(0,3)=6
(0,4)=8
(1,0)=1
(1,1)=3
(1,2)=5
(1,3)=7
(1,4)=9
Scala-Arrays
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Scala
Type Casting in Scala
Scala | yield Keyword
Scala | Functions - Basics
Throw Keyword in Scala
Method Overloading in Scala
Class and Object in Scala
Tail Recursion in Scala
Scala | Traits
Hello World in Scala
Throwable getCause() method in Java with Examples

06 Feb, 2019
The getCause() method of Throwable class is the inbuilt method used to return the cause of this throwable or null if cause can’t be determined for the Exception occurred. This method help to get the cause that was supplied by one of the constructors or that was set after creation with the initCause(Throwable) method. All the PrintStackTrace methods of Throwable class invoke getCause() method to determine the cause of the Throwable or Exception. In simple terms, it can be said that this method returns the cause because of which Exception occurred.
Syntax:
public Throwable getCause()
Return Value: This method returns the cause of this Throwable or null if cause can’t be determined.
Below programs demonstrate the getCause() method of Throwable Class:
Example 1:
// Java program to demonstrate// the ensureCapacity() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {              // divide the numbers            divide(2, 0);        }          catch (ArithmeticException e) {              System.out.println("Cause of Exception: "                               + e.getCause());        }    }      // method which divides two number    public static void divide(int a, int b)        throws Exception    {          try {              // divide two numbers            int i = a / b;        }          catch (ArithmeticException e) {              // initializing new Exception with cause            ArithmeticException exe = new ArithmeticException();              exe.initCause(e);              throw(exe);        }    }}
Cause of Exception: java.lang.ArithmeticException: / by zero

Example 2:
// Java program to demonstrate// the ensureCapacity() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {              // divide the numbers            divide(2, 0);        }          catch (ArithmeticException e) {              System.out.println("Cause of Exception : "                               + e.getCause());        }    }      // method which divides two number    public static void divide(int a, int b)        throws Exception    {          // divide two numbers        int i = a / b;    }}
Cause of Exception : null

References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getCause()
Java-Exception Handling
Java-Exceptions
Java-Functions
Java-lang package
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
Switch Case in JavaScript

20 Jun, 2022
We have learned about decision-making in JavaScript using if-else statements in our previous article on if-else statements in JavaScript. We have seen in our previous article that we can use the if-else statements to perform actions based on some particular condition. That is if a condition is true then perform some task or else if the condition is false then execute some other task. The switch case statement in JavaScript is also used for decision-making purposes. In some cases, using the switch case statement is seen to be more convenient than if-else statements. Consider a situation when we want to test a variable for hundred different values and based on the test we want to execute some task. Using if-else statements for this purpose will be less efficient than switch-case statements and also it will make the code look messy.The switch case statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.Syntax:  
switch (expression)
{
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    .
    .
    case valueN:
        statementN;
        break;
    default:
        statementDefault;
}
Explanation:  
expression can be of type numbers or strings.
Duplicate case values are not allowed.
The default statement is optional. If the expression passed to switch does not match with the value in any case then the statement under default will be executed.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional. If omitted, execution will continue on into the next case.
Cases are compared strictly.
Flowchart:  
Example:  
JavaScript
<script type = "text/javascript">     // JavaScript program to illustrate switch-case    let i = 9;       switch (i)     {       case 0:           console.log("i is zero.");           break;       case 1:           console.log("i is one.");           break;       case 2:           console.log("i is two.");           break;       default:           console.log("i is greater than 2.");    } </script>
Output:  
i is greater than 2.
 
immukul
sagar0719kumar
farzams101
javascript-basics
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to rename a username in MongoDB?

To rename a user, you need to use update() and $set to set the new username. Following is the syntax −
db.system.users.update({"user":"yourOldUserName"}, {$set:{"user":"yourNewUserName"}});
Firstly, display all the users from the MongoDB database −
> use admin;
switched to db admin

> db.getUsers();
This will produce the following output −
[
   {
      "_id" : "admin.Chris",
      "user" : "Chris",
      "db" : "admin",
      "roles" : [
         {
            "role" : "readWrite",
            "db" : "test"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   },
   {
      "_id" : "admin.John",
      "user" : "John",
      "db" : "admin",
      "roles" : [
         {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   },
   {
      "_id" : "admin.Robert",
      "user" : "Robert",
      "db" : "admin",
      "roles" : [
         {
            "role" : "readWrite",
            "db" : "sample"
         }
      ],
      "mechanisms" : [
         "SCRAM-SHA-1",
         "SCRAM-SHA-256"
      ]
   }
]
Now rename user name from ‘John’ to ‘Larry’ −
> db.system.users.update({"user":"John"}, {$set:{"user":"Larry"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us verify the user has been created with name ‘Larry’ or not using getUser() −
> db.getUser('Larry');
This will produce the following output −
{
   "_id" : "admin.John",
   "user" : "Larry",
   "db" : "admin",
   "roles" : [
      {
         "role" : "userAdminAnyDatabase",
         "db" : "admin"
      }
   ],
   "mechanisms" : [
      "SCRAM-SHA-1",
      "SCRAM-SHA-256"
   ]
}
If you will now try to get older user name then a null value will be displayed. Let us see the same −
> db.getUser('John');
This will produce the following output −
Null