code-rag-bench/online-tutorials huggingface dataset:
C# | Check whether a SortedList object contains a specific key - GeeksforGeeks

01 Feb, 2019
SortedList.Contains(Object) Method is used to check whether a SortedList object contains a specific key.
Syntax:
public virtual bool Contains (object key);
Here, key is the Key which is to be located in the SortedList object.
Return Value: This method returns the true if the SortedList object contains an element with the specified key otherwise, it returns false
Exceptions:
ArgumentNullException: If the key is null.
InvalidOperationException: If the comparer throws an exception.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to Check whether a SortedList// object contains a specific keyusing System;using System.Collections;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // Creating a SortedList of integers        SortedList mylist = new SortedList();          // Adding elements to SortedList        mylist.Add("1", "C++");        mylist.Add("2", "Java");        mylist.Add("3", "DSA");        mylist.Add("4", "Python");        mylist.Add("5", "C#");          // Checking whether 4 is present        // in SortedList or not        Console.Write(mylist.Contains("4"));    }}
Output:
True

Example 2:
// C# code to Check whether a SortedList// object contains a specific keyusing System;using System.Collections;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // Creating a SortedList of integers        SortedList mylist = new SortedList();          // Adding elements to SortedList        mylist.Add("First", "Ram");        mylist.Add("Second", "Shyam");        mylist.Add("Third", "Mohit");        mylist.Add("Fourth", "Rohit");        mylist.Add("Fifth", "Manish");          // Checking whether 10 is present        // in SortedList object or not        Console.Write(mylist.Contains("Sixth"));    }}
Output:
False

Note:
Contains implements IDictionary.Contains. It behaves exactly as ContainsKey.
This method uses a binary search algorithm; therefore, this method is an O(log n) operation, where n is Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.contains?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-SortedList
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
C Program to Add two Integers - GeeksforGeeks

12 Jan, 2022
Given two numbers A and B. The task is to write a program to find the addition of these two numbers. 
Examples:  
Input: A = 2, B = 3
Output: 5

Input: A = 3, B = 6
Output: 9
 
In the below program to add two numbers, the user is first asked to enter two numbers and the input is scanned using the scanf() function and stored in the variables and . Then, the variables and are added using the arithmetic operator and the result is stored in the variable sum.Below is the C program to add two numbers:  
C
// C program to add two numbers#include<stdio.h> int main(){    int A, B, sum = 0;         // Ask user to enter the two numbers    printf("Enter two numbers A and B : \n");         // Read two numbers from the user || A = 2, B = 3    scanf("%d%d", &A, &B);         // Calculate the addition of A and B    // using '+' operator    sum = A + B;         // Print the sum    printf("Sum of A and B is: %d", sum);         return 0;}
Output:  
Enter two numbers A and B : 2 3
Sum of A and B is: 5
 
sagar0719kumar
C-Operators
school-programming
C Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Difference between break and continue statement in C
Python Dictionary
Arrays in C/C++
Reverse a string in Java
Inheritance in C++
C++ Classes and Objects
How to filter single column of a matrix with column name in R?

To filter a single column of a matrix in R if the matrix has column names, we can simply use single square brackets but this will result in a vector without the column name. If we want to use the column name then column name or column number needs to be passed with drop=FALSE argument as shown in the below examples.
Live Demo
> M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4)
> colnames(M1)<-c("V1","V2","V3","V4")
> M1
      V1 V2 V3 V4
[1,]  0  0  1  0
[2,]  1  1  1  1
[3,]  0  0  0  0
[4,]  0  1  1  0
[5,]  1  1  1  1
[6,]  0  1  1  0
[7,]  0  1  0  1
[8,]  1  1  0  1
[9,]  1  1  0  1
[10,] 0  0  1  0
[11,] 0  0  0  1
[12,] 0  1  0  0
[13,] 0  0  0  0
[14,] 1  0  0  0
[15,] 0  1  0  1
[16,] 0  0  1  0
[17,] 1  1  1  1
[18,] 1  0  1  1
[19,] 1  0  1  1
[20,] 0  0  0  0
Extracting column V1 from M1 −
> M1[,"V1",drop = FALSE]
      V1
[1,]  0
[2,]  1
[3,]  0
[4,]  0
[5,]  1
[6,]  0
[7,]  0
[8,]  1
[9,]  1
[10,] 0
[11,] 0
[12,] 0
[13,] 0
[14,] 1
[15,] 0
[16,] 0
[17,] 1
[18,] 1
[19,] 1
[20,] 0
Live Demo
> M2<-matrix(sample(c("Yes","No"),40,replace = TRUE),ncol=2)
> colnames(M2)<-c("Binary1","Binary2")
> M2
    Binary1 Binary2
