code-rag-bench/online-tutorials huggingface dataset:
is_displayed() element method - Selenium Python - GeeksforGeeks

27 Apr, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies
This article revolves around how to use is_displayed method in Selenium. is_displayed method is used to check if element it visible to user or not. It returns a boolean value True or False.
element.is_displayed()
Example –
<a href="https://www.geeksforgeeks.org/" id="link" />Text Here</a>
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("link")
element = driver.find_element_by_xpath("//a[@id='link']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_id("link")
Now one can check if this element is being displayed with
text_length = element.is_displayed()
Let’s use https://www.geeksforgeeks.org/ to illustrate this method in Selenium Python . Here we gcheck visibility of courses tab in navigation bar at geeksforgeeks.Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get element element = driver.find_element_by_link_text("Courses")  # print valueprint(element.is_displayed())
Output-
Terminal Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
How to add an element to a javascript object?

JavaScript object notation is like
var car = {name:"Benz", "Brand": "Mercedes", model:"open roof"};
 if we need to add the price of the Benz car then the code is as follows.
 Live Demo
<html>
<body>
<p id="demo"></p>
<script>
   var car = {name:"Benz", "Brand": "Mercedes", model:"open roof"};
   car.price = "50,000$",
   car.color = "Black"
   document.write(JSON.stringify(car));
</script>
</body>
</html>
{"name":"Benz","Brand":"Mercedes","model":"open roof","price":"50,000$","color":"Black"}
How to match a column in a data frame with a column in another data frame in R?

To match a column in a data frame with a column in another data frame, we can use match function. For example, if we have two data frames called df1 and df2 each having one similar column and the second having an extra column then the matching can be done for similar columns and a new column in the first data frame can be created based on that match and the second column the second data frame. Check out the below examples to understand how it works.
Live Demo
> df1<-data.frame(x1=sample(0:2,20,replace=TRUE))
> df1
   x1
1   2
2   2
3   1
4   0
5   2
6   2
7   2
8   2
9   2
10  1
11  1
12  2
13  1
14  0
15  2
16  2
17  2
18  2
19  2
20  2
> df2<-data.frame(x1=rpois(20,2),x2=rpois(20,5))
> df2
   x1 x2
1   2  5
2   2  5
3   3  6
4   0  5
5   1  3
6   1  5
7   2  6
8   1  3
9   4  6
10  0  5
11  1  0
12  3  4
13  1  3
14  1  4
15  2  6
16  1  5
17  2  2
18  3  8
19  0  5
20  1  6
> df1$x2<-df2$x2[match(df1$x1,df2$x1)]
> df1
   x1 x2
1   2  5
2   2  5
3   1  3
4   0  5
5   2  5
6   2  5
7   2  5
8   2  5
9   2  5
10  1  3
11  1  3
12  2  5
13  1  3
14  0  5
15  2  5
16  2  5
17  2  5
18  2  5
19  2  5
20  2  5
Live Demo
> y1<-sample(c("A","B","C"),20,replace=TRUE)
> df3<-data.frame(y1)
> df3
   y1
1   A
2   C
3   C
4   A
5   C
6   B
7   C
8   B
9   B
10  C
11  B
12  C
13  B
14  A
15  A
16  C
17  B
18  B
19  A
20  A
> y1<-sample(c("A","B","C","D","E"),20,replace=TRUE)
> y2<-sample(LETTERS[1:4],20,replace=TRUE)
> df4<-data.frame(y1,y2)
> df4
   y1 y2
1   E  C
2   A  D
3   C  B
4   C  D
5   D  B
6   B  D
7   D  C
8   C  B
9   D  D
10  C  A
11  B  D
12  B  C
13  C  B
14  B  D
15  D  C
16  B  B
17  E  C
18  D  B
19  A  D
20  B  C
> df3$y2<-df4$y2[match(df3$y1,df4$y1)]
> df3
   y1 y2
1   A  D
2   C  B
3   C  B
4   A  D
5   C  B
6   B  D
7   C  B
8   B  D
9   B  D
10  C  B
11  B  D
12  C  B
13  B  D
14  A  D
15  A  D
16  C  B
17  B  D
18  B  D
19  A  D
20  A  D
How to read contents of a file using Scanner class?

From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens).
To read various datatypes from the source using the nextXXX() methods provided by this class.
To read the contents of a file, Scanner class provides various constructors.
Assume we have a file myFile.txt in the path D:\ as shown below −
Following examples demonstrate how to read data from this file using the above constructors.
Create a File object representing your required file.
Create a Scanner class by passing the above created file object.
The hasNext() verifies whether the file has another line and the nextLine() method reads and returns the next line in the file. Using these methods read the contents of the file.
import java.io.File;
import java.util.Scanner;
public class ContentsOfFile {
   public static void main(String args[]) throws Exception {
      //Creating the File object
      File file = new File("D:\\MyFile.txt");
      //Creating a Scanner object
      Scanner sc = new Scanner(file);
      //StringBuffer to store the contents
      StringBuffer sb = new StringBuffer();
      //Appending each line to the buffer
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine());
      }
      System.out.println(sb);
   }
}
Hi welcome to Tutorialspoint ....
Create an FileInputStream object by passing the path of the required file to its constructor, as a parameter.
Create a Scanner class by passing the above created FileInputStream object.
The hasNext() verifies whether the file has another line and the nextLine() method reads and returns the next line in the file. Using these methods read the contents of the file.
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
public class ContentsOfFile {
   public static void main(String args[]) throws Exception {
      //Creating the File object
      InputStream inputStream = new FileInputStream("D:\\MyFile.txt");
      //Creating a Scanner object
      Scanner sc = new Scanner(inputStream);
      //StringBuffer to store the contents
      StringBuffer sb = new StringBuffer();
      //Appending each line to the buffer
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine());
      }
      System.out.println(sb);
   }
}
Hi welcome to Tutorialspoint ....
How to convert a datetime string to millisecond UNIX time stamp?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off. 
import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds)
This will give the output −
1514825676008
If you want to convert a datetime object to milliseconds timestamp, you can use the timestamp function then apply the same math as above to get the milliseconds time. 
import time
from datetime import datetime
dt = datetime(2018, 1, 1)
milliseconds = int(round(dt.timestamp() * 1000))
print(milliseconds)
This will give the output −
1514745000000
Python program to print a checkboard pattern of n*n using numpy.

