code-rag-bench/online-tutorials huggingface dataset:
Pie plot using Plotly in Python

28 Jun, 2021
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. 
A pie chart is a circular analytical chart, which is divided into region to symbolize numerical percentage. In px.pie, data anticipated by the sectors of the pie to set the values. All  sector  are classify in names. Pie chart is used usually to show the percentage with next corresponding slice of pie. Pie chart helps to make understand well because of its different portions and color codings.
Syntax: plotly.express.pie(data_frame=None, names=None, values=None, color=None, color_discrete_sequence=None, color_discrete_map={}, hover_name=None, hover_data=None, custom_data=None, labels={}, title=None, template=None, width=None, height=None, opacity=None, hole=None)
Parameters:
Example:
Python3
import plotly.express as pximport numpy # Random Datarandom_x = [100, 2000, 550]names = ['A', 'B', 'C'] fig = px.pie(values=random_x, names=names)fig.show()
 
 
Output:
 
 
The same value for the names parameter are grouped together. Repeated labels visually groups rows or columns together to make the data easier to understand. Let’s see one example given below.
 
Example: The iris dataset contains many rows but only 3 species so the data is grouped according to the species.
 
Python3
import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.pie(df, values="sepal_width", names="species")fig.show()
 
 
Output: 
 
 
The pie chart can be customized by using the px.pie, using some of its parameters such as hover_data and labels. Let’s see the below example for better understanding.
 
Example:
 
Python3
import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.pie(df, values="sepal_width", names="species",             title='Iris Dataset', hover_data=['sepal_length'])fig.show()
 
 
Output:
 
 
The color of pie can be change in plotly module. Different colors help in to distinguish the data from each other, which help  to understand the data more efficiently.
 
Example:
 
Python3
import plotly.express as px # Loading the iris datasetdf = px.data.iris() fig = px.pie(df, values="sepal_width",             names="species",             color_discrete_sequence=px.colors.sequential.RdBu)fig.show()
 
 
Output:
 
 
sooda367
Python-Plotly
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
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
jQuery | height() and innerHeight() with Examples

13 Feb, 2019
The height() is an inbuilt method in jQuery which is used to check the height of an element but it will not check the padding, border and margin of the element.Syntax:
$("param").height()

Parameters : This function do not accept any parameter.Return value : It returns height of the selected element.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/                 jquery/3.3.1/jquery.min.js"></script>    <script>        $(document).ready(function() {            $("button").click(function() {                var msg = "";                msg += "height of div: " + $("#demo").height();                $("#demo").html(msg);            });        });    </script>    <style>        #demo {            height: 150px;            width: 350px;            padding: 10px;            margin: 3px;            border: 1px solid blue;            background-color: lightgreen;        }    </style></head>  <body>    <div id="demo"></div>    <button>Click Me!!!</button>    <p>Click on the button and check the height of the       element(excluding padding).</p></body>  </html>
Output:Before clicking on “Click Me” button-After clicking on “Click Me” button-
jQuery also include innerHeight() method i.e, it used to check inner height of the element including padding.Syntax:
$("param").innerHeight()

Parameters: This function do not accept any parameter.Return value: It returns the inner height of the selected element.Code #2:
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/                 jquery/3.3.1/jquery.min.js"></script>    <script>        $(document).ready(function() {            $("button").click(function() {                var msg = "";                msg += "Inner Height of div: " + $("#demo").                        innerHeight() + "</br>";                $("#demo").html(msg);            });        });    </script></head><style>    #demo {        height: 150px;        width: 350px;        padding: 10px;        margin: 3px;        border: 1px solid blue;        background-color: lightgreen;    }</style>  <body>    <div id="demo"></div>    <button>Click Me!!!</button>    <p>Click on the button and check the innerHeight of       an element(includes padding).</p></body>  </html>
Output:Before clicking on “Click Me” button-After clicking on “Click Me” button-
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change css styles of elements in JavaScript?

JavaScript can change Css styles such as color, font size etc. of elements using some methods such as getElementById(), getElementByClassName() etc.
In the following example font style and font size of the elements have changed using getElementById() method.
Live Demo
In the following example, using style commands "style.fontSize" and "style.fontStyle", the provided texts are changed to a font size of "35px" and font style to "italic"
<html>
<body>
   <p id="size">JavaScript can change the style of an HTML element.</p>
   <p id="style">JavaScript can change the style of an HTML element.</p>
   <button type="button"
   onclick="document.getElementById('size').style.fontSize='35px'">Size</button>
   <button type="button" onclick="document.getElementById('style')
.style.fontStyle='italic'">Style</button>
</body>
</html>
On executing the above code we will get the following on the browser.
After clicking the above buttons first text will be changed to different font size and second text will be changed to a different font style as shown in the output.
In the following example the color of the text has changed to blue using style command "style.color".
Live Demo
<html>
<body>
   <p id="color">JavaScript can change the color of an HTML element.</p>
   <button type="button" onclick="document.getElementById('color').
   style.color='blue'">Color Me</button>