[1,]  "Yes" "Yes"
[2,]  "Yes" "No"
[3,]  "Yes" "No"
[4,]  "Yes" "Yes"
[5,]  "Yes" "Yes"
[6,]  "No"  "No"
[7,]  "Yes" "Yes"
[8,]  "No"  "Yes"
[9,]  "No"  "No"
[10,] "Yes" "Yes"
[11,] "Yes" "Yes"
[12,] "Yes" "No"
[13,] "Yes" "No"
[14,] "No"  "Yes"
[15,] "No"  "Yes"
[16,] "Yes" "Yes"
[17,] "No"  "Yes"
[18,] "Yes" "Yes"
[19,] "Yes" "Yes"
[20,] "No"  "No"
Extracting column Binary2 from M2 −
> M2[,"Binary2",drop = FALSE]
     Binary2
[1,]  "Yes"
[2,]  "No"
[3,]  "No"
[4,]  "Yes"
[5,]  "Yes"
[6,]  "No"
[7,]  "Yes"
[8,]  "Yes"
[9,]  "No"
[10,] "Yes"
[11,] "Yes"
[12,] "No"
[13,] "No"
[14,] "Yes"
[15,] "Yes"
[16,] "Yes"
[17,] "Yes"
[18,] "Yes"
[19,] "Yes"
[20,] "No"
Decimal to binary list conversion in Python

Python being a versatile language can handle many requirements that comes up during the data processing. When we need to convert a decimal number to a binary number we can use the following python programs.
We can Use the letter in the formatter to indicate which number base: decimal, hex, octal, or binary we want our number to be formatted. In the below example we take the formatter as 0:0b then supply the integer to the format function which needs to get converted to binary.
 Live Demo
Dnum = 11

print("Given decimal : " + str(Dnum))

# Decimal to binary number conversion
binnum = [int(i) for i in list('{0:0b}'.format(Dnum))]

# Printing result
print("Converted binary list is : ",binnum)
Running the above code gives us the following result −
Given decimal : 11
Converted binary list is : [1, 0, 1, 1]
The bin() is a in-built function which can also be used in a similar way as above. This function Python bin() function converts an integer number to a binary string prefixed with 0b. So we slice the first two characters.
 Live Demo
Dnum = 11

print("Given decimal : " + str(Dnum))

# Decimal to binary number conversion
binnum = [int(i) for i in bin(Dnum)[2:]]

# Printing result
print("Converted binary list is : ",binnum)

Running the above code gives us the following result −
Given decimal : 11
Converted binary list is : [1, 0, 1, 1]
Differences between Collection and Collections in Java?

The Collection is an interface whereas Collections is a utility class in Java. The Set, List, and Queue are some of the subinterfaces of Collection interface, a Map interface is also part of the Collections Framework, but it doesn't inherit Collection interface. The important methods of Collection interface are add(), remove(), size(), clear() etc and Collections class contains only static methods like sort(), min(), max(), fill(), copy(), reverse() etc.
public interface Collection<E> extends Iterable<E>
public class Collections extends Object
import java.util.*;
public class CollectionTest {
   public static void main(String args[]) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      // Adding elements to the ArrayList
      list.add(5);
      list.add(20);
      list.add(35);
      list.add(50);
      list.add(65);
      // Collections.min() method to display minimum value
      System.out.println("Minimum value: " + Collections.min(list));
      // Collections.max() method to display maximum value
      System.out.println("Maximum value: " + Collections.max(list));
   }
}
Minimum value: 5
Maximum value: 65
Comparing enum members in Java


The java.lang.Enum class is the common base class of all Java language enumeration types.
Following is the declaration for java.lang.Enum class -
public abstract class Enum<E extends Enum<E>>
   extends Object
      implements Comparable<E>, Serializable
We can compare enum variables using the following ways.
Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order.
Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order.
Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant.
Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant.
Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants.
Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants.
Live Demo
public class Tester {
   // enum showing topics covered under Tutorials
   enum Tutorials {        
      TOPIC_1, TOPIC_2, TOPIC_3;    
   }  