Given the value of n, our task is to display the check board pattern for a n x n matrix.
Different types of functions to create arrays with initial value are available in numpy . NumPy is the fundamental package for scientific computing in Python.
Step 1: input order of the matrix.
Step 2: create n*n matrix using zeros((n, n), dtype=int).
Step 3: fill with 1 the alternate rows and columns using a slicing technique.
Step 4: print the matrix.

import numpy as np 
def checkboardpattern(n): 
   print("Checkerboard pattern:") 
   x = np.zeros((n, n), dtype = int) 
   x[1::2, ::2] = 1
   x[::2, 1::2] = 1
   # print the pattern 
   for i in range(n): 
      for j in range(n): 
         print(x[i][j], end =" ")  
      print()  
# Driver code 
n = int(input("Enter value of n ::>"))
checkboardpattern(n) 
Enter value of n ::>4
Checkerboard pattern:
0 1 0 1  
1 0 1 0  
0 1 0 1  
1 0 1 0
How to set margins in an Android LinearLayout programmatically?

This example demonstrate about How to set margins in an Android LinearLayout programmatically.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.java
<? xml version= "1.0" encoding= "utf-8" ?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
   xmlns: tools = "http://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :id= "@+id/linearLayout"
   android :layout_height= "match_parent"
   android :orientation= "vertical"
   tools :context= ".MainActivity" />
Step 3 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
import android.widget.Button ;
import android.widget.LinearLayout ;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState) ;
      setContentView(R.layout. activity_main ) ;
      LinearLayout ll = findViewById(R.id. linearLayout ) ;
      LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams. MATCH_PARENT ,
      LinearLayout.LayoutParams. WRAP_CONTENT ) ;
      layoutParams.setMargins( 30 , 20 , 30 , 0 ) ;
      Button okButton= new Button( this ) ;
      okButton.setText( "some text" ) ;
      ll.addView(okButton , layoutParams) ;
   }
}
Step 4 − Add the following code to androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.sample" >
   <uses-permission android :name= "android.permission.VIBRATE" />
   <application
      android :allowBackup= "true"
      android :icon= "@mipmap/ic_launcher"
      android:label= "@string/app_name"
      android:roundIcon= "@mipmap/ic_launcher_round"
      android:supportsRtl= "true"
      android:theme= "@style/AppTheme" >
      <activity android:name= ".MainActivity" >
         <intent-filter>
            <action android:name= "android.intent.action.MAIN" />
            <category android:name= "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
C++ Program to Implement Selection Sort

