code-rag-bench/online-tutorials huggingface dataset:
Remove the last entry of the TreeMap in Java

To remove the last entry of the TreeMap, use the pollLastEntry() method.
Let us first create a TreeMap and add elements
TreeMap<Integer, String> m = new TreeMap<Integer, String>();
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");
Remove the last entry now
m.pollLastEntry()
The following is an example to remove the last entry of the TreeMap
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeMap<Integer, String> m = new TreeMap<Integer, String>();
      m.put(1,"India");
      m.put(2,"US");
      m.put(3,"Australia");
      m.put(4,"Netherlands");
      m.put(5,"Canada");
      System.out.println("TreeMap Elements = "+m);
      System.out.println("Removing Last Entry : "+m.pollLastEntry());
      System.out.println("Updated TreeMap Elements = "+m);
   }
}
The following is the output
TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands, 5=Canada}
Removing Last Entry : 5=Canada
Updated TreeMap Elements = {1=India, 2=US, 3=Australia, 4=Netherlands}
How to delete cookies in JavaScript?

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiry date to a time in the past.
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one month behind the current date.
<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               var now = new Date();
               now.setMonth( now.getMonth() - 1 );
               cookievalue = escape(document.myform.customer.value) + ";"

               document.cookie="name=" + cookievalue;
               document.cookie = "expires=" + now.toUTCString() + ";"
               document.write("Setting Cookies : " + "name=" + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         Enter name: <input type="text" name="customer"/>
         <input type="button" value="Set Cookie" onclick="WriteCookie()"/>
      </form>
   </body>
</html>
Python | Pandas Series.squeeze()

05 Feb, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.squeeze() function squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged.
Syntax: Series.squeeze(axis=None)
Parameter :axis : A specific axis to squeeze. By default, all length-1 axes are squeezed.
Returns : Projection after squeezing axis or all the axes.
Example #1 : Use Series.squeeze() function to squeeze the single element of the given series to scalar.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65])  # Print the seriesprint(sr)
Output :
Let’s transform the series in a way that it only contains those elements which are divisible by 13.
# Keep only those elements which are divisible by 13sr_temp = sr[sr % 13 == 0]  # Let's print the seriesprint(sr_temp)
Output :
Now we will use Series.squeeze() function to reduce the given series object to a scalar.
# squeeze the series to scalarsr_temp.squeeze()
Output :As we can see in the output, Series.squeeze() function has successfully reduced the given series to a scalar. Example #2 : Use Series.squeeze() function to squeeze the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.std() function to squeeze the given series object.
# squeeze the series to scalarsr_temp.squeeze()
Output :
As we can see in the output, Series.squeeze() function has returned the same series object because there are more than one elements in the given series object and hence it could not be squeezed to a scalar value.
Python pandas-series
Python pandas-series-methods
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 ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python program to find the sum of all items in a dictionary

13 Apr, 2022
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary.
Examples: 
Input : {‘a’: 100, ‘b’:200, ‘c’:300}Output : 600
Input : {‘x’: 25, ‘y’:18, ‘z’:45}Output : 88
Approach #1 : Using Inbuilt sum() FunctionUse the sum function to find the sum of dictionary values.
Python3
# Python3 Program to find sum of# all items in a Dictionary # Function to print sum  def returnSum(myDict):     list = []    for i in myDict:        list.append(myDict[i])    final = sum(list)     return final  # Driver Functiondict = {'a': 100, 'b': 200, 'c': 300}print("Sum :", returnSum(dict))
Sum : 600

Approach #2 : Using For loop to iterate through values using values() functionIterate through each value of the dictionary using values() function and keep adding it to the sum. 
Python3
# Python3 Program to find sum of# all items in a Dictionary # Function to print sum  def returnSum(dict):     sum = 0    for i in dict.values():        sum = sum + i     return sum  # Driver Functiondict = {'a': 100, 'b': 200, 'c': 300}print("Sum :", returnSum(dict))
Sum : 600

Approach #3: Using For loop to iterate through items of DictionaryIterate through each item of the dictionary and simply keep adding the values to the sum variable. 
Python3
# Python3 Program to find sum of# all items in a Dictionary # Function to print sum  def returnSum(dict):     sum = 0    for i in dict:        sum = sum + dict[i]     return sum  # Driver Functiondict = {'a': 100, 'b': 200, 'c': 300}print("Sum :", returnSum(dict))
Sum : 600

Approach #4 : Using dictionary.sum() method to find the sum of values taken out through dictionary.values() function.
Python3
# Python3 Program to find sum of# all items in a Dictionary # Function to print sum  def returnSum(dict):    return sum(dict.values())  # Driver Functiondict = {'a': 100, 'b': 200, 'c': 300}print("Sum :", returnSum(dict))
Sum : 600

ashrithpradeep
apurvkumar408
dongrimohammedafreed
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
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 Program for Fibonacci numbers
Properties isEmpty() method in Java with Examples

23 May, 2019
The isEmpty() method of Properties class is used to check if this Properties object is empty or not.
Syntax:
public boolean isEmpty()
Parameters: This method accepts no parameters
Returns: This method returns a boolean value stating if this Properties object is empty or not.
Below programs show the implementation of int isEmpty() method.
Program 1:
// Java code to show the implementation of// isEmpty method  import java.util.*;public class GfG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();        properties.put("Pen", 10);        properties.put("Book", 500);        properties.put("Clothes", 400);        properties.put("Mobile", 5000);          // Print Properties details        System.out.println("Properties: "                           + properties.toString());          // Checking if the Properties is empty        System.out.println("Is Properties empty: "                           + properties.isEmpty());    }}
Properties: {Book=500, Mobile=5000, Pen=10, Clothes=400}
Is Properties empty: false

Program 2:
// Java program to demonstrate// isEmpty() method.  import java.util.*;  public class GFG {      // Main method    public static void main(String[] args)    {          // Create a properties and add some values        Properties properties = new Properties();          // Print Properties details        System.out.println("Current Properties: "                           + properties.toString());          // Checking if the Properties is empty        System.out.println("Is Properties empty: "                           + properties.isEmpty());    }}
Current Properties: {}
Is Properties empty: true

References: https://docs.oracle.com/javase/9/docs/api/java/util/Properties.html#isEmpty–
nidhi_biet
Java - util package
Java-Functions
Java-Properties
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
jQuery UI Datepicker setDate() Method

08 Jan, 2021
jQuery UI datepicker setDate() method is used to set the date from the date field.
Syntax:
$( ".selector" ).datepicker( "setDate" )
Parameters: This method does not accept any parameters.
Return values: This method returns the date.
Approach: First, add jQuery mobile scripts needed for your project.
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js”></script><script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js”></script><link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css” rel=”stylesheet” type=”text/css” />
Example 1:
HTML
<!doctype html><html lang = "en">   <head>    <meta charset="utf-8">     <meta name="viewport" content=         "width=device-width, initial-scale=1">       <script src=      "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">     </script>       <script src=      "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js">     </script>       <link href=       "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css"       rel="stylesheet" type="text/css" />         <script>         $(function() {            $( "#datepicker" ).datepicker();            $( "#datepicker" ).datepicker("setDate","06/01/21");         });      </script>   </head>        <body>      <p>Date: <input type = "text"          id = "datepicker"></p>   </body></html>
 
Output:
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
HTTP headers | Proxy-Authorization

31 Oct, 2019
The HTTP Proxy_Authorization header is a request type of header. This header contains the credentials to authenticate between the user agent and the user-specified server. When the server responded with 407 proxy Authentication Required status that brings the authentication between the user agent and the server.
Syntax:
Proxy-Authorization: <type> <credentials>
Directives: This header accepts two directives as mentioned above and described below:
<type>: This directive tells the type of authentication. The common type is the “Basic”.
<credentials>: This is the base64 encoded resulting string. The credentials constructed like username and password are combined with a colon like (Username:password).
Example:
Proxy-Authorization: Basic 6dc7dbfe151046f2be8fc383a9abb147
This example has Proxy-Authorization which has the type Basic and the credentials as the above.
To check this Proxy-Authorization in action go to Inspect Element -> Network check the request header for Proxy-Authorization.
Supported Browsers The browsers compatible with HTTP Proxy-Authorization header are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby Mixins

21 Nov, 2019
Before studying about Ruby Mixins, we should have the knowledge about Object Oriented Concepts. If we don’t, go through Object Oriented Concepts in Ruby . When a class can inherit features from more than one parent class, the class is supposed to have multiple inheritance. But Ruby does not support multiple inheritance directly and instead uses a facility called mixin. Mixins in Ruby allows modules to access instance methods of another one using include method.Mixins provides a controlled way of adding functionality to classes. The code in the mixin starts to interact with code in the class. In Ruby, a code wrapped up in a module is called mixins that a class can include or extend. A class consist many mixins.
Below is the example of Ruby Mixins.Example #1:
# Ruby program of mixins  # module consist 2 methodsmodule G    def g1   end   def g2   endend  # module consist 2 methodsmodule GFG   def gfg1   end   def gfg2   endend  # Creating a classclass GeeksforGeeksinclude Ginclude GFG   def s1   endend  # Creating objectgfg = GeeksforGeeks.new  # Calling methodsgfg.g1gfg.g2gfg.gfg1gfg.gfg2gfg.s1
Here, module G consists of the methods g1 and g2. Module GFG consists of the methods gfg1 and gfg2. The class GeeksforGeeks includes both modules G and GFG. The class GeeksforGeeks can access all four methods, namely, g1, g2, gfg1, and gfg2. Therefore, we can see that the class GeeksforGeeks inherits from both the modules. Thus, we can say the class GeeksforGeeks shows mixin.
Consider the example below for elucidation.Example #2:
# Modules consist a methodmodule Child_1  def a1   puts 'This is Child one.'  endendmodule Child_2  def a2   puts 'This is Child two.'  endendmodule Child_3  def a3   puts 'This is Child three.'  endend  # Creating classclass Parent  include Child_1  include Child_2  include Child_3  def display   puts 'Three modules have included.'  endend  # Creating objectobject = Parent.new  # Calling methodsobject.displayobject.a1object.a2object.a3
Output
Three modules have included.
This is Child one.
This is Child two.
This is Child three.

In above example, module Child_1 consist of the method a1 similarly module Child_2 and Child_3 consist of the methods a2 and a3. The class Parent includes modules Child_1, Child_2 and Child_3 . The class Parent also include a method display. As we can see that the class Parent inherits from all three modules. the class Parent shows multiple inheritance or mixin.
Picked
Ruby modules
Ruby
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Export Plot to EPS File in R

16 May, 2021
An EPS file is a graphics file saved in the Encapsulated PostScript (EPS) file format. The EPS files may contain images, graphics, or even text. In this article, we will discuss how we export a plot to an EPS file using R programming language.
The postscripts can be defined using the setEPS() method in R. postscript initiates the graphics device driver for producing PostScript graphics. The eps file is stored in the current working directory by default. To save it to a specific location specify the full destination path along with the name of the file in postscript() function.
Example: 
R
# declaring the xpos vector xpos <- c(1:10)  # declaring the ypos vector # equivalent to x^2ypos <- xpos^2  setEPS()  # naming the eps filepostscript("gfg.eps")  # plotting the x and y position# vectorsplot(xpos,ypos)dev.off()
Output
The ggplot library can be installed and loaded into the working space to work with graphics.The ggplot() method in this package is used to visualize data in the form of scatter plots, boxplots, and time series plots. This method is fed the data in the form of data points, and then a scatter plot is displayed. In this function, an aesthetic mapping(aes) is deployed by selecting the variables x and y and further customized by the addition of a graphical representation of data in the form of points using the geom_point() method in the graph. The plot can be saved in the eps format using the ggplot.save() method, which takes as argument the string name of the plot. 
Example:
R
# loading the required librarieslibrary("ggplot2")  # declaring the xpos vector xpos <- 1:10  # declaring the ypos vector equivalent # to x^2ypos <- xpos^2  # declaring the data using x and y # position vectorsdata_frame <- data.frame(x = xpos,                          y = ypos)# plotting the dataggplot(data_frame, aes(x, y)) + geom_point()  # save the eps plotggplot.save("gfg.eps")
Output
Picked
R-Charts
R-Graphs
R-plots
R Language
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
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
What is the difference between YAML and JSON?

17 May, 2020
YAML: It is a light-weight, human-readable data-representation language. It is primarily designed to make the format easy to read while including complex features. Since YAML is a superset of JSON, it can parse JSON with a YAML parser.The extensions in YAML are .yaml or .yml. YAML specifications allow user-defined data types as well as explicit data typing.
The most common data types used in YAML are :
Numbers
Strings
Null values
Boolean
Dates and timestamps
Sequences
Nested values
Example:
Origin:
   author: Dan Brown
   language: English
   publication-date: 2017-10-03
   pages: 461
   description: | When billionaire researcher Edmond Kirsch is killed, 
                  it is up to Robert Langdon & Ambra Vidal to honor 
                  his memory by making public his findings concerning the 
                  origin of human life and its destiny.

JSON: It is a language-independent, human-readable language used for its simplicity and is most commonly used in web based applications.The JSON extensions end with a .json. JSON is a user-friendly substitute to XML as it is light weight and easy to read.
Some of the valid data types used in JSON are:
Numbers
Strings
Objects
Arrays
Example:
{
  "Origin": {
    "author": "Dan Brown",
    "language": "English",
     "publication-date": "2017-10-03",
     "pages": 461,
     "description": "When billionaire researcher Edmond Kirsch is killed, 
                     it is up to Robert Langdon and Ambra Vidal to honor
                     his memory  by making public his findings concerning 
                     the origin of human life and its destiny."
  }
}

Differences between YAML and JSON are:
JSON
Picked
Difference Between
Web Technologies
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl vs C/C++

29 Jun, 2021
Perl is a general purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official acronym for the Perl, but still, the most used acronym is “Practical Extraction and Reporting Language“. Some of the programmers also refer to Perl as the “Pathologically Eclectic Rubbish Lister” Or “Practically Everything Really Likable“. The acronym “Practical Extraction and Reporting Language” is used widely because Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. It supports both procedural and Object-Oriented programming.C++ is a general purpose programming language and widely used now a days for competitive programming. It has imperative, object-oriented and generic programming features. C++ runs on lots of platform like Windows, Linux, Unix, Mac etc.Below are some major differences between Perl and c/c++: 
 
Program for addition of two numbers in C++ and Perl  
C++
Perl
// C++ program to add two numbers#include <stdio.h> // Function to perform addition// operationint add(int x, int y){    int res = x + y;    return res;} // Driver Codeint main(){    int choice = 3;    int choice2 = 5;     int res = add(choice, choice2);    printf("The result is %d", res);    return 0;}
#!/usr/bin/perl # Perl program to add two numbers$choice = 3;$choice2 = 5;$res = add($choice, $choice2);print "The result is $res"; # Subroutine to perform# addition operationsub add{    ($x, $y) = @_;    $res = $x + $y;    return $res;}
Output:  
The result is 8
 
perl-basics
Picked
C++
Difference Between
Perl
Perl
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Access Global Variable if there is a Local Variable with Same Name in C/ C++?

21 Jun, 2022
Local Variable: The variable whose scope lies inside a function or a block in which they are declared. 
Global Variable: The variable that exists outside of all functions. It is the variable that is visible from all other scopes.
We can access global variable if there is a local variable with same name in C and C++ through Extern and Scope resolution operator respectively.
1) We can access a global variable if we have a local variable with same name in C using extern. 
C
// C Program to demonstrate that we can access a global// variable if we have a local variable with same name#include <stdio.h> // Global variable xint x = 50; int main(){    // Local variable x    int x = 10;    {        extern int x;        printf("Value of global x is %d\n", x);    }    printf("Value of local x is %d\n", x);    return 0;}
Value of global x is 50
Value of local x is 10
Time Complexity: O(1)
Auxiliary Space: O(1)
2) We can access a global variable if we have a local variable with the same name in C++ using Scope resolution operator (::). 
C++
// C++ Program to demonstrate that We can access a global// variable if we have a local variable with same name in// C++ using Scope resolution operator (::)#include <iostream>using namespace std; // Global variable xint x = 50; int main(){    // Local variable x    int x = 10;    cout << "Value of global x is " << ::x << endl;    cout << "Value of local x is " << x;    getchar();    return 0;}
Value of global x is 50
Value of local x is 10
Time Complexity: O(1)
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.  
mharshita31
scorchingeagle
anshikajain26
tarakki100
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
Templates in C++ with Examples
Operator Overloading in C++
Inheritance in C++
Random sampling in numpy | randint() function