   public static void main(String[] args) {
      Tutorials t1, t2, t3;
 
      t1 = Tutorials.TOPIC_1;        
      t2 = Tutorials.TOPIC_2;        
      t3 = Tutorials.TOPIC_3;  

      //Comparing using compareTo() method
      if(t1.compareTo(t2) > 0) {
         System.out.println(t2 + " completed before " + t1);        
      }

       if(t1.compareTo(t2) < 0) {
         System.out.println(t1 + " completed before " + t2);        
      }

      if(t1.compareTo(t2) == 0) {          
         System.out.println(t1 + " completed with " + t2);        
      }

      //Comparing using ==      
      //In this case t1 can be null as well causing no issue
      if(t1 == Tutorials.TOPIC_1) {
         System.out.println("t1 = TOPIC_1");
      }else {
         System.out.println("t1 != TOPIC_1");
      }

      //Comparing using equals() method
      //In this case t2 cannot be null. It will cause
      //null pointer exception
      if(t2.equals(Tutorials.TOPIC_2)) {
         System.out.println("t2 = TOPIC_2");
      }else {
         System.out.println("t2 != TOPIC_2");
      }

      Tutorials t4 = null;  
      //Comparing using equals() method
      //in null safe manner
      if(Tutorials.TOPIC_3.equals(t4)) {
         System.out.println("t4 = TOPIC_3");
      }else {
         System.out.println("t4 != TOPIC_3");
      }          
   }
}
TOPIC_1 completed before TOPIC_2
t1 = TOPIC_1
t2 = TOPIC_2
t4 != TOPIC_3
HTML | <input> accept Attribute - GeeksforGeeks