</body>
</html>
After executing above code we will get the following on the browser window. 
On clicking on the "color me" button the provided text's color will be changed to 'blue' as shown in the output.
Gerrit - Configuring Git-Review

Gerrit is built on top of Git version control system, which extracts the code from other host, pushing changes to the code, submitting the code for review, etc. The default remote name of Git is origin and we tell git-review to use this name 'origin' by using the following command.
$ git config --global gitreview.remote origin
How to find the missing number in a given Array from number 1 to n in Java?

If a single number is missing in an integer array that contains a sequence of numbers values, you can find it basing of the sum of numbers or, basing on the xor of the numbers.
Based on the sum of the numbers −
The sum of n sequential numbers will be [n*(n+1)]/2. Using this get the sum of the numbers the n numbers.
Add all the elements in the array.
Subtract the sum of the numbers in the array from the sum of the n numbers.
import java.util.Scanner;
public class MissingNumber {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the n value: ");
      int n = sc.nextInt();
      int inpuArray[] = new int[n];
      System.out.println("Enter (n-1) numbers: ");
      for(int i=0; i<=n-2; i++) {
         inpuArray[i] = sc.nextInt();
      }
      //Finding the missing number
      int sumOfAll = (n*(n+1))/2;
      int sumOfArray = 0;
      for(int i=0; i<=n-2; i++) {
         sumOfArray = sumOfArray+inpuArray[i];
      }
      int missingNumber = sumOfAll-sumOfArray;
      System.out.println("Missing number is: "+missingNumber);
   }
}
Enter the n value:
5
Enter (n-1) numbers:
1
2
4
5
Missing number is: 3
Using XOR operation − Another way to find the missing number is using XOR.
Find the XOR of all the numbers up ton.
Find the XOR of all the numbers in the array.
Then find the XOR of both results.
import java.util.Scanner;
public class MissingNumber {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the n value: ");
      int n = sc.nextInt();
      int inpuArray[] = new int[n];
      System.out.println("Enter (n-1) numbers: ");
      for(int i=0; i<=n-2; i++) {
         inpuArray[i] = sc.nextInt();
      }
      //Finding the missing number
      int xorArray = inpuArray[0];
      //XOR of elements of the array
      for(int i=1; i<=n-1; i++) {
         xorArray = xorArray ^ i;
      }
      int xorAll = inpuArray[0];
      //XOR of elements of the array
      for(int i=1; i<=n+1; i++) {
         xorAll = xorAll ^ i;
      }
      int missingNumber = xorArray ^ xorAll;
      System.out.println("Missing number is: "+missingNumber);
   }
}
Enter the n value:
5
Enter (n-1) numbers:
1
2
4
5
Missing number is: 3
after method in Python Tkinter

Tkinter is a python library to make GUIs. It has many built in methods to create and manipulate GUI windows and other widgets to show the data and GUI events. In this article we will see how the after method is used in a Tkinter GUI.
.after(delay, FuncName=FuncName)
This method calls the function FuncName after the given delay in milisecond
Here we make a frame to display a list of words randomly. We use the random library along with the after method to call a function displaying a given list of text in a random manner.
import random
from tkinter import *

base = Tk()

a = Label(base, text="After() Demo")
a.pack()

contrive = Frame(base, width=450, height=500)
contrive.pack()

words = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat','Sun']
#Display words randomly one after the other.
def display_weekday():
   if not words:
   return
   rand = random.choice(words)
   character_frame = Label(contrive, text=rand)
   character_frame.pack()
   contrive.after(500,display_weekday)
   words.remove(rand)

base.after(0, display_weekday)
base.mainloop()
Running the above code gives us the following result:
On running the same program again we get the result showing different sequence of the words.
In the next example we will see how we can use the after method as a delay mechanism to wait for a process to run for a certain amount of time and then stop the process. We also use the destroy method to stop the processing.
from tkinter import Tk, mainloop, TOP
from tkinter.ttk import Button

from time import time

base = Tk()

stud = Button(base, text = 'After Demo()')
stud.pack(side = TOP, pady = 8)

print('processing Begins...')

begin = time()

base.after(3000, base.destroy)

mainloop()

conclusion = time()
print('process destroyed in % d seconds' % ( conclusion-begin))
Running the above code gives us the following result:
processing Begins...
process destroyed in 3 seconds
DFA of alternate 0's and 1's - GeeksforGeeks