26 Feb, 2019
numpy.random.randint() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random integers from low (inclusive) to high (exclusive), i.e. in the interval [low, high).
Syntax : numpy.random.randint(low, high=None, size=None, dtype=’l’)
Parameters :low : [int] Lowest (signed) integer to be drawn from the distribution.But, it works as a highest integer in the sample if high=None.high : [int, optional] Largest (signed) integer to be drawn from the distribution.size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.dtype : [optional] Desired output data-type.
Return : Array of random integers in the interval [low, high) or a single such random int if size not provided.
Code #1 :
# Python program explaining# numpy.random.randint() function  # importing numpyimport numpy as geek  # output arrayout_arr = geek.random.randint(low = 0, high = 3, size = 5)print ("Output 1D Array filled with random integers : ", out_arr) 
Output 1D Array filled with random integers :  [1 1 0 1 1]

 
Code #2 :
# Python program explaining# numpy.random.randint() function  # importing numpyimport numpy as geek    # output arrayout_arr = geek.random.randint(low = 4, size =(2, 3))print ("Output 2D Array filled with random integers : ", out_arr) 
Output 2D Array filled with random integers :  [[1 1 0]
 [1 0 3]]

 Code #3 :
# Python program explaining# numpy.random.randint() function  # importing numpyimport numpy as geek  # output arrayout_arr = geek.random.randint(2, 10, (2, 3, 4))print ("Output 3D Array filled with random integers : ", out_arr) 
Output 3D Array filled with random integers :  [[[4 8 5 7]
  [6 5 6 7]
  [4 3 4 3]]

 [[2 9 2 2]
  [3 2 2 3]
  [6 8 3 2]]]