In the selection sort technique, the list is divided into two parts. In one part all elements are sorted and in another part the items are unsorted. At first we take the maximum or minimum data from the array. After getting the data (say minimum) we place it at the beginning of the list by replacing the data of first place with the minimum data. After performing the array is getting smaller. Thus this sorting technique is done.
Time Complexity: O(n2)
Time Complexity: O(n2)
Space Complexity: O(1)
Space Complexity: O(1)
Input − The unsorted list: 5 9 7 23 78 20
Output − Array after Sorting: 5 7 9 20 23 78
Input: An array of data, and the total number in the array
Output: The sorted Array
Begin
   for i := 0 to size-2 do //find minimum from ith location to size
      iMin := i;
      for j:= i+1 to size – 1 do
         if array[j] < array[iMin] then
            iMin := j
      done
      swap array[i] with array[iMin].
   done
End
#include<iostream>
using namespace std;
void swapping(int &a, int &b) {         //swap the content of a and b
   int temp;
   temp = a;
   a = b;
   b = temp;
}
void display(int *array, int size) {
   for(int i = 0; i<size; i++)
      cout << array[i] << " ";
   cout << endl;
}
void selectionSort(int *array, int size) {
   int i, j, imin;
   for(i = 0; i<size-1; i++) {
      imin = i;   //get index of minimum data
      for(j = i+1; j<size; j++)
         if(array[j] < array[imin])
            imin = j;
         //placing in correct position
         swap(array[i], array[imin]);
   }
}
int main() {
   int n;
   cout << "Enter the number of elements: ";
   cin >> n;
   int arr[n];           //create an array with given number of elements
   cout << "Enter elements:" << endl;
   for(int i = 0; i<n; i++) {
      cin >> arr[i];
   }
   cout << "Array before Sorting: ";
   display(arr, n);
   selectionSort(arr, n);
   cout << "Array after Sorting: ";
   display(arr, n);
}
Enter the number of elements: 6
Enter elements:
5 9 7 23 78 20
Array before Sorting: 5 9 7 23 78 20
Array after Sorting: 5 7 9 20 23 78
How to specify the file path in a tkinter filedialog?

Tkinter offers several built-in functions and class library methods to build components and user-actionable items of an application. filedialog is one of the tkinter modules that provides classes and library functions to create file/directory selection windows. You can use filedialog where you need to ask the user to browse a file or a directory from the system.
You can also specify the location of the directory from where a particular file should be picked up. To display the filedialog that starts from a particular location, use the initialdir = <location> argument in the static factory function askopenfilename(initialdir=<location>). This function creates a modal-like dialogbox and waits for the user's selection and returns the value of the selected file to the caller.
Let us create an application which asks the user to select a file from the system directory.
# Import required libraries
from tkinter import *
from tkinter import filedialog
from tkinter import ttk

# Create an instance of tkinter window
win = Tk()
win.geometry("700x350")

# Create an instance of style class
style=ttk.Style(win)

def open_win_diag():
   # Create a dialog box
   file=filedialog.askopenfilename(initialdir="C:/")
   f=open(win.file, 'r')

# Create a label widget
label=Label(win, text= "Click the button to browse the file", font='Arial 15 bold')
label.pack(pady= 20)

# Create a button to open the dialog box
button=ttk.Button(win, text="Open", command=open_win_diag)
button.pack(pady=5)

win.mainloop()
Running the above code will display a window that contains two widgets.
The button widget triggers the file dialog box, asking the user to browse the file from the system.
We have specified "initialdir=C:/" in the askopenfilename() function. Hence, it opens the C Drive as the initial directory.
Configuration file parser in Python (configparser)

The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have .INI extension.
The INI file consists of sections, each led by a [section] header. Between square brackets, we can put the section’s name. Section is followed by key/value entries separated by = or : character. It may include comments, prefixed by # or ; symbol. A sample INI file is shown below −
[Settings]
# Set detailed log for additional debugging info
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
# Sets the location of the MV_FTP log file
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown

[FTP]
# set the FTP server active
RunFTP=1
# defines the FTP control port
FTPPort=21
# Sets the location of the FTP data directory
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
# set the admin Name
UserName=admin
# set the Password
Password=admin
The configparser module has ConfigParser class. It is responsible for parsing a list of configuration files, and managing the parsed database.
Object of ConfigParser is created by following statement −
parser = configparser.ConfigParser()

Following methods are defined in this class −
Following script reads and parses the 'sampleconfig.ini' file
import configparser
parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')
for sect in parser.sections():
   print('Section:', sect)
   for k,v in parser.items(sect):
      print(' {} = {}'.format(k,v))
   print()
Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown

Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin
The write() method is used to create a configuration file. Following script configures the parser object and writes it to a file object representing 'test.ini'
import configparser
parser = configparser.ConfigParser()
parser.add_section('Manager')
parser.set('Manager', 'Name', 'Ashok Kulkarni')
parser.set('Manager', 'email', 'ashok@gmail.com')
parser.set('Manager', 'password', 'secret')
fp=open('test.ini','w')
parser.write(fp)
fp.close()
How to convert an std::string to const char* or char* in C++?