09 Sep, 2020
Regular Expression can be anything, from a terminal symbol, ∅, to union of two regular expressions (R1 + R2), their concatenation (R1R2) or its closure R1* as well.
Examples of Regular Expression :
Regular expression of set of all strings of 0’s and 1’s starting with two zeros :00(0+1)*Regular expression of set of all strings of 0’s and 1’s having even number of 0’s followed by odd numbers of 1’s :(00)*1(11)*Regular expression of set of all strings of 0’s and 1’s containing at least one 0 and at least two 1’s :00*11(0+1)* + 0111*(0+1)*
Regular expression of set of all strings of 0’s and 1’s starting with two zeros :00(0+1)*
00(0+1)*
Regular expression of set of all strings of 0’s and 1’s having even number of 0’s followed by odd numbers of 1’s :(00)*1(11)*
(00)*1(11)*
Regular expression of set of all strings of 0’s and 1’s containing at least one 0 and at least two 1’s :00*11(0+1)* + 0111*(0+1)*
00*11(0+1)* + 0111*(0+1)*
Strings that will be acceptable by regular expression with alternate 0’s and 1’s –
∈ (no input, 0 and 1)010101..... (string that starts with 0 followed by 1 and so on).101010..... (string that starts with 1 followed by 0 and so on).
∈ (no input, 0 and 1)
010101..... (string that starts with 0 followed by 1 and so on).
101010..... (string that starts with 1 followed by 0 and so on).
Now, a regular expression for set of all strings consisting of alternate 0’s and 1’s would be (01)*, where it can accept ∈, 01, 0101, 010101.....etc but this restricts the string as it can always begin with 0 only.
Again, the expression (10)* will accept ∈, 10, 1010, 101010....etc but this too restricts string as it can always begin with 1 only.
So, we introduce 1(01)* and 0(10)* to meet gap in respective cases.
While 1(01)* breaks the restriction of string starting with 0, 0(10)* breaks same for string starting with 1.
So, the final expression is –
(01)* + (10)* + 0(10)* + 1(01)*
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Construct a Turing Machine for language L = {ww | w ∈ {0,1}}
Proof that vertex cover is NP complete
Boyer-Moore Majority Voting Algorithm
CYK Algorithm for Context Free Grammar
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Introduction To Grammar in Theory of Computation
Removing Direct and Indirect Left Recursion in a Grammar
Applications of various Automata
Practice problems on finite automata
Construct Pushdown Automata for all length palindrome
C++ String Library - reserve

It request a change in capacity.
Following is the declaration for std::string::reserve.
void reserve (size_t n = 0);
void reserve (size_t n = 0);
n − Planned length for the string.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::reserve.
#include <iostream>
#include <fstream>
#include <string>

int main () {
   std::string str;

   std::ifstream file ("test.txt",std::ios::in|std::ios::ate);
   if (file) {
      std::ifstream::streampos filesize = file.tellg();
      str.reserve(filesize);

      file.seekg(0);
      while (!file.eof()) {
         str += file.get();
      }
   std::cout << str;
   }
   return 0;
}
 Print
 Add Notes
 Bookmark this page
C library function - ftell()

The C library function long int ftell(FILE *stream) returns the current file position of the given stream.
Following is the declaration for ftell() function.
long int ftell(FILE *stream)
stream − This is the pointer to a FILE object that identifies the stream.
stream − This is the pointer to a FILE object that identifies the stream.
This function returns the current value of the position indicator. If an error occurs, -1L is returned, and the global variable errno is set to a positive value.
The following example shows the usage of ftell() function.
#include <stdio.h>

int main () {
   FILE *fp;
   int len;

   fp = fopen("file.txt", "r");
   if( fp == NULL )  {
      perror ("Error opening file");
      return(-1);
   }
   fseek(fp, 0, SEEK_END);

   len = ftell(fp);
   fclose(fp);

   printf("Total size of file.txt = %d bytes\n", len);
  
   return(0);
}
Let us assume we have a text file file.txt, which has the following content −
This is tutorialspoint.com
Now let us compile and run the above program that will produce the following result if file has above mentioned content otherwise it will give different result based on the file content −
Total size of file.txt = 26 bytes


    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
How to Check if PHP session has already started?

In PHP,we utilize session_start() an inbuilt function to start the session .But the problem we face in a PHP script is if we execute it more than once it throws an error. So here we will learn how to check the session started or not without calling session_start() function twice.
There are two ways to follow to resolve this problem.
For below PHP 5.4.0 version.
<?php
   if(session_id() == ''){
      session_start();
   }
?>
If the session not started this code above will always start the session in the PHP script.
In the second method, we can utilize the function session_status(), which returns the status of the present session. This function can return three integer values, which all are predefined constants. These are:
0 – PHP_SESSION_DISABLED: Sessions are currently disabled.
1 – PHP_SESSION_NONE: Sessions are enabled, but no session has been started.
2 – PHP_SESSION_ACTIVE: Sessions are enabled and a session has been started.
<?php
   if (session_status() == PHP_SESSION_NONE) {
      session_start();
   }
?>
The above code checks whether the session started or not, if not started this will start the session in the PHP script.
session_status() function only runs in PHP 5.4.0 version or above.
How do we use radio buttons in HTML forms?

Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc.
Let’s learn how to use radio buttons in HTML forms to get user input. Radio buttons are used when out of many options; just one option is required to be selected. They are also created using HTML <input> tag and the type attribute is set to radio.
Here are the attributes for radio button −
 You can try to run the following code to learn how to work with radio buttons in HTML −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <head>
         <title>HTML Radio Button</title>
      </head>
      <p>Gender</p>
      <form>
         <input type="radio" name="gender" value="male">Male
         <br>
         <input type="radio" name="gender" value="female">Female
      </form>
   </body>