Python numpy-Random sampling
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
How To Index and Slice Strings in Python?

27 Apr, 2022
The Python string data type is a sequence made up of one or more individual characters that could consist of letters, numbers, whitespace characters, or symbols. As the string is a sequence, it can be accessed in the same ways that other sequence-based data types are, through indexing and slicing.
Indexing means referring to an element of an iterable by its position within the iterable. Each of a string’s characters corresponds to an index number and each character can be accessed using its index number. We can access characters in a String in Two ways :
Accessing Characters by Positive Index NumberAccessing Characters by Negative Index Number
Accessing Characters by Positive Index Number
Accessing Characters by Negative Index Number
1. Accessing Characters by Positive Index Number: In this type of Indexing, we pass a Positive index(which we want to access) in square brackets. The index number starts from index number 0 (which denotes the first character of a string).
Indexing in Python
Example 1 (Positive Indexing) : 
python3
# declaring the stringstr = "Geeks for Geeks !" # accessing the character of str at 0th indexprint(str[0]) # accessing the character of str at 6th indexprint(str[6]) # accessing the character of str at 10th indexprint(str[10])
G
f
G
2. Accessing Characters by Negative Index Number: In this type of Indexing, we pass the Negative index(which we want to access) in square brackets. Here the index number starts from index number -1 (which denotes the last character of a string). Example 2 (Negative Indexing) : 
python3
# declaring the stringstr = "Geeks for Geeks !" # accessing the character of str at last indexprint(str[-1]) # accessing the character of str at 5th index from the lastprint(str[-5]) # accessing the character of str at 10th index from the lastprint(str[-10])
!
e
o
Slicing in Python is a feature that enables accessing parts of the sequence. In slicing a string, we create a substring, which is essentially a string that exists within another string. We use slicing when we require a part of the string and not the complete string. Syntax :
string[start : end : step]
start : We provide the starting index.
end : We provide the end index(this is not included in substring).
step : It is an optional argument that determines the increment between each index for slicing.
Example 1 : 
python3
# declaring the stringstr ="Geeks for Geeks !" # slicing using indexing sequenceprint(str[: 3])print(str[1 : 5 : 2])print(str[-1 : -12 : -2])
Gee
ek
!seGrf
Example 2 : 
python3
# declaring the stringstr ="Geeks for Geeks !" print("Original String :-")print(str) # reversing the string using slicingprint("Reverse String :-")print(str[: : -1])
Original String :-
Geeks for Geeks !
Reverse String :-
! skeeG rof skeeG
harendrakumar123
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Draw a horizontal bar chart with Matplotlib