You can use the c_str() method of the string class to get a const char* with the string contents. 
#include<iostream>
using namespace std;

int main() {
   string x("hello");
   const char* ccx = x.c_str();
   cout << ccx;
}
This will give the output −
hello
To get a char*, use the copy function.
#include<iostream>
using namespace std;

int main() {
   string x("hello");

   // Allocate memory
   char* ccx = new char[s.length() + 1];

   // Copy contents
   std::copy(s.begin(), s.end(), ccx)
   cout << ccx;
}
This will give the output −
hello
Bootstrap class input-group-xs

To make extra small input group, use the input-group-xs.
You can try to run the following code to implement the input-group-xs class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div style = "padding: 100px 100px 10px; background: blue;">
         <form class = "bs-example bs-example-form" role = "form">
            <div class = "input-group input-group-xs">
               <span class = "input-group-addon">$</span>
               <input type = "text" class = "form-control">
            </div>
         </form>
      </div>
   </body>
</html>
Reverse bits of a positive integer number in Python - GeeksforGeeks

19 Nov, 2020
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.
Examples:
Input : n = 1, bitSize=32
Output : 2147483648  
On a machine with size of 
bit as 32. Reverse of 0....001 is
100....0.

Input : n = 2147483648, bitSize=32
Output : 1  

We can solve this problem quickly in Python. Approach is very simple,
Convert integer number into it’s binary representation using bin(num) function.bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string.As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize – len(reversedBits) number of zeros after reversing remaining string.Now convert binary representation into integer number using int(string,base) method.
Convert integer number into it’s binary representation using bin(num) function.
bin() function appends 0b as a prefix in binary representation of number, skip first two characters of binary representation and reverse remaining part of string.
As we know in memory any binary representation of a number is filled with leading zeros after last set bit from left that means we need to append bitSize – len(reversedBits) number of zeros after reversing remaining string.
Now convert binary representation into integer number using int(string,base) method.
int(string,base) method takes a string and base to identify that string is referring to what number system ( binary=2, heaxadecimal=16, octal=8 etc. ) and converts string into decimal number system accordingly. For example ; int(‘1010’,2) = 10.
# Function to reverse bits of positive  # integer number     def reverseBits(num,bitSize):          # convert number into binary representation      # output will be like bin(10) = '0b10101'      binary = bin(num)          # skip first two characters of binary      # representation string and reverse      # remaining string and then append zeros      # after it. binary[-1:1:-1]  --> start      # from last character and reverse it until      # second last character from left      reverse = binary[-1:1:-1]      reverse = reverse + (bitSize - len(reverse))*'0'         # converts reversed binary string into integer      print (int(reverse,2))     # Driver program if __name__ == "__main__":     num = 1    bitSize = 32    reverseBits(num,bitSize)
Output:
2147483648

base-conversion
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
How to update DB2 table with a duplicate primary key?

To maintain the integrity of a DB2 table the primary key is always unique in the entire
table. For example, if we have a DB2 table ORDERS which stores all the orders and the
primary key of the table is column ORDER_ID. Then there can be only a single row having
a particular order id. This will be useful to identify an order distinctly.
If we try to insert or update a row in a DB2 table having duplicate primary key using a
COBOL-DB2 program, we will get DB2 error code -803. As per the IBM documentation -
803 error code states the following−
“Unique index violation. Try to insert duplicate record (Duplicate Error)”
Convert character array to string in Arduino

In order to convert a character array to a string, the String() constructor can be used. An example is shown below −
void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   char buf[10] = "Hello!";

   Serial.print("Char array: ");
   Serial.println(buf);
   String s = String(buf);
   Serial.print("String: ");
   Serial.println(s);
}
void loop() {
   // put your main code here, to run repeatedly:
}
The output of the Serial monitor is shown below −
How to open new tab in same browser and switch between them using Selenium?