</html>
Matplotlib.axes.Axes.set_transform() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_transform() function in axes module of matplotlib library is used to set the artist transform.
Syntax: Axes.set_transform(self, t)
Parameters: This method accepts only one parameters.
t : This parameter is the Transform.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.set_transform() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.transforms as mtransforms  delta = 0.25x = y = np.arange(-3.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z1 = np.exp(-X**2 - Y**2)Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2)  transform = mtransforms.Affine2D().rotate_deg(30)fig, ax = plt.subplots()      im = ax.imshow(Z, interpolation ='none',               origin ='lower',               extent =[-2, 4, -3, 2],                clip_on = True)  trans_data = transform + ax.transDataim.set_transform(trans_data)  x1, x2, y1, y2 = im.get_extent()ax.plot([x1, x2, x2, x1, x1],         [y1, y1, y2, y2, y1],        "ro-",        transform = trans_data)  ax.set_xlim(-5, 5)ax.set_ylim(-4, 4)  fig.suptitle('matplotlib.axes.Axes.set_transform() \function Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib function  import matplotlib.pyplot as pltfrom matplotlib import collections, colors, transformsimport numpy as np   nverts = 50npts = 100   r = np.arange(nverts)theta = np.linspace(0, 2 * np.pi, nverts)xx = r * np.sin(theta)yy = r * np.cos(theta)spiral = np.column_stack([xx, yy])   rs = np.random.RandomState(19680801)   xyo = rs.randn(npts, 2)   colors = [colors.to_rgba(c)          for c in plt.rcParams['axes.prop_cycle'].by_key()['color']]   fig, ax1 = plt.subplots()   col = collections.RegularPolyCollection(    7, sizes = np.abs(xx) * 10.0,     offsets = xyo,     transOffset = ax1.transData)  trans = transforms.Affine2D().scale(fig.dpi / 72.0)col.set_transform(trans)   ax1.add_collection(col, autolim = True)col.set_color(colors)   fig.suptitle('matplotlib.axes.Axes.set_transform() function\ Example\n', fontweight ="bold")  fig.canvas.draw()  plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
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 ?
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 | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
How to multiply each value in a column by a constant in R?

To multiply each value in a column by a constant, we can use multiplication sign *.
For example, if we have a data frame called df that contains a column say x. Now, if we want to multiply each value in x with 10 then we can use the below mentioned command −
df$x<-10*(df$x)
Following snippet creates a sample data frame −
x<-rpois(20,1)
df1<-data.frame(x)
df1
The following dataframe is created −
   x
1  0
2  2
3  1
4  1
5  0
6  1
7  1
8  0
9  3
10 1
11 0
12 0
13 1
14 1
15 0
16 3
17 2
18 0
19 2
20 0
To multiply each value in x with 5, add the following code to the above snippet −
x<-rpois(20,1)
df1<-data.frame(x)
df1$x<-5*(df1$x)
df1
If you execute all the above given snippets as a single program, it generates the following Output −
    x
1   0
2  10
3   5
4   5
5   0
6   5
7   5
8   0
9  15
10  5
11  0
12  0
13  5
14  5
15  0
16 15
17 10
18  0
19 10
20  0
Following snippet creates a sample data frame −
y<-round(rnorm(20),1)
df2<-data.frame(y)
df2
The following dataframe is created −
     y
1   1.0
2  -1.8
3   0.0
4   0.2
5  -2.9
6   1.0
7  -0.6
8  -1.3
9  -0.2
10 -0.3
11  0.3
12  0.8
13 -0.9
14  0.4
15 -2.2
16  1.1
17  0.5
18  3.0
19  1.6
20  1.0
To multiply each value in y with 2, add the following code to the above snippet −
y<-round(rnorm(20),1)
df2<-data.frame(y)
df2$y<-2*(df2$y)
df2
If you execute all the above given snippets as a single program, it generates the following Output −
     y
1   2.0
2  -3.6
3   0.0
4   0.4
5  -5.8
6   2.0
7  -1.2
8  -2.6
9  -0.4
10 -0.6
11  0.6
12  1.6
13 -1.8
14  0.8
15 -4.4
16  2.2
17  1.0
18  6.0
19  3.2
20  2.0
java.time.LocalDateTime.getLong() Method Example

The java.time.LocalDateTime.getLong(TemporalField field) method gets the value of the specified field from this date-time as an long.
Following is the declaration for java.time.LocalDateTime.getLong(TemporalField field) method.
public long getLong(TemporalField field)

field − the field to get, not null.
the value for the field.
DateTimeException − if a value for the field cannot be obtained or the value is outside the range of valid values for the field.
DateTimeException − if a value for the field cannot be obtained or the value is outside the range of valid values for the field.
UnsupportedTemporalTypeException − if the field is not supported or the range of values exceeds an long.
UnsupportedTemporalTypeException − if the field is not supported or the range of values exceeds an long.
ArithmeticException − if numeric overflow occurs
ArithmeticException − if numeric overflow occurs
The following example shows the usage of java.time.LocalDateTime.getLong(TemporalField field) method.
package com.tutorialspoint;

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class LocalDateTimeDemo {
   public static void main(String[] args) {
 
      LocalDateTime date = LocalDateTime.parse("2017-02-03T12:30:30");
      System.out.println(date.getLong(ChronoField.CLOCK_HOUR_OF_DAY));  
   }
}
Let us compile and run the above program, this will produce the following result −
12

 Print
 Add Notes
 Bookmark this page
Selenium - Radio Button Interaction

In this section, we will understand how to interact with Radio Buttons. We can select a radio button option using the 'click' method and unselect using the same 'click' method.
Let us understand how to interact with radio buttons using https://www.calculator.net/mortgage-payoff-calculator.html. We can also check if a radio button is selected or enabled.
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class webdriverdemo {
   public static void main(String[] args) throws InterruptedException {
   
      WebDriver driver = new FirefoxDriver();
      
      //Puts an Implicit wait, Will wait for 10 seconds before throwing exception
      driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      
      //Launch website
      driver.navigate().to("http://www.calculator.net/mortgage-payoff-calculator.html");
      driver.manage().window().maximize();
      
      // Click on Radio Button
      driver.findElement(By.id("cpayoff1")).click();
      System.out.println("The Output of the IsSelected " +
         driver.findElement(By.id("cpayoff1")).isSelected());
      System.out.println("The Output of the IsEnabled " +
         driver.findElement(By.id("cpayoff1")).isEnabled());
      System.out.println("The Output of the IsDisplayed " +
         driver.findElement(By.id("cpayoff1")).isDisplayed());
      
      //Close the Browser.
      driver.close();
   }
}
Upon execution, the radio button is selected and the output of the commands are displayed in the console.

    46 Lectures 
     5.5 hours 

 Aditya Dua

    296 Lectures 
     146 hours 

 Arun Motoori

    411 Lectures 
     38.5 hours 

 In28Minutes Official

    22 Lectures 
     7 hours 

 Arun Motoori

    118 Lectures 
     17 hours 

 Arun Motoori

    278 Lectures 
     38.5 hours 

 Lets Kode It
 Print
 Add Notes
 Bookmark this page
JavaScript | How to add an element to a JSON object?

27 May, 2019
In order to add Key/value pair to a JSON object, Either we use dot notation or square bracket notation. Both methods are widely accepted.
Example 1: This example adds {“prop_4” : “val_4”} to the GFG_p object by using dot notation.
<!DOCTYPE html><html>  <head>    <title>        JavaScript |      Add a key/value pair to JSON object    </title></head>  <body style="text-align:center;">      <h1 style="color:green;">              GeeksForGeeks          </h1>      <p id="GFG_up"       style=" font-weight: bold">    </p>      <button onclick="Geeks()">        Click to add    </button>      <p id="GFG_down"        style="color:green;              font-weight: bold" ;>    </p>      <script>        var GFG_p = {            prop_1: "val_1",            prop_2: "val_2",            prop_3: "val_3"        };        var p_up =             document.getElementById("GFG_up");        var p_down =             document.getElementById("GFG_down");        p_up.innerHTML =           JSON.stringify(GFG_p);          function Geeks() {            GFG_p.prop_4 = "val_4";            p_down.innerHTML = JSON.stringify(GFG_p);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example adds {“prop_4” : “val_4”} to the GFG_p object by using square bracket notation.
<!DOCTYPE html><html>  <head>    <title>        JavaScript       | Add a key/value pair to JSON object    </title></head>  <body style="text-align:center;">      <h1 style="color:green;">              GeeksForGeeks          </h1>      <p id="GFG_up"       style=" font-weight: bold">    </p>      <button onclick="Geeks()">        Click to add    </button>      <p id="GFG_down"        style="color:green;               font-weight: bold" ;>    </p>      <script>        var GFG_p = {            prop_1: "val_1",            prop_2: "val_2",            prop_3: "val_3"        };        var p_up =             document.getElementById("GFG_up");        var p_down =             document.getElementById("GFG_down");        p_up.innerHTML =           JSON.stringify(GFG_p);          function Geeks() {            GFG_p["prop_4"] = "val_4";            p_down.innerHTML = JSON.stringify(GFG_p);        }    </script></body>  </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JSON
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
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Maximum possible XOR of every element in an array with another array in C++

In this problem, we are given two arrays A and B of n elements each. Our task is to create a program to find the maximum possible XOR of every element in an array with another array.
We have to compute the maximum XOR for each element of array A with array B i.e. for each element of array A we will select an element in array B which will have the maximum XOR value.
Let's take an example to understand the problem −
Input −
array A = {3, 6 ,11, 9}
array B = {8, 2, 4, 1}
Output −
11 14 15 13
Explanation−
Let’s see the XOR combination of each element of array A with all elements of array B and then select the maximum for each.
3 XOR 8 = 11 3 XOR 2 = 1 3 XOR 4 = 7 3 XOR 1 = 2
Maximum = 11.
6 XOR 8 = 14 6 XOR 2 = 4 6 XOR 4 = 2 6 XOR 1 = 1
Maximum = 14.
11 XOR 8 = 3 11 XOR 2 = 9 11 XOR 4 = 15 11 XOR 1 = 10
Maximum = 15.
9 XOR 8 = 1 9 XOR 2 = 11 9 XOR 4 = 13 9 XOR 1 = 8
Maximum = 13.
To solve this problem, a simple and naive approach is to calculate all the combinations and print the maximum XOR as shown in the above example.
But this will not be effective as the code relies on two loops which make its complexity of the order O(n^2).
So, we will see a better solution to the problem.
It is to use a trie data structure which will store the binary of all elements of array B for the match with array A, to find the maximum XOR.
So, for an element of array A, we will check its most significant bit and try to make it 1. And the go to the next MSB. Following this we will get our maximum XOR element for an element of A in array B.
Program to find the maximum possible XOR of every element in an array with another array
 Live Demo
#include<iostream>
using namespace std;
struct trie{
   int value;
   trie *child[2];
};
trie * get(){
   trie * root = new trie;
   root -> value = 0;
   root -> child[0] = NULL;
   root -> child[1] = NULL;
   return root;
}
void insert(trie * root, int key){
   trie * temp = root;
   for (int i = 31; i >= 0; i--){
      bool current_bit = key & (1 << i);
      if (temp -> child[current_bit] == NULL)
         temp -> child[current_bit] = get();
      temp = temp -> child[current_bit];
   }
   temp -> value = key;
}
int findMaxXor(trie * root, int element){
   trie * temp = root;
   for (int i = 31; i >= 0; i--){
      bool bits = ( element & ( 1 << i) );
      if (temp -> child[1 - bits] != NULL)
         temp = temp -> child[1 - bits];
      else
         temp = temp -> child[bits];
   }
   return (element ^ temp -> value);
}
int main(){
   int A[] = {3, 11, 6, 9};
   int B[] = {8, 2, 4, 1};
   int N = sizeof(A)/sizeof(A[0]);
   trie * root = get();
   for (int i = 0; i < N; i++)
   insert(root, B[i]);
   cout<<"The maximum possible XOR of every possible element in array A with Array B is\n";
   for (int i = 0; i < N; i++)
   cout <<findMaxXor(root, A[i])<<"\t";
   return 0;
}
The maximum possible XOR of every possible element in array A with Array B is
11 15 14 13
matplotlib.axes.Axes.barh() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.barh() function in axes module of matplotlib library is used to make a horizontal bar plot.
Syntax: Axes.barh(self, y, width, height=0.8, left=None, *, align=’center’, **kwargs)
Parameters: This method accept the following parameters that are described below:
y: This parameter is the sequence of y coordinates of the bar.
height: This parameter is the height(s) of the bars.
width: This parameter is an optional parameter. And it is the width(s) of the bars with default value 0.8.
left : This parameter is also an optional parameter. And it is the x coordinate(s) of the left sides of the bars.
align: This parameter is also an optional parameter. And it is used for alignment of the bars to the y coordinates.
Returns: This returns the following:
BarContainer:This returns the container with all the bars and optionally errorbars.
Below examples illustrate the matplotlib.axes.Axes.barh() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  data = ((1000, 30), (30, 10),        (30, 100), (800, 500),         (50, 10))  dim = len(data[0])w = 0.3dimw = w / dim  fig, ax = plt.subplots()x = np.arange(len(data))  for i in range(len(data[0])):    y = [d[i] for d in data]    b = ax.barh(x + i * dimw, y,                dimw, left = 0.001)  ax.set_yticks(x + dimw / 2)ax.set_yticklabels(map(str, x))ax.set_xscale('log')  ax.set_title('matplotlib.axes.Axes.barh Example')  plt.show()
Output:
Example #2:
# ImpleMinetation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  labels = ['Month1', 'Month2',           'Month3', 'Month4']  mine = [21, 52, 33, 54]others = [54, 23, 32, 41]Mine_std = [2, 3, 4, 1]Others_std = [3, 5, 2, 3]width = 0.3  fig, ax = plt.subplots()  ax.barh(labels, mine, width,        xerr = Mine_std,         label ='Mine')  ax.barh(labels, others, width,         xerr = Others_std,         left = mine,         label ='Others')  ax.set_xlabel('Articles')ax.legend()  ax.set_title('matplotlib.axes.Axes.barh Example')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
How to use Xpath with BeautifulSoup ?

16 Mar, 2021
Prerequisites: Beautifulsoup
In this article, we will see how to use Xpath with BeautifulSoup. Getting data from an element on the webpage using lxml requires the usage of Xpaths. XPath works very much like a traditional file system
First, we need to install all these modules on our computer.
BeautifulSoup: Our primary module contains a method to access a webpage over HTTP.
pip install bs4
lxml: Helper library to process webpages in python language.
pip install lxml
requests: Makes the process of sending HTTP requests flawless.the output of the function
pip install requests
Getting data from an element on the webpage using lxml requires the usage of Xpaths.
XPath works very much like a traditional file system.
To access file 1,
C:/File1
Similarly, To access file 2,
C:/Documents/User1/File2
Right-click the element in the page and click on Inspect.
Right-click on the element in the Elements Tab.
Click on copy XPath.
Import module
Scrap content from a webpage
Now to use the Xpath we need to convert the soup object to an etree object because BeautifulSoup by default doesn’t support working with XPath.
However, lxml supports XPath 1.0. It has a BeautifulSoup compatible mode where it’ll try and parse broken HTML the way Soup does.
To copy the XPath of an element we need to inspect the element and then right-click on it’s HTML and find the XPath.
After this, you can use the .xpath method available in etree class of lxml module to parse the value inside the concerned element.
Note: If XPath is not giving you the desired result copy the full XPath instead of XPath and the rest other steps would be the same.
Given below is an example to show how Xpath can be used with Beautifulsoup
Program:
Python3
from bs4 import BeautifulSoupfrom lxml import etreeimport requests    URL = "https://en.wikipedia.org/wiki/Nike,_Inc."  HEADERS = ({'User-Agent':            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \            (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',\            'Accept-Language': 'en-US, en;q=0.5'})  webpage = requests.get(URL, headers=HEADERS)soup = BeautifulSoup(webpage.content, "html.parser")dom = etree.HTML(str(soup))print(dom.xpath('//*[@id="firstHeading"]')[0].text)
Output:
Nike, Inc.
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | utf8_decode() Function

07 Aug, 2021
The utf8_decode() function is an inbuilt function in PHP which is used to decode a UTF-8 string to the ISO-8859-1. This function decodes back to the encoded string which is encoded with the utf8_encode() function.
Syntax: 
string utf8_decode( string $string )
Parameter: This function accepts single parameter $string which is required. It specifies the UTF-8 encoded string to be decoded.
Return Value: This function returns a string representing the decoded string on success and false on failure.
Note: This function is available for PHP 4.0.0 and newer version.
Program 1:  
PHP
<?php // String to decode$string_to_decode = "\x63"; // Encoding stringecho utf8_encode($string_to_decode) ."<br>"; // Encoding stringecho utf8_decode($string_to_decode); ?>
Output: 
c
c
Program 2:  
PHP
<?php // Creating an array of 256 elements$text = array(    "\x20", "\x21", "\x22", "\x23", "\x24", "\x25",    "\x26", "\x27", "\x28", "\x29", "\x2a", "\x2b",    "\x2c", "\x2d", "\x2e", "\x2f", "\x30", "\x31"); echo "Encoded elements:\n"; // Encoding and decoding all elementsforeach( $text as $index ) {    echo utf8_encode($index) . " ";} echo "\nDecoded elements:\n"; foreach( $text as $index ) {    echo utf8_decode($index) . " ";} ?>
Output: 
Encoded elements:
  ! " # $ % & ' ( ) * + , - . / 0 1 
Decoded elements:
  ! " # $ % & ' ( ) * + , - . / 0 1 
Reference: https://www.php.net/manual/en/function.utf8-decode.php 
ruhelaa48
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python IMDbPY – Searching a movie

18 Jan, 2022
IMDbPY is a Python package which is used to retrieve and manage the data of the IMDb.IMDb is an online database of information related to films, television programs, home videos, video games, and streaming content online – including cast, production crew and personal biographies, plot summaries, trivia, fan and critical reviews, and ratings.In this article we will see how we can install this module and use this module to fetch variety of information.Installation In order to extract data from IMDb, we must first install the Python IMDbP library. This can be done by entering the command below in your command prompt or terminal:  
pip install IMDbPY
Searching a movie We can search a movie with the help of search_movie  
Syntax : imdb_object.search_movie(name)Argument : It takes string as argument, which is the movie name.Return : It return list, items in list have same or similar title to the searched movie.  
Below is the implementation  
Python3
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # movie namename = "3 idiots" # searching the moviesearch = ia.search_movie(name) # printing the resultfor i in search:    print(i)
Output :  
3 Idiots
3 idiotas
3 Idiots
3 Idiots w/ GUNS
3 Idiots on Wheels
3 Idiots Try Candy!
3 Idiots; How Cho Copes with Slump
The Idiots
Idiots
Vidiots
Idiotest
The Idiot
Idiotsitter
Idiots
Idioten
4 Idiots
Idiots
Idiots
Los 3 Idiotas
iDiots
Another example:  
Python3
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # movie namename = "Tarzan the wonder car" # searching the moviesearch = ia.search_movie(name) # printing the resultprint(search)
Output :  
[Movie id:0435437[http] title:_Taarzan: The Wonder Car (2004)_>]
 
sagartomar9927
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Print all even numbers from 1 to n in PL/SQL

29 Jun, 2018
Prerequisite- PL/SQL Introduction
In PL/SQL code groups of commands are arranged within a block. It groups together related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a number N, the task is to display all the even numbers and their sum from 1 to N.
Examples:
Input: N = 3
Output: 2
Sum = 2

Input: N = 5
Output: 2, 4
Sum = 6

Approach is to initialize a number num with 2 and keep incrementing it by 2 until num is <= N.Below is its implementation:
-- Display all even number from 1 to nDECLARE    -- Declare variable num    num NUMBER(3) := 2;    sum1 NUMBER(4) := 0;BEGIN    WHILE num <= 5 LOOP          -- Display even number        dbms_output.Put_line(num);          -- Sum of even numbers        sum1 := sum1 + num;          -- Next even number        num := num + 2;                -- End  loop    END LOOP;      -- Display even number        dbms_output.Put_line('Sum of even numbers is ' || sum1);END;
Output:
2
4
Sum of even numbers is 6

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DDL and DML in DBMS
Window functions in SQL
SQL Correlated Subqueries
Difference between DELETE and TRUNCATE
Foundation - Pagination

Pagination is a type of navigation that divides the content into a series of related pages.
The following example demonstrates the use of pagination in Foundation −
<!doctype html>
   <head>
      <meta charset = "utf-8" />
      <meta http-equiv = "x-ua-compatible" content = "ie = edge" />
      <meta name = "viewport" content = "width = device-width, initial-scale = 1.0" />

      <title>Pagination</title>

      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/css/foundation.min.css" integrity="sha256-1mcRjtAxlSjp6XJBgrBeeCORfBp/ppyX4tsvpQVCcpA= sha384-b5S5X654rX3Wo6z5/hnQ4GBmKuIJKMPwrJXn52ypjztlnDK2w9+9hSMBz/asy9Gw sha512-M1VveR2JGzpgWHb0elGqPTltHK3xbvu3Brgjfg4cg5ZNtyyApxw/45yHYsZ/rCVbfoO5MSZxB241wWq642jLtA==" crossorigin="anonymous">

      <!-- Compressed JavaScript -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.0.1/js/vendor/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/foundation-sites@6.5.1/dist/js/foundation.min.js" integrity="sha256-WUKHnLrIrx8dew//IpSEmPN/NT3DGAEmIePQYIEJLLs= sha384-53StQWuVbn6figscdDC3xV00aYCPEz3srBdV/QGSXw3f19og3Tq2wTRe0vJqRTEO sha512-X9O+2f1ty1rzBJOC8AXBnuNUdyJg0m8xMKmbt9I3Vu/UOWmSg5zG+dtnje4wAZrKtkopz/PEDClHZ1LXx5IeOw==" crossorigin="anonymous"></script>
   </head>

   <body>
      <h2>Pagination Example</h2>

      <ul class = "pagination">
         <li class = "disabled">Previous</li>
         <li class = "current">1</li>
         <li><a href = "#">2</a></li>
         <li><a href = "#">3</a></li>
         <li><a href = "#">4</a></li>
         <li class = "ellipsis"></li>
         <li><a href = "#">12</a></li>
         <li><a href = "#">13</a></li>
         <li><a href = "#">Next</a></li>
      </ul>
   </body>
</html>
Let us carry out the following steps to see how the above given code works −
Save the above given html code pagination.html file.
Save the above given html code pagination.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.
Previous
1
2
3
4
12
13
Next

    117 Lectures 
     5.5 hours 

 Shakthi Swaroop

    61 Lectures 
     1.5 hours 

 Hans Weemaes

    17 Lectures 
     4 hours 

 Stephen Kahuria

    8 Lectures 
     50 mins

 Zenva

    28 Lectures 
     2 hours 

 Sandra L

    16 Lectures 
     2.5 hours 

 GreyCampus Inc.
 Print
 Add Notes
 Bookmark this page
HTML canvas fillStyle Property

The fillStyle() property of the HTML canvas is used to set the color or gradient or pattern for the drawing. The default is #000000. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.
Following is the syntax −
ctx.fillStyle=color|gradient|pattern;
Above, the values, include −
color: The drawing’s fill color, which is a CSS color.
gradient: Linear or radial gradient object to fill the drawing
pattern: The pattern object to fill the drawing.
Let us now see an example to implement the fillStyle() property of canvas −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<canvas id="newCanvas" width="500" height="350" style="border:2px solid orange;">
</canvas>
<script>
   var c = document.getElementById("newCanvas");
   var ctx = c.getContext("2d");
   var newGrad =ctx.createLinearGradient(0, 0, 130, 0);
   newGrad.addColorStop(0, "blue");
   newGrad.addColorStop(0.8, "green");
   ctx.fillStyle = newGrad;
   ctx.fillRect(0, 0, 500, 350);
</script>
</body>
</html>
Java Program to display double and single quote in a string

The following are our strings with single and double quote.
String str1 = "This is Jack's mobile";
String str2 = "\"This is it\"!";
Above, for single quote, we have to mention it normally like.
This is Jack's mobile
However, for double quotes, use the following and add a slash in the beginning as well as at the end.
String str2 = "\"This is it\"!";
The following is an example.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String str1 = "This is Jack's mobile";
      String str2 = "\"This is it\"!";
      System.out.println("Displaying Single Quote: "+str1);
      System.out.println("Displaying Double Quotes: "+str2);
   }
}
Displaying Single Quote: This is Jack's mobile
Displaying Double Quotes: "This is it"!