25 Aug, 2021
Matplotlib is the standard python library for creating visualizations in Python. Pyplot is a module of Matplotlib library which is used to plot graphs and charts and also make changes in them. In this article, we are going to see how to draw a horizontal bar chart with Matplotlib.
Approach:
Importing matplotlib.pyplot as plt
Creating list x for discrete values on x-axis
Creating list y  consisting only numeric data for discrete values on y-axis
Calling plt.bar() function with parameters x,y as plt.bar(x,y)
Setting x_label() and y_label()
Setting title() for our bar chart
Calling plt.show() for visualizing our chart
Below is the implementation:
Python3
import matplotlib.pyplot as plt x=['one', 'two', 'three', 'four', 'five'] # giving the values against# each value at x axisy=[5, 24, 35, 67, 12]plt.bar(x, y) # setting x-label as pen soldplt.xlabel("pen sold") # setting y_label as priceplt.ylabel("price")  plt.title(" Vertical bar graph")plt.show()
Output:
Approach:
Importing matplotlib.pyplot as plt
Creating list y   for discrete values on y-axis
Creating list x  consisting only numeric data for discrete values on x-axis
Calling plt.barh() function with parameters y,x as plt.barh(y,x)
Setting x_label() and y_label()
Setting title() for our bar chart
Calling plt.show() for visualizing our chart
Below is the implementation:
Python3
import matplotlib.pyplot as plty=['one', 'two', 'three', 'four', 'five'] # getting values against each value of yx=[5,24,35,67,12]plt.barh(y, x) # setting label of y-axisplt.ylabel("pen sold") # setting label of x-axisplt.xlabel("price")plt.title("Horizontal bar graph")plt.show()
Output:
saurabh1990aror
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install SQLmap on Android Termux?