We can open new tabs in the same browser and switch between them using Selenium webdriver. Firstly, to open a new tab in the same browser we have to take the help of the methods – Keys.chord and sendKeys.
The parameters Keys.CONTROL and Keys.ENTER are passed to the Keys.chord method. This method yields a string value and in turn passed as a parameter to the sendKeys method.
String n = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.id("open-tab")).sendKeys(n);
Once the second tab is opened, the getWindowHandles method is used to hold all the window handle ids in a Set. To shift the focus of the webdriver object to the new tab, the method switchTo().window is used.
The window handle id of the new tab should be passed as a parameter to the switchTo().window to shift the driver focus to the new tab. The method getWindowHandle is used to obtain the window handle id of the browser window in focus.
Let us open the link Team in a new tab in the same browser −
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.Keys;
import java.util.ArrayList;
public class SwitchNewTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // method Keys.chord
      String n = Keys.chord(Keys.CONTROL, Keys.ENTER);
      //open link in new tab
      driver.findElement(By.linkText("Team")).sendKeys(n);
      Thread.sleep(8000);
      // store window handle ids
      ArrayList<String> w = new ArrayList<String>(driver.getWindowHandles());
      //switch to open tab
      driver.switchTo().window(w.get(1));
      System.out.println("New tab title: " + driver.getTitle());
      //switch to first tab
      driver.switchTo().window(w.get(0));
      System.out.println("First tab title: " + driver.getTitle());
      driver.quit();
   }
}
How to implement Python __lt__ __gt__ custom (overloaded) operators?

Python has magic methods to define overloaded behaviour of operators. The comparison operators (<, <=, >, >=, == and !=) can be overloaded by providing definition to __lt__, __le__, __gt__, __ge__, __eq__ and __ne__ magic methods.  Following program overloads < and > operators to compare objects of distance class. 
class distance:
  def __init__(self, x=5,y=5):
    self.ft=x
    self.inch=y

  def __eq__(self, other):
    if self.ft==other.ft and self.inch==other.inch:
      return "both objects are equal"
    else:
      return "both objects are not equal"

  def __lt__(self, other):
    in1=self.ft*12+self.inch
    in2=other.ft*12+other.inch
    if in1<in2:
      return "first object smaller than other"
    else:
      return "first object not smaller than other"

  def __gt__(self, other):
    in1=self.ft*12+self.inch
    in2=other.ft*12+other.inch
    if in1<in2:
      return "first object greater than other"
    else:
      return "first object not greater than other"

d1=distance(5,5)
d2=distance()
print (d1>d2)
d3=distance()
d4=distance(6,10)
print (d1<d2)
d5=distance(3,11)
d6=distance()
print(d5<d6)
Result shows implementation of __lt__ and _gt__ magic methods
first object not greater than other
first object not smaller than other
first object smaller than other
How to Set Classpath in Java? - GeeksforGeeks

20 Nov, 2020
CLASSPATH describes the location where all the required files are available which are used in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate the required files. If the CLASSPATH is not set, Java Compiler will not be able to find the required files and hence will throw the following error.
Error: Could not find or load main class <class name> (e.g. GFG)

The above error is resolved when CLASSPATH is set.
Java
// If the following code is run when the CLASSPATH is not// set, it will throw the above error.  // If it is set, we get the desired result  import java.io.*;  class GFG {    public static void main(String[] args)    {          // prints GeeksForGeeks to the console        System.out.println("GeekForGeeks!");    }}
GeekForGeeks!


Command Prompt:
set PATH=.;C:\Program Files\Java\JDK1.6.20\bin

Note: Semi-colon (;) is used as a separator and dot (.) is the default value of CLASSPATH in the above command.
1. Select Start
2. Go to the Control Panel
3. Select System and Security
4. Select Advanced System settings
5. Click on Environment Variables
6. Click on New under System Variables
7. Add CLASSPATH as variable name and path of files as a variable value.
8. Select OK.
Command Line:
Find out where you have installed Java, basically, it’s in /usr/lib/jvm path. Set the CLASSPATH in /etc/environment using 
sudo <editor name> /etc/environment

Add the following lines,
JAVA_HOME = "/usr/lib/jvm/<java folder (eg. java-1.8.0-openjdk-amd64>)/bin"
export JAVA_HOME
CLASSPATH=".:/usr/lib/jvm/<java folder>/lib:/home/name/Desktop"
export CLASSPATH


Note: Colon (:) is used as a separate directory and dot (.) is the default value of CLASSPATH in the above command.
To check the current CLASSPATH, run 
echo ${CLASSPATH}

Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Initialize an ArrayList in Java
Overriding in Java
Collections in Java
Singleton Class in Java
Multithreading in Java
Main thread vs child thread in C#

The first thread to be executed in a process is called the main thread. When a C# program starts execution, the main thread is automatically created.
The threads created using the Thread class are called the child threads of the main thread.
Here is an example showing how to create a main and child thread −
 Live Demo