02 Dec, 2021
The HTML <input> accept Attribute is used to specifies the type of file that the server accepts. This attribute can be used with <input type=”file”> element only. This attribute is not used for validation tool because file uploads should be validated on the Server.Syntax:  
<input accept = "file_extension | audio/* | video/* | image/* | media_type">
Attribute Values  
file_extension: It Specify the file extension(s) like .gif, .jpg, .png, .doc) the user can pick from.
audio/*: The user can pick all sound files.
video/*: The user can pick all video files.
image/*: :A valid media type, with no parameters. Look at IANA Media Types for a complete list standard media types
media_type: A valid media type without parameters.
Example: 
html
<!DOCTYPE html><html> <head>    <title>      HTML input accept attribute  </title>    <style>        body {            text-align: center;        }                 h1 {            color: green;        }    </style></head> <body>    <h1>GeeksForGeeks</h1>    <h2>      HTML <input> accept attribute  </h2>    <form action=" ">        <input type="file"               name="picture"               accept="image/*">               <input type="submit">    </form></body> </html>
Output: 
Supported Browsers: The browsers supported by HTML <input> accept Attribute are listed below: 
Google Chrome 8.0
Internet Explorer 10.0
Firefox 4.0
Apple Safari 6.0
Opera 15.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
varshagumber28
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Python Program to implement Full Subtractor - GeeksforGeeks

21 Nov, 2021
Prerequisite –Full Subtractor in Digital Logic
In this, we will discuss the overview of the full subtractor and will implement the full subtractor logic in the python language. Also, we will cover with the help of examples. Let’s discuss it one by one.
Given three inputs of Full Subtractor A, B, Bin. The task is to implement the Full Subtractor circuit and Print output i.e Difference (d) and B-Out of three inputs.
Full Subtractor :
The full Subtractor is a combinational circuit that is used to perform subtraction of three input bits: the minuend, subtrahend, and borrow in. The full Subtractor generates two output bits: the difference and borrow out.
Logical Expression :
Difference = (A XOR B) XOR Bin
Borrow Out = Ā Bin + Ā B + B Bin
Truth Table :
Examples :
Input       : 0 1 1
Output      : Difference=0, B-Out=1
Explanation : According to logical expression Difference= (A XOR B) XOR Bin  i.e (0 XOR 1) XOR 1  =0 ,
B-Out=Ā Bin + Ā B + B Bin  i.e  1 AND 1 + 1 AND 1 + 1 AND 1 = 1

Input       : 1 0 0
Output      : Difference=1, B-Out=0
Approach :
We take three inputs A, B, and Bin.
Applying (A XOR B) XOR Bin gives the Value of Difference.
Applying Ā Bin + Ā B + B Bin gives the value of B-Out.
Below is the implementation :
Python3
# python program to implement full Subtractor# Function to print Difference and B-Out def getResult(A, B, Bin):     # Calculating value of Difference    Difference = (A ^ B) ^ Bin         # calculating NOT  value of a    A1 = not(A)         # Calculating value of B-Out    B_Out = A1 & Bin | A1 & B | B & Bin     # printing the values    print("Difference = ", Difference)    print("B-Out = ", B_Out)  # Driver codeA = 0B = 1Bin = 1# passing three inputs of fullsubtractor as arguments to get result functiongetResult(A, B, Bin)
Output :
Difference =  0
B-Out      =  1
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
simranarora5sos
adnanirshad158
Technical Scripter 2020
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shift Registers in Digital Logic
Difference between Unipolar, Polar and Bipolar Line Coding Schemes
Flip-flop types, their Conversion and Applications
Counters in Digital Logic
Introduction to memory and memory units
Master-Slave JK Flip Flop
Difference between Half adder and full adder
Difference between combinational and sequential circuit
Design 101 sequence detector (Mealy machine)
Analog to Digital Conversion
How to flatten a Vector of Vectors or 2D Vector in C++ - GeeksforGeeks

07 Apr, 2020
Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector.
Examples:
Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]]Output: 1 2 3 4 5 6 7 8
Input: vector = [[1, 2], [3], [4, 5, 6, 8]]Output: 1 2 3 4 5 6 8
Algorithm:
2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively.Create a hasNext() method to check if it has the vector has next element or not.Print the current element, if hasNext() yields true
2D Vector can be flattened using iterators.
Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively.
Create a hasNext() method to check if it has the vector has next element or not.
Print the current element, if hasNext() yields true
Below is the implementation of the above approach:
// C++ program to flatten a// Vector of Vectors or 2D Vector  #include <bits/stdc++.h>using namespace std;  // Class to flatten the 2d vectorclass FlattenVector {  public:    int n;      vector<vector<int>::iterator> iStart;    vector<vector<int>::iterator> iEnd;    int currIndex;      // Store ending and starting iterators.    FlattenVector(vector<vector<int> >& v)    {          // Get the number        // of rows in 2d vector        n = v.size();        currIndex = 0;        iStart.resize(n);        iEnd.resize(n);          for (int i = 0; i < n; i++) {            iStart[i] = v[i].begin();            iEnd[i] = v[i].end();        }    }      // Returns true if any element is left.    bool hasNext()    {        for (int i = 0; i < n; i++) {            if (iStart[i] != iEnd[i])                return true;        }        return false;    }      int next()    {        // Vector at currIndex is printed,        // increment currIndex.        if (iStart[currIndex]            == iEnd[currIndex]) {            currIndex++;            return next();        }          // Increment iterator        // and return the value.        else            return *iStart[currIndex]++;    }};  // Driver codeint main(){    vector<vector<int> >        v{ { 1, 2 },           { 3 },           { 4, 5, 6 },           { 7, 8, 9, 10 } };    FlattenVector iter(v);      while (iter.hasNext())        cout << iter.next() << " ";      return 0;}
1 2 3 4 5 6 7 8 9 10

cpp-iterator
cpp-vector
Arrays
C++
Recursion
Arrays
Recursion
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Multidimensional Arrays in Java
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL
C++ Classes and Objects
Matplotlib.axes.Axes.broken_barh() in Python - GeeksforGeeks

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.broken_barh() function in axes module of matplotlib library is used to plot a horizontal sequence of rectangles.
Syntax:
Axes.broken_barh(self, xranges, yrange, *, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
y: This parameter is the sequence of y coordinates of the bar.
xranges: This parameter is the sequence of tuples (xmin, xwidth).It is the x-positions and extends of the rectangles.
yrange: This parameter is the sequence of tuples (ymin, yheight).It is the y-positions and extends for all the rectangles.
Returns: This returns the following:
BrokenBarHCollection:This returns the container with all the broken_barh.
Below examples illustrate the matplotlib.axes.Axes.broken_barh() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()ax.broken_barh([(110, 30), (150, 10)],               (10, 9),                facecolors ='tab:green')  ax.set_xlabel('x')ax.set_ylabel('y')ax.grid(True)  ax.set_title('matplotlib.axes.Axes.\broken_barh Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  fig, ax = plt.subplots()ax.broken_barh([(110, 30), (150, 10)],                (10, 9),                facecolors ='tab:green')  ax.broken_barh([(100, 20),                (130, 10)],                (20, 9),                facecolors =('tab:green'))  ax.set_ylim(5, 35)ax.set_xlim(50, 200)ax.set_xlabel('Learning Rate')ax.set_yticks([15, 25])ax.set_yticklabels(['Geeks1', 'Geeks2'])ax.grid(True)  ax.annotate('Broken', (125, 25),            xytext =(0.8, 0.9),             textcoords ='axes fraction',            arrowprops = dict(facecolor ='black',                              shrink = 0.05),            fontsize = 16,            horizontalalignment ='right',             verticalalignment ='top')  ax.set_title('matplotlib.axes.Axes.broken_barh Example')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
SQL Query to Drop Foreign Key Constraint Using ALTER Command - GeeksforGeeks

13 Apr, 2021
Here, we are going to see How to Drop a Foreign Key Constraint using ALTER Command(SQL Query) using  Microsoft SQL Server.
A Foreign key is an attribute in one table which takes references from another table where it acts as the primary key in that table. Also, the column acting as a foreign key should be present in both tables. 
CREATE DATABASE geeks;
USE geeks;
We have the following emp table in our database :
CREATE TABLE emp(
empno number(2) constraint pk primary key ,
empname varchar2(20),
deptno number(2),
empsal number(20));
To verify table schema use the following query:
EXEC SP_COLUMNS emp;
Output:
EMP TABLE SCHEMA
Use the below statement to add data to the emp table:
INSERT INTO emp values(1,'abc',5,20000);
INSERT INTO emp values(2,'def',6,30000);
INSERT INTO emp values(3,'xyz',7,40000);
Output:
VALUES IN EMP TABLE
Now let’s write SQL Query to Drop Foreign Key Constraint Using ALTER Command. For that, we have to create another table called “DEPT”.
CREATE TABLE dept(
deptno number(2) constraint pk2 primary key ,
dname varchar2(5),
loc varchar2(5));
To check out the current table use the following statement:
SELECT * FROM dept;
Output:
DEPT TABLE SCHEMA
Use the below statement to add data to the dept table:
INSERT INTO dept values(5,'IT','hyd');
INSERT INTO dept values(6,'sales','bglr');
INSERT INTO dept values(7,'mgr','mumb');
To check out the current table use the following statement:
SELECT * FROM dept;
DEPT TABLE VALUES
Here we have kept the DEPTNO column as common in both EMP and DEPT tables
ALTER TABLE emp add constraint fk foreign key(deptno) references dept(deptno);
 //ADDS FOREIGN KEY CONSTRAINT ON EMP TABLE
FOREIGN KEY “FK” HAS BEEN CREATED
ALTER TABLE TABLE NAME drop constraint CONSTRAINT_NAME
ALTER TABLE emp drop constraint fk;
Output:
Hence, in this way, we can Drop Foreign Key Constraint Using ALTER Command
Picked
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
ChronoZonedDateTime isBefore() method in Java with Examples - GeeksforGeeks

29 May, 2019
The isBefore() method of ChronoZonedDateTime interface in Java is used to check if the date, passed as the parameter, is before this ChronoZonedDateTime instance or not. It returns a boolean value showing the same.
Syntax:
public boolean isBefore(ChronoZonedDateTime otherDate)
Parameter: This method accepts a parameter otherDate which specifies the other date-time to be compared to this ChronoZonedDateTime. It should not be null.
Returns: The function returns boolean value showing if this date-time is before the specified date-time.
Below programs illustrate the ChronoZonedDateTime.isBefore() method:
Program 1:
// Program to illustrate the isBefore() method  import java.util.*;import java.time.*;import java.time.chrono.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        ChronoZonedDateTime dt1            = ZonedDateTime.parse(                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");          // Prints the date        System.out.println(dt1);          // Parses the date        ChronoZonedDateTime dt2            = ZonedDateTime.parse(                "2018-10-06T19:21:12.123+05:30[Asia/Calcutta]");          // Prints the date        System.out.println(dt2);          // Compares both dates        System.out.println(dt1.isBefore(dt2));    }}
2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
2018-10-06T19:21:12.123+05:30[Asia/Calcutta]
false

Program 2:
// Program to illustrate the isBefore() method  import java.util.*;import java.time.*;import java.time.chrono.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        ChronoZonedDateTime dt1            = ZonedDateTime.parse(                "2018-10-06T19:21:12.123+05:30[Asia/Calcutta]");          // Prints the date        System.out.println(dt1);          // Parses the date        ChronoZonedDateTime dt2            = ZonedDateTime.parse(                "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");          // Prints the date        System.out.println(dt2);          // Compares both dates        System.out.println(dt1.isBefore(dt2));    }}
2018-10-06T19:21:12.123+05:30[Asia/Calcutta]
2018-12-06T19:21:12.123+05:30[Asia/Calcutta]
true

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoZonedDateTime.html#isBefore-java.time.chrono.ChronoZonedDateTime-
Java-ChronoZonedDateTime
Java-Functions
Java-Time-Chrono package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
GATE | GATE-CS-2014-(Set-1) | Question 21 - GeeksforGeeks

28 Jun, 2021
Consider a rooted Binary tree represented using pointers. The best upper bound on the time required to determine the number of subtrees having having exactly 4 nodes O(na Logn b). Then the value of a + 10b is ________(A) 1(B) 11(C) 12(D) 21Answer: (A)Explanation: We can find the subtree with 4 nodes in O(n) time. Following can be a simple approach.1) Traverse the tree in bottom up manner and find size of subtree rooted with current node2) If size becomes 4, then print the current node.
Following is C implementation
#include<stdio.h>#include<stdlib.h>  struct Node{    int data;    struct Node *left, *right;};  // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){    struct Node *temp =  (struct Node *)malloc(sizeof(struct Node));    temp->data = item;    temp->left = temp->right = NULL;    return temp;}  int print4Subtree(struct Node *root){    if (root == NULL)      return 0;    int l =  print4Subtree(root->left);    int r =   print4Subtree(root->right);    if ((l + r + 1) == 4)       printf("%d ", root->data);    return (l + r + 1);}  // Driver Program to test above functionsint main(){    struct Node *root = newNode(1);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(4);    root->left->right = newNode(5);    root->right->left = newNode(6);    root->right->right = newNode(7);    root->right->left->right = newNode(8);      print4Subtree(root);      return 0;}
Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Control Statements Usage - GeeksforGeeks

13 May, 2022
Continue StatementIt returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'for letter in 'geeksforgeeks':     if letter == 'e' or letter == 's':         continue    print 'Current Letter :', letter    var = 10
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Break StatementIt brings control out of the loop
for letter in 'geeksforgeeks':       # break the loop as soon it sees 'e'     # or 's'    if letter == 'e' or letter == 's':         break  print 'Current Letter :', letter
Output:
Current Letter : e
Pass StatementWe use pass statement to write empty loops. Pass is also used for empty control statement, function and classes.
# An empty loopfor letter in 'geeksforgeeks':    passprint 'Last Letter :', letter
Output:
Last Letter : s
Exercise:How to print a list in reverse order (from last to first item) using while and for in loops.
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Interfaces in Java
How to Truncate a File in Golang? - GeeksforGeeks

23 Mar, 2020
In Go language, you are allowed to truncate the size of the file with the help of the Truncate() function. This function is used to truncate the size of the given file in the specified size.
If the given file is a symbolic link, then it changes the size of the link’s target.
If this method throws an error, then it will be of type *PathError.
It is defined under the os package so, you have to import os package in your program for accessing Truncate() function.
Suppose if the truncate file if of 100 bytes and the original file is less than 100 bytes, then the original content remains at the beginning and the remaining space is filled with the null bytes. And if the original file is greater than 100 bytes, then the truncated file lost content after 100 bytes.
If you pass 0 in the Truncate() function, then you will get an empty file.
Syntax:
func Truncate(name string, size int64) error
Example 1:
// Golang program to illustrate how to// truncate the size of the given filepackage main  import (    "log"    "os")  var (    myfile *os.FileInfo    e      error)  func main() {  // Truncate the size of the   // given file to 200 bytes   // Using Truncate() function    err := os.Truncate("gfg.txt", 200)    if err != nil {        log.Fatal(err)      }}
Output:
Before:
After:
Example 2:
// Golang program to illustrate how to// truncate the size of the given filepackage main  import (    "log"    "os")  var (    myfile *os.FileInfo    e      error)  func main() {  // Truncate the size of the given   // file to 0 bytes or empty file  // Using Truncate() function    err := os.Truncate("gfg.txt",0)    if err != nil {        log.Fatal(err)      }}
Output:
Before:
After:
Example 3:
// Golang program to illustrate how to // truncate the size of the given filepackage main  import (    "log"    "os")  var (    myfile *os.FileInfo    e      error)  func main() {  // Truncate the size of the   // given file to 300 bytes   // Using Truncate() function    err := os.Truncate("/Users/anki/Documents/new_folder/bingo.txt", 300)    if err != nil {        log.Fatal(err)      }}
Output:
Before:
After:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang
Tryit Editor v3.7

Tryit: Using the list-style shorthand property
Static and non static blank final variables in Java

Static variable: Declared with the help of the keyword ‘static’, they are also known as class variables. They are defined within a constructor or outside a class function. When a variable is static, it is shared between all objects of the class, irrespective of the number of objects that are created.
Demonstrating how the ‘static’ keyword, when used with variable works −
 Live Demo
public class Demo{
   String name;
   static String designation;
   public void display_data(){
      System.out.println("The name is: " + name);
      System.out.println("The designation of this team members is : " + designation);
   }
   public static void main(String s[]){
      Demo.designation = "Intern";
      Demo my_obj = new Demo();
      my_obj.name = "Joe";
      Demo my_obj_2 = new Demo();
      my_obj_2.name = "Joanna";
      my_obj.display_data();
      my_obj_2.display_data();
      my_obj.designation = "Senior dev";
      System.out.println("\nAfter the changes, the data is :\n");
      my_obj.display_data();
      my_obj_2.display_data();
   }
}
The name is: Joe
The designation of this team members is : Intern
The name is: Joanna
The designation of this team members is : Intern
After the changes, the data is :
The name is: Joe
The designation of this team members is : Senior dev
The name is: Joanna
The designation of this team members is : Senior dev
A class named Demo contains variables and a function named ‘display_data’ that is used to display the class variables. In the main function, an instance of the class is created and a name and designation is assigned to the object variable. It is displayed and another object is created and the same is done. The data is displayed on the console. The changes reflect here.
Static final blank variable − The same definition as that of blank final variable along with the keyword ‘static’, meaning it can be initialized within a static block of code only.
Blank final variable − As the name suggests, the final variable that has no value assigned to it is known as a blank final variable. It can be initialized within a constructor only, and failing to initiate a blank final variable results in a compilation error.
Blank final variable’s working −
 Live Demo
public class Demo{
   private static final int val_1;
   private final int val_2;
   static{ val_1 = 1;
   }
   Demo(int val_3){
      val_2 = val_3;
   }
   public static void main(String s[]){
      Demo obj_1 = new Demo(95);
      Demo obj_2 = new Demo(99);
      System.out.println("The value of first variable is : ");
      System.out.println(Demo.val_1);
      System.out.println("The value of first variable accessed using the object : ");
      System.out.println(obj_1.val_2);
   }
}
The value of first variable is :
1
The value of first variable accessed using the object :
95
A class named Demo contains variables and a constructor named ‘Demo’ that is used to assign one value to another class variable. In the main function, two instances of the class are created and their values are displayed on the console.
numpy.radians() and deg2rad() in Python

04 Dec, 2020
The numpy.radians() is a mathematical function that helps user to convert angles from degree to radians.
Syntax : numpy.radians(x[, out]) = ufunc ‘radians’)Parameters :
array : [array_like] elements are in degrees.out : [ndaaray, optional]Output array of same shape as x.          2pi Radians = 36o degrees
Return : An array with radian values in place of degree values.
 Code #1 : Working
# Python3 program explaining# degrees() function  import numpy as npimport math  in_array = np.arange(10.) * 90print ("Degree values : \n", in_array)  radian_Values = np.radians(in_array)print ("\nRadian values : \n", radian_Values)
Output :
Degree values : 
 [   0.   90.  180.  270.  360.  450.  540.  630.  720.  810.]

Radian values : 
 [  0.           1.57079633   3.14159265   4.71238898   6.28318531
   7.85398163   9.42477796  10.99557429  12.56637061  14.13716694]

 
numpy.deg2rad(x[, out]) = ufunc ‘deg2rad’) : This mathematical function helps user to convert angles from degrees to radians
Parameters :
array : [array_like] elements are in radians.out : [ndaaray, optional]Output array of same shape as x.          2pi Radians = 36o degrees
Return : Corresponding angles in radians.
 Code #2 : deg2rad() Equivalent to radians()
# Python3 program explaining# rad2deg() function  import numpy as npimport math  degree = np.arange(10.) * 90print ("Degree values : \n", degree)  radian = np.deg2rad(degree)print ("\nradian values : \n", radian)
Output :
Degree values : 
 [   0.   90.  180.  270.  360.  450.  540.  630.  720.  810.]

radian values : 
 [  0.           1.57079633   3.14159265   4.71238898   6.28318531
   7.85398163   9.42477796  10.99557429  12.56637061  14.13716694]

 References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.radians.html#numpy.radians.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Tensorflow | tf.data.Dataset.from_tensor_slices()

03 Oct, 2019
With the help of tf.data.Dataset.from_tensor_slices() method, we can get the slices of an array in the form of objects by using tf.data.Dataset.from_tensor_slices() method.
Syntax : tf.data.Dataset.from_tensor_slices(list)Return : Return the objects of sliced elements.
Example #1 :In this example we can see that by using tf.data.Dataset.from_tensor_slices() method, we are able to get the slices of list or array.
# import tensorflowimport tensorflow as tf  # using tf.data.Dataset.from_tensor_slices() methodgfg = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5])  for ele in gfg:    print(ele.numpy())
Output :
12345
Example #2 :
# import tensorflowimport tensorflow as tf  # using tf.data.Dataset.from_tensor_slices() methodgfg = tf.data.Dataset.from_tensor_slices([[5, 10], [3, 6]])  for ele in gfg:    print(ele.numpy())
Output :
[5, 10][3, 6]
Tensorflow
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Internet Message Access Protocol (IMAP)

22 Jan, 2021
Prerequisite – Protocols in Application Layer
Internet Message Access Protocol (IMAP) is an application layer protocol that operates as a contract for receiving emails from the mail server. It was designed by Mark Crispin in 1986 as a remote access mailbox protocol, the current version of IMAP is IMAP4. It is used as the most commonly used protocol for retrieving emails. This term is also known as Internet mail access protocol, Interactive mail access protocol, and Interim mail access protocol.
Features of IMAP :
It is capable of managing multiple mailboxes and organizing them into various categories.
Provides adding of message flags to keep track of which messages are being seen.
It is capable of deciding whether to retrieve email from a mail server before downloading.
It makes it easy to download media when multiple files are attached.
Working of IMAP :IMAP follows Client-server Architecture and is the most commonly used email protocol. It is a combination of client and server process running on other computers that are connected through a network. This protocol resides over the TCP/IP protocol for communication. Once the communication is set up the server listens on port 143 by default which is non-encrypted. For the secure encrypted communication port, 993 is used.
Architecture of IMAP :
Advantages :
It offers synchronization across all the maintained sessions by the user.
It provides security over POP3 protocol as the email only exists on the IMAP server.
Users have remote access to all the contents.
It offers easy migration between the devices as it is synchronized by a centralized server.
There is no need to physically allocate any storage to save contents.
Disadvantages :
IMAP is complex to maintain.
Emails of the user are only available when there is an internet connection.
It is slower to load messages.
Some emails don’t support IMAP which makes it difficult to manage.
Many browser-based solutions are unavailable due to not support of IMAP.
Computer Networks
GATE CS
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a negative number to positive in JavaScript

29 May, 2019
We can convert a negative number to a positive number in javascript by the methods described below.
Method 1: This is a general method in which we will first check whether the number is already positive or negative, if the number is negative then we will multiply the number with -1 to make it positive.
Syntax:
if (a < 0) {
    a = a * -1;
}

Example: Below is the implementation of the above approach:
<script>    // Javascript script     // to convert negative number    // to positive number      // Function to convert    // given number to     // positive number    function convert_positive(a) {        // Check the number is negative        if (a < 0) {            // Multiply number with -1            // to make it positive            a = a * -1;        }        // Return the positive number        return a;    }  //Driver codevar n = -10;var m = 5;  // Call functionn = convert_positive(n);  // Print resultdocument.write(n + "<br>");  // Call functionm = convert_positive(m);  // Print resultdocument.write(m + "<br>"); </script>
Output:
10
5

Method 2: In this method we will use Math.abs() function to convert negative number to positive number.
Syntax:
Math.abs(value)
Example: Below is the implementation of the above approach:
<script>    // Javascript script     // to convert negative number    // to positive number                //Driver code    var n = -30;    var m = 15;      // Using Math.abs() function    n = Math.abs(n);          // Print result    document.write(n + "<br>");          // Using Math.abs() function    m = Math.abs(m);          // Print result    document.write(m + "<br>");</script>                                    
Output:
30
15

javascript-math
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the size of a Tuple in Python

17 May, 2020
Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers.Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses.The size of a Tuple means the amount of memory (in bytes) taken by a Tuple object. In this article, we will learn various ways to get the size of a python Tuple.
1.Using getsizeof() function:
The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example.
Example 1:
import sys  # sample TuplesTuple1 = ("A", 1, "B", 2, "C", 3)Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu")Tuple3 = ((1, "Lion"), ( 2, "Tiger"), (3, "Fox"), (4, "Wolf"))  # print the sizes of sample Tuplesprint("Size of Tuple1: " + str(sys.getsizeof(Tuple1)) + "bytes")print("Size of Tuple2: " + str(sys.getsizeof(Tuple2)) + "bytes")print("Size of Tuple3: " + str(sys.getsizeof(Tuple3)) + "bytes")
Output:
Size of Tuple1: 96bytes
Size of Tuple2: 96bytes
Size of Tuple3: 80bytes
Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used.
1.Using inbuilt __sizeof__() method:
Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:
# sample TuplesTuple1 = ("A", 1, "B", 2, "C", 3)Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu")Tuple3 = ((1, "Lion"), ( 2, "Tiger"), (3, "Fox"), (4, "Wolf"))  # print the sizes of sample Tuplesprint("Size of Tuple1: " + str(Tuple1.__sizeof__()) + "bytes")print("Size of Tuple2: " + str(Tuple2.__sizeof__()) + "bytes")print("Size of Tuple3: " + str(Tuple3.__sizeof__()) + "bytes")
Output:
Size of Tuple1: 72bytes
Size of Tuple2: 72bytes
Size of Tuple3: 56bytes
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Contains Duplicate in Python

Suppose we have a list of numbers. We have to check whether the list is holding some duplicate elements or not. So if the list is like [1,5,6,2,1,3], then it will return 1 as there are two 1s, but if the list is [1,2,3,4], then it will be false, as there is no duplicate present.
To solve this, we will follow this approach −
We know that the set data structure only holds unique data. But the list can fold duplicate contents. So if we convert the list into the set, its size will be reduced if there are any duplicate elements, by matching the length, we can solve this problem.
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def containsDuplicate(self, nums):
      """
      :type nums: List[int]
      :rtype: bool
      """
      return not len(nums) == len(set(nums))
ob1 = Solution()
print(ob1.containsDuplicate([1,5,6,2,1,3]))
print(ob1.containsDuplicate([1,2,3,4]))
nums = [1,5,6,2,1,3]
nums = [1,2,3,4]
True
False
Tryit Editor v3.6 - Show Python

mydb = mysql.connector.connect(
  host="localhost",
  user="myusername",
  password="mypassword"
)
​
mycursor = mydb.cursor()