29 Dec, 2021
Sqlmap is an open-source penetration testing tool. It comes with a powerful detection engine. It automates the process of detecting & taking over the database server. There is a total of six SQL injection tool techniques are present. This is the highest amount of tool present than others. When we are going to extract the password from a vulnerable database, often the passwords are in hash form. It can detect the hash & can mention which type of hash was that.
Follow the below steps to install SQLmap on Android using Termux:
Step 1: Open Termux & execute the below command:
apt update&&upgrade
Step 2: Now list the files in the directory using the below command:
 ls
Step 3: Now use the below command to install sqlmap:
python2 sqlmap.py
It will give the following output:
Hence, your installation is successful.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
Getting unique values within two arrays in one MongoDB document

To get unique values within two arrays in a document, use a $setUnion in aggregate(). The $setUnion takes two or more arrays and returns an array containing the elements that appear in any input array.
Let us create a collection with documents −
>db.demo608.insertOne({"ListOfName1":["John","Chris","Bob","David"],"ListOfName2":["Bob", "Sam","John","Robert","Chris"]}
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e974542f57d0dc0b182d62b")
}
Display all documents from a collection with the help of find() method −
> db.demo608.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e974542f57d0dc0b182d62b"),
   "ListOfName1" : [
      "John",
      "Chris",
      "Bob",
      "David"
   ],
   "ListOfName2" : [
      "Bob",
      "Sam",
      "John",
      "Robert",
      "Chris"
   ]
}
Following is the query to get unique values within two arrays in one MongoDB document −
> db.demo608.aggregate([
...    {$project:{SetOfNames:{$setUnion:['$ListOfName1','$ListOfName2']}}}
... ]).pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e974542f57d0dc0b182d62b"),
   "SetOfNames" : [
      "Bob",
      "Chris",
      "David",
      "John",
      "Robert",
      "Sam"
   ]
}
Python | Check if given multiple keys exist in a dictionary