using System;
using System.Threading;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Thread th = Thread.CurrentThread;
         th.Name = "MainThread";
         Console.WriteLine("This is {0}", th.Name);
         Console.ReadKey();
      }
   }
}
This is MainThread
Battleships in a Board in C++

Suppose we have an 2D board, we have to count how many battleships are in it. The battleships are represented with the symbol 'X', empty slots are represented with '.'s. We can assume these rules −
You receive a valid board, made of only battleships or empty slots.
You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
So if the board is like:
Then the output will be 2, as there are two battleships.
To solve this, we will follow these steps −
ans := 0, n := row count and m := column count
ans := 0, n := row count and m := column count
for ith rowfor jth columnif board[i, j] is dot, then go for the next iterationif i > 0 and board[i – 1, j] = ‘X’, then go for the next iterationif j > 0 and board[i, j - 1] = ‘X’, then go for the next iterationincrease ans by 1
for ith row
for jth columnif board[i, j] is dot, then go for the next iterationif i > 0 and board[i – 1, j] = ‘X’, then go for the next iterationif j > 0 and board[i, j - 1] = ‘X’, then go for the next iterationincrease ans by 1
for jth column
if board[i, j] is dot, then go for the next iteration
if board[i, j] is dot, then go for the next iteration
if i > 0 and board[i – 1, j] = ‘X’, then go for the next iteration
if i > 0 and board[i – 1, j] = ‘X’, then go for the next iteration
if j > 0 and board[i, j - 1] = ‘X’, then go for the next iteration
if j > 0 and board[i, j - 1] = ‘X’, then go for the next iteration
increase ans by 1
increase ans by 1
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int countBattleships(vector<vector<char>>& board) {
      int ans = 0;
      int n = board.size();
      int m = board[0].size();
      for(int i = 0; i < n; i++){
         for(int j = 0; j < m; j++){
            if(board[i][j] == '.')continue;
            if(i > 0 && board[i - 1][j] == 'X')continue;
            if(j > 0 && board[i][j - 1] == 'X')continue;
            ans++;
         }
      }
      return ans;
   }
};
main(){
   vector<vector<char>> v = {{'X','.','.','X'},{'.','.','.','X'},{'.','.','.','X'}};
   Solution ob;
   cout << (ob.countBattleships(v));
}
[["X",".",".","X"],[".",".",".","X"],[".",".",".","X"]]
2
Enum in a class in Java

Yes, we can create Enum in a class in Java.
Set the enum inside the class. Here, we have an Enum with four constants −
enum Devices {
LAPTOP, MOBILE, TABLET, DESKTOP;
}
Now, create objects inside the main() method −
Devices d = Devices.MOBILE;
System.out.println(d);
d = Devices.DESKTOP;
System.out.println(d);
The following is the complete example −
 Live Demo
public class Demo {
   enum Devices {
      LAPTOP, MOBILE, TABLET, DESKTOP;
   }
   public static void main(String[] args) {
      Devices d = Devices.MOBILE;
      System.out.println(d);
      d = Devices.DESKTOP;
      System.out.println(d);
      d = Devices.TABLET;
      System.out.println(d);
   }
}
MOBILE
DESKTOP
TABLET
C++ Map Library - ~map() Function

The C++ destructor std::map::~map() destroys map object by deallocating it's memory.
Following is the declaration for std::map::~map() function form std::map header.
~map();

None
Destructor never returns value.
This member function never throws exception.
Linear i.e. O(n)
 Print
 Add Notes
 Bookmark this page
chr () in Python

This function return the string representing a character whose Unicode code point is the integer supplied as parameter to this function. For example, chr(65) returns the string 'A', while chr(126) returns the string '~'.
The syntax of the function is as below.
chr(n) where n is an integer value
The below program shows how the chr() is used. We supply various integer values as parameter and get back the respective characters.
 Live Demo
# Printing the strings from chr() function
print(chr(84),chr(85),chr(84),chr(79),chr(82))
Running the above code gives us the following result −
T U T O R
We can take help of python data structures like lists to loop through a series of numbers and apply char function to create a required string. In the below example we see that we have used a list to
 Live Demo
str = ""
series = [84,85,84,79,82,73,65,76,83]
for i in range(0,len(series)):
   char = chr(series[i])
   str = str + char
   i=i+1
print(str)
Running the above code gives us the following result −
TUTORIALS
Rexx - ADDRESS

This method returns the name of the environment in the which the Rexx commands are currently running in.
ADDRESS() 

None
This method returns the name of the environment in the which the Rexx commands are currently running in.
/* Main program */ 
say ADDRESS()
When we run the above program we will get the following result.
bash

 Print
 Add Notes
 Bookmark this page