11 May, 2020
A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value.
Input : dict[] = {“geeksforgeeks” : 1, “practice” : 2, “contribute” :3}keys[] = {“geeksforgeeks”, “practice”}Output : Yes
Input : dict[] = {“geeksforgeeks” : 1, “practice” : 2, “contribute” :3}keys[] = {“geeksforgeeks”, “ide”}Output : No
Let’s discuss various ways of checking multiple keys in a dictionary :
Method #1 Using comparison operator :This is the common method where we make a set which contains keys that use to compare and using comparison operator we check if that key present in our dictionary or not.
# Python3 code to check multiple key existence# using comparison operator  # initializing a dictionarysports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}  # using comparison operatorprint(sports.keys() >= {"geeksforgeeks", "practice"})print(sports.keys() >= {"contribute", "ide"})
True
False

Method #2 Using issubset() :In this method, we will check the keys that we have to compare is subset() of keys in our dictionary or not.
# Python3 code heck multiple key existence# using issubset  # initializing a dictionarysports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}  # creating set of keys that we want to compares1 = set(['geeksforgeeks', 'practice'])s2 = set(['geeksforgeeks', 'ide'])  print(s1.issubset(sports.keys()))print(s2.issubset(sports.keys()))
True
False

Method #3 Using if and all statement :In this method we will check that if all the key elements that we want to compare are present in our dictionary or not .
# Python3 code check multiple key existence# using if and all  # initializing a dictionarysports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}  # using if, all statement if all(key in sports for key in ('geeksforgeeks', 'practice')):    print("keys are present")else:    print("keys are not present")  # using if, all statement if all(key in sports for key in ('geeksforgeeks', 'ide')):    print("keys are present")else:    print("keys are not present")
keys are present
keys are not present

Picked
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Convert a Data Frame into a Molten Form in R Programming – melt() Function

17 Jun, 2020
function in R Language is used to combine multiple columns of s Data Frame into a single column.
Syntax: melt(x, na.rm, value.name)
Parameters:x: data to be meltedna.rm: Boolean value to remove NAvalue.name: Setting column names
Example 1:
# R program to reshape data frame  # Loading librarylibrary(reshape)   # Creating a data framea <- data.frame(id = c("1", "1", "2", "2"),                 points = c("1", "2", "1", "2"),                 x1 = c("5", "3", "6", "2"),                 x2 = c("6", "5", "1", "4")) a  # Calling melt() Functionm <- melt(a, id = c("id", "points")) print(m) 
Output:
  id points x1 x2
1  1      1  5  6
2  1      2  3  5
3  2      1  6  1
4  2      2  2  4
  id points variable value
1  1      1       x1     5
2  1      2       x1     3
3  2      1       x1     6
4  2      2       x1     2
5  1      1       x2     6
6  1      2       x2     5
7  2      1       x2     1
8  2      2       x2     4

Example 2:
# R program to reshape data frame  # Loading librarylibrary(reshape2)   # Calling pre-defined data setBOD  # Calling melt() Functionm <- melt(BOD, variable.name = "Stat", value.name ="Data") print(m) 
Output:
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
No id variables; using all as measure variables
     Stat Data
1    Time  1.0
2    Time  2.0
3    Time  3.0
4    Time  4.0
5    Time  5.0
6    Time  7.0
7  demand  8.3
8  demand 10.3
9  demand 19.0
10 demand 16.0
11 demand 15.6
12 demand 19.8

R DataFrame-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Split Column Into Multiple Columns in R DataFrame?
Printing Output of an R Program
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
p5.js | textAlign() Function