std::basic_istream::gcount() in C++ with Examples - GeeksforGeeks

21 May, 2020
The std::basic_istream::gcount() is used to count the characters in the given string. It returns the number of characters extracted by the last unformatted input operation. The unformatted input operation is returned by these function: get(), getline(), ignore(), peek(), read(), etc.
Header File:
<iostream>

Syntax:
streamsize gcount() const

Parameter: This method doesn’t accepts any parameter.
Return Value: It returns the number of characters extracted by the last unformatted input operation.
Below is the program to illustrate std::basic_istream::gcount():
Program 1:
// C++ code to illustrate std::gcount()  #include <bits/stdc++.h>using namespace std;  // Driver Codeint main(){      // Initialise array of characters    char arr[20];      // Declare string stream    istringstream stream("GeeksforGeeks");      // Read the string in string stream    stream.read(arr, sizeof arr);      // Print the count of characters in    // string "GeeksforGeeks"    cout << "The count of characters"         << " in the string "         << " is " << stream.gcount()         << endl;      return 0;}
The count of characters in the string  is 13

References: http://www.cplusplus.com/reference/istream/basic_istream/gcount/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Python String rstrip() Method

19 Aug, 2021
Python String rstrip() method returns a copy of the string with trailing characters removed (based on the string argument passed). If no argument is passed, it removes trailing spaces.
Syntax: 
string.rstrip([chars])
Parameters:
chars (optional) – a string specifying the set of characters to be removed.
Returns:
Returns a copy of the string with trailing characters stripped
Python3
# Python3 program to demonstrate the use of# rstrip() method using optional parameters # string which is to be strippedstring = "geekssss" # Removes given set of characters from# right.print(string.rstrip('s'))
Output: 
geek
Python3
# Python3 program to demonstrate the use of# rstrip() method using optional parameters # string which is to be strippedstring = "   for    " # Leading whitespaces are removedprint("Geeks" + string.rstrip() + " Geeks ")
Output: 
Geeks   for Geeks
Python3
# string which is to be strippedstring = "geeks for geeks" # Argument doesn't contain trailing 's'# So, no characters are removedprint(string.rstrip('ek'))
Output: 
geeks for geeks
Python3
# string which is to be strippedstring = "geeks for geeks" # Removes given set of characters from# right.print(string.rstrip('ske'))
Output: 
geeks for g
AmiyaRanjanRout
python-string
Python-string-functions
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
How to Install PIP on Windows ?
D3.js node.sort() Function - GeeksforGeeks

31 Aug, 2020
The node.sort() function in D3.js is used to sort the children at each level of the given hierarchical data. The comparator function can be used to define the basis on which the sorting would be done.
Syntax:
node.sort( compare )
Parameters: This function accepts a single parameter as mentioned above and described below:
compare: It is a function that specifies the basis on which sorting should be done.
Return Value: This function returns an object.
Below example illustrates the node.sort() function in D3.js:
Example 1:
HTML
<!DOCTYPE html><html>  <head>    <script src="https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>          // Construct a tree        var tree = {              // Specify the root node            name: "rootNode",            children: [                { value: 1 },                { value: 2 },                { value: 3 },                { value: 4 },                { value: 5 },                { value: 6 },            ]        };          var obj = d3.hierarchy(tree);          // Use the sort() function to sort        // the nodes in descending order        var sorted = obj.sum(d => d.value)            .sort((a, b) =>                d3.descending(a.value, b.value));          // Show the sorted output        console.log(            sorted.children.map(                d => ["value", d.value])        );    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html>  <head>    <script src="https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>        // Construct a tree        var tree = {              // Specify the root node            name: "rootNode",            children: [                { value: 1 },                { value: 2 },                { value: 3 },                { value: 4 },                { value: 5 },                { value: 6 },            ]        };          var obj = d3.hierarchy(tree);          // Use the sort() function to sort        // the nodes in ascending order        var sorted = obj.sum(d => d.value)            .sort((a, b) =>                d3.ascending(a.value, b.value));          // Show the sorted output        console.log(            sorted.children.map(d => ["value", d.value])        )    </script></body>  </html>
Output:
D3.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
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create an unordered_map of pairs in C++?

In this tutorial, we will be discussing a program to understand how to create an unordered map of pairs in C++.
Unordered maps are the ones that don't contain hash function for the pairs by default. If we want a hash value for a particular pair, it needs to be passed on explicitly.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//to hash any given pair
struct hash_pair {
   template <class T1, class T2>
   size_t operator()(const pair<T1, T2>& p) const{
      auto hash1 = hash<T1>{}(p.first);
      auto hash2 = hash<T2>{}(p.second);
      return hash1 ^ hash2;
   }
};
int main(){
   //explicitly sending hash function
   unordered_map<pair<int, int>, bool, hash_pair> um;
   //creating some pairs to be used as keys
   pair<int, int> p1(1000, 2000);
   pair<int, int> p2(2000, 3000);
   pair<int, int> p3(2005, 3005);
   um[p1] = true;
   um[p2] = false;
   um[p3] = true;
   cout << "Contents of the unordered_map : \n";
   for (auto p : um)
      cout << "[" << (p.first).first << ", "<< (p.first).second << "] ==> " << p.second << "\n";
   return 0;
}
Contents of the unordered_map :
[1000, 2000] ==> 1
[2005, 3005] ==> 1
[2000, 3000] ==> 0
Python Pandas - Create a Horizontal Bar Chart

To plot a Horizontal Bar Plot, use the pandas.DataFrame.plot.barh. A bar plot shows comparisons among discrete categories.
At first, import the required libraries −
import pandas as pd
import matplotlib.pyplot as plt
Create a Pandas DataFrame with 4 columns −
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})
Plot Horizontal Bar Chart using the plot.barh() −
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')

Following is the complete code −
import pandas as pd
import matplotlib.pyplot as plt

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})

# plotting Horizontal Bar Chart
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')

# set the label
plt.xlabel("CC (Cubic Capacity)" )

# display the plotted Horizontal Bar Chart
plt.show()
This will produce the following output −
How to call a parent window function from an iframe using JavaScript?

To call a parent window function, use “window.top”.
You can try to run the following code to call a parent window function from an iframe
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         function display(){
            alert("Hello World!");
         }
      </script>
      <iframe id="myFrame">
         <a onclick="window.top.display();" href="#">Click</a>
      </iframe>
   </body>
</html>
\odot - Tex Command

\odot - Used to create odot symbol.
{ \odot}
\odot command draws odot symbol.

\odot

⊙



\odot

⊙


\odot

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
C Quiz - 101 | Question 2 - GeeksforGeeks

28 Jun, 2021
Assume int is 4 bytes, char is 1 byte and float is 4 bytes. Also, assume that pointer size is 4 bytes (i.e. typical case)
char *pChar;int *pInt;float *pFloat;  sizeof(pChar);sizeof(pInt);sizeof(pFloat);
What’s the size returned for each of sizeof() operator?(A) 4 4 4(B) 1 4 4(C) 1 4 8(D) None of the aboveAnswer: (A)Explanation: Irrespective of the type of pointer, the size for a pointer is always same. So whether it’s pointer to char or pointer to float, the size of any pointer would be same. Even size of a pointer to user defined data type (e.g. struct) is also would be same.Quiz of this Question
C Quiz - 101
C-C Quiz - 101
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
C | Misc | Question 7
How to display Material Chip View in React Native?

To display chips in the UI, we are going to make use of React Native Paper Material
Design.
Install react native paper as shown below −
npm install --save-dev react-native-paper
The chip component looks as follows on the UI −
The basic chip component is as follows −
<Chip icon="icontodisplay" onPress={onPressfunc}>Chip Name</Chip>
The basic properties of chip are as follows −
The code that displays chip is as follows −
<SafeAreaView style={styles.container}>
   <Chip icon="camera" disabled onPress={() => console.log('camera')}>Click
      Here</Chip>
      <Chip icon="apple" mode="outlined"selectedColor='green' selected
         onPress={() => console.log('apple')}>Apple Icon</Chip>
</SafeAreaView>
import * as React from 'react';
import { StyleSheet, Text, SafeAreaView } from 'react-native';
import { Chip } from 'react-native-paper';
const MyComponent = () => (
   <SafeAreaView style={styles.container}>
      <Chip icon="camera" style={styles.chip} disabled onPress={() =>
         console.log('camera')}>Click Here</Chip>
         <Chip icon="apple" style={styles.chip}
            mode="outlined"selectedColor='green' selected onPress={() =>
            console.log('apple')}>Apple Icon</Chip>
         <Chip icon="calendar-month" style={styles.chip} mode="outlined" selected
            onPress={() => console.log('calendar')}>Select Date</Chip>
      </SafeAreaView>
   );
   export default MyComponent;
   const styles = StyleSheet.create({
   container: {
      flex: 1,
      alignItems: "center",
      justifyContent: "center"
   },
   chip: {
      marginTop:10
   }
});