16 Apr, 2019
The textAlign() function in p5.js is used to set the alignment for the drawing the text. This function accepts two parameter horizAlign and vertAlign. The horizAlign parameter sets the alignment on x-axis and the vertAlign parameter sets the alignment on y-axis.
Syntax:
textAlign( horizAlign, vertAlign)
or
textAlign()
Parameters: This function accepts two parameters as mentioned above and described below:
horizAlign: This parameter stores the horizontal alignment of the text as (LEFT, CENTER, or RIGHT).
vertAlign: This parameter stores the vertical alignment of the text as (TOP, BOTTOM, CENTER, or BASELINE).
Below programs illustrate the textAlign() function in p5.js:Example 1: This example uses textAlign() function to align the content horizontally.
function setup() {          // Create Canvas of given size    createCanvas(380, 150);}  function draw() {          // Set the background color    background(220);          let c = 0.5;          // Use atan() function to calculate    // arc tangent value    let ac = atan(c);          // Set font size    textSize(26);          // Set font color    fill(color('green'));          // Set the text alignment to    // CENTER, RIGHT, LEFT    textAlign(LEFT);    text('GEEKS', 100, 30);    textAlign(CENTER);    text('for', 100, 60);    textAlign(RIGHT);    text('GEEKS', 100, 90);}
Output:
Example 2: This example uses textAlign() function to align the content vertically.
function setup() {          // Create Canvas of given size    createCanvas(380, 150);}  function draw() {          // Set the background color    background(220);          // Set the text size    textSize(26);          // Set the stroke width    strokeWeight(0.5);          // Set the co-ordinates for line    line(0, height/2, width, height/2);          // set the alignment for the text    textAlign(CENTER, TOP);          // Set the text     text('CENTER', 0, height/2, width);}
Output:
Reference: https://p5js.org/reference/#/p5/textAlign
JavaScript-p5.js
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
Roadmap to Learn JavaScript For Beginners
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 ?
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks

28 Jun, 2021
A Young tableau is a 2D array of integers increasing from left to right and from top to bottom. Any unfilled entries are marked with ∞, and hence there cannot be any entry to the right of, or below a ∞. The following Young tableau consists of unique entries.
1     2     5      14
3     4     6      23       
10    12    18     25  
31    ∞     ∞       ∞ 
When an element is removed from a Young tableau, other elements should be moved into its place so that the resulting table is still a Young tableau (unfilled entries may be filled in with a ∞). The minimum number of entries (other than 1) to be shifted, to remove 1 from the given Young tableau is ____________(A) 2(B) 5(C) 6(D) 18Answer: (B)Explanation: Initially
1     2     5      14
3     4     6      23       
10    12    18     25  
31    ∞     ∞       ∞ 
When 1 is removed, it is replaced by the smallest adjacent which is 2.
2     2     5      14
3     4     6      23       
10    12    18     25  
31    ∞     ∞       ∞ 
When 2 is moved in place of 1, it is replaced by smallest adjacent which is 4
2     4     5      14
3     4     6      23       
10    12    18     25  
31    ∞     ∞       ∞ 
When 4 is moved in place of 2, it is replaced by smallest adjacent which is 6
2     4     5      14
3     6     6      23       
10    12    18     25  
31    ∞     ∞       ∞ 
When 6 is moved in place of 4, it is replaced by smallest adjacent which is 18.
2     4     5      14
3     6     18     23       
10    12    18     25  
31    ∞     ∞       ∞ 
When 18 is moved in place of 6, it is replaced by smallest adjacent which is 25.
2     4     5      14
3     6     18     23       
10    12    25     25  
31    ∞     ∞       ∞ 
When 25 is moved in place of 18, it is replaced by smallest adjacent which is ∞.
2     4     5      14
3     6     18     23       
10    12    25      ∞  
31    ∞     ∞       ∞ 
Shifted numbers are 2, 4, 6, 18, 25Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
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 MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Files Class readString() Method in Java with Examples - GeeksforGeeks

05 Feb, 2021
The readString() method of File Class in Java is used to read contents to the specified file.
Syntax:
Files.readString(filePath)
Parameters: 
path - File path with data type as Path
Return Value: This method returns the content of the file in String format.
Below are two overloaded forms of the readString() method.
public static String readString​(Path path) throws IOException 
public static String readString​(Path path, Charset cs) throws IOException
Using the UTF-8 charset in the first method reads all content from a file into a string, decoding from bytes to characters.
The second method does the same using the specified charset.
Input File:
Input File
Below is the implementation of the problem statement:
Java
// Implementation fo readString() method in Javaimport java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)    {        // creating path        Path filePath            = Paths.get("/home/mayur/", "temp", "gfg.txt");        try          {            // reading file from given path            String content = Files.readString(filePath);            // printing the content            System.out.println(content);        }        catch (IOException e) {            e.printStackTrace();        }    }}
Output:
Hello from GFG!
Java-File Class
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
MySQL | RENAME USER - GeeksforGeeks

03 Mar, 2018
The RENAME USER statement can be used in MySQL if a MySQL administrator wants to change the username or the host of an existing MySQL user account without altering the user account’s privileges.
Syntax :
RENAME USER 'username'@'host' TO 'new_username'@'host';

Parameters Used:
Username: It is the username of the user account you want to rename.new_username: It is the new name you want to assign to the user.
Username: It is the username of the user account you want to rename.
new_username: It is the new name you want to assign to the user.
Suppose there are 4 users in the MySQL database server as listed below:
Let us now learn about how to rename users using RENAME USER statement:
Renaming a single user using the RENAME USER statement: To rename the user account with the username “gfguser1”, the RENAME USER statement should be executed as follows:Syntax:Output:Table after execution of the rename user statement will be as follows:Renaming multiple users using the RENAME USER statement: The RENAME USER statement can be used to rename multiple user accounts at once. To rename two user account “gfguser2” and “gfguser1” from the table mentioned above,the RENAME USER statement should be executed as follows:Syntax:Output:Table after execution of the above rename user statement will be as follows:
Renaming a single user using the RENAME USER statement: To rename the user account with the username “gfguser1”, the RENAME USER statement should be executed as follows:Syntax:Output:Table after execution of the rename user statement will be as follows:
Renaming multiple users using the RENAME USER statement: The RENAME USER statement can be used to rename multiple user accounts at once. To rename two user account “gfguser2” and “gfguser1” from the table mentioned above,the RENAME USER statement should be executed as follows:Syntax:Output:Table after execution of the above rename user statement will be as follows:
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter