code-rag-bench/online-tutorials huggingface dataset:
Tensorflow.js tf.train.sgd() Function

14 Aug, 2021
Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.
The .train.sgd() function is used to build a tf.SGDOptimizer which utilizes stochastic gradient descent.
Syntax:
tf.train.sgd(learningRate)
Parameters:
learningRate: The stated learning rate which is used in favor of the SGD algorithm. It is of type number.
Return Value: It returns tf.SGDOptimizer.
 
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Declaring learningRateconst learning_rate = 0.02;  // Calling train.sgd() methodconst res = tf.train.sgd(learning_rate);  // Printing outputconsole.log(res);
Output:
{
  "learningRate": 0.02,
  "c": {
    "kept": true,
    "isDisposedInternal": false,
    "shape": [],
    "dtype": "float32",
    "size": 1,
    "strides": [],
    "dataId": {
      "id": 1298
    },
    "id": 1192,
    "rankType": "0",
    "scopeId": 1251
  }
}
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Calling train.sgd() and sin() methodconsole.log(JSON.stringify(tf.train.sgd(tf.sin(45))));
Output:
{"learningRate":{"kept":false,"isDisposedInternal":false,"shape":[],
"dtype":"float32","size":1,"strides":[],"dataId":{"id":1316},"id":1207,
"rankType":"0","scopeId":1269},"c":{"kept":true,"isDisposedInternal":false,
"shape":[],"dtype":"float32","size":1,"strides":[],"dataId":{"id":1318},
"id":1208,"rankType":"0","scopeId":1269}}
Reference: https://js.tensorflow.org/api/latest/#train.sgd
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | sympy.apart() method

25 Jun, 2019
With the help of sympy.apart() method, we are able to do a partial fraction decomposition of a rational function and put it into a standard canonical form i.e p/q.
Syntax : sympy.apart()Return : Return the partial fraction decomposition of rational function.
Example #1 :In the given example, we can see that by using sympy.apart() method, we can do the partial fraction of rational function.
# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = (x**2 + 2 * x + 1)/(x**2 + x)   # Using sympy.apart() methodgfg_exp = apart(gfg_exp)   print(gfg_exp)
Output :
1 + 1/x
Example #2 :
# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = 1 / x + (3 * x / 2 - 2)/(x - 4)   # Using sympy.apart() methodgfg_exp = apart(gfg_exp)   print(gfg_exp)
Output :
3/2 + 4/(x – 4) + 1/x
SymPy
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to get coordinates from the contour in matplotlib?

To get coordinates from the contour in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create lists of x, y and m with data points.
Use plt.contour(x, y, m) to create a contour plot with x, y and m data points.
Get the contour collections instance.
Get the path of the collections, and print the vertices or coordinates of the contour.
To display the figure, use show() method.
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
m = [[15, 14, 13, 12], [14, 12, 10, 8], [13, 10, 7, 4], [12, 8, 4, 0]]

cs = plt.contour(x, y, m)

for item in cs.collections:
   for i in item.get_paths():
      v = i.vertices
      x = v[:, 0]
      y = v[:, 1]
      print(x, y)
plt.show()
It will produce the following output
In addition, it will print the coordinates of the contour on the terminal
[4.] [4.]
[4. 3.5] [3.5 4. ]
[4. 3.] [3. 4.]
[4.      3.33333333 3.     2.5 ] [2.5    3.     3.33333333 4.   ]
[4.      3. 2.66666667     2. ]  [2.     2.66666667   3.   4. ]
[4. 3. 2. 1.5] [1.5 2. 3. 4. ]
[4. 3. 2.     1.33333333 1. ] [1. 1.33333333 2. 3. 4. ]
[2. 1.] [1. 2.]
sympy.integrals.transforms.inverse_fourier_transform() in python

10 Jul, 2020
With the help of inverse_fourier_transform() method, we can compute the inverse fourier transformation and return the unevaluated function.
Inverse Fourier Transformation
Syntax :  inverse_fourier_transform(F, k, x, **hints)
Return : Return the unevaluated function.
Example #1 :
In this example we can see that by using inverse_fourier_transform() method, we are able to compute the inverse fourier transformation which return the unevaluated function by using this method.
Python3
# import inverse_fourier_transformfrom sympy import inverse_fourier_transform, exp, sqrt, pifrom sympy.abc import x, k  # Using inverse_fourier_transform()gfg = inverse_fourier_transform(sqrt(pi)*exp(-(pi * k)**2), k, x)  print(gfg)
Output :
exp(-x**2)
Example #2 :
Python3
# import inverse_fourier_transformfrom sympy import inverse_fourier_transform, exp, sqrt, pifrom sympy.abc import x, k  # Using inverse_fourier_transform()gfg = inverse_fourier_transform(sqrt(pi)*exp(-(pi * k)**2), k, 4)  print(gfg)
Output :
exp(-16)
Python SymPy-Stats
SymPy
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Python program to verify that a string only contains letters, numbers, underscores and dashes

19 Aug, 2020
Prerequisite: Regular Expression in Python
Given a string, we have to find whether the string contains any letters, numbers, underscores, and dashes or not. It is usually used for verifying username and password validity. For example, the user has a string for the username of a person and the user doesn’t want the username to have any special characters such as @, $, etc. 
Let’s see the different methods for solving this task:
Method 1: Using Regular Expression.
There is a function in the regular expression library(re) that compares two string for us. re.match(pattern, string) is a function that returns an object, to find whether a match is find or not we have to typecast it into boolean. 
Syntax: re.match(pattern, string) 
Parameters:
pattern: the pattern against which you want to check 
string: the string you want to check for the pattern 
Return: Match object 
Let’s see an example:
Example 1:
Python3
# import libraryimport re  # make a patternpattern = "^[A-Za-z0-9_-]*$"  # inputstring = "G33ks_F0r_Geeks"  # convert match object # into boolean valuesstate = bool(re.match(pattern, string))  print(state)
Output:
True
Example 2:
Python3
# import libraryimport re  print(bool(re.match("^[A-Za-z0-9_-]*$",                    'ValidString12-_')))  print(bool(re.match("^[A-Za-z0-9_-]*$",                     'inv@lidstring')))
Output:
True
False
Method 2: Using Set.
Set is built-in data-type in Python. We are using issubset() function of set that returns True if all characters of a set are present in a given set Otherwise False.
Syntax: set_name.issubset(set)Parameters: 
set: Represents that set in which the subset has to be searched 
Return: boolean value
Let’s see an example:Example 1: 
Python3
# create a set of allowed charactersallowed_chars = set(("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"))  # input stringstring = "inv@lid"  # convert string into set of charactersvalidation = set((string))  # check conditionif validation.issubset(allowed_chars):    print("True")      else:    print ("False")
Output:
False
Example 2: 
Python3
allowed_chars = set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-")  string = "__Val1d__"  validation = set((string))  if validation.issubset(allowed_chars):    print("True")      else:    print ("False")
Output:
True
Python string-programs
python-string
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python String | max()

08 Dec, 2021
max() is an inbuilt function in Python programming language that returns the highest alphabetical character in a string.
Syntax:
max(string)
Parameter:max() method takes a string as a parameter
Return value:
Returns a character which is alphabetically the highest character in the string.
Below is the Python implementation of the method max()
Python
# python program to demonstrate the use of # max() function   # maximum alphabetical character in # "geeks" string = "geeks" print max(string)  # maximum alphabetical character in # "raj"string = "raj" print max(string)
s
r

prachisoda1234
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert String to Double in Python3

08 Oct, 2021
Given a string and our task is to convert it in double. Since double datatype allows a number to have non -integer values. So conversion of string to  double is the same as the conversion of string to float 
This can be implemented in these two ways
1) Using float() method
Python3
str1 = "9.02"print("This is the initial string: " + str1) # Converting to doublestr2 = float(str1)print("The conversion of string to double is", str2) str2 = str2+1print("The converted string to double is incremented by 1:", str2)
Output:
This is the initial string: 9.02
The conversion of string to double is 9.02
The converted string to double is incremented by 1: 10.02
2) Using decimal() method: Since we only want a string with a number with  decimal values this method can also be used
Python3
from decimal import Decimal  str1 = "9.02"print("This is the initial string: " + str1) # Converting to doublestr2 = Decimal(str1)print("The conversion of string to double is", str2) str2 = str2+1print("The converted string to double is incremented by 1:", str2)
Output:
This is the initial string: 9.02
The conversion of string to double is 9.02
The converted string to double is incremented by 1: 10.02
kashishsoda
python-basics
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Overriding toString() Method in Java

25 Feb, 2022
Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representation or in short output on the console while using System.out.print. It is because this method was getting automatically called when the print statement is written. So this method is overridden in order to return the values of the object which is showcased below via examples.
Example 1:
Java
// file name: Main.java class Complex {    private double re, im;             public Complex(double re, double im) {        this.re = re;        this.im = im;    }}  // Driver class to test the Complex classpublic class Main {    public static void main(String[] args) {        Complex c1 = new Complex(10, 15);        System.out.println(c1);    }}
Complex@214c265e
Output Explanation: The output is the class name, then ‘at’ sign, and at the end hashCode of the object. All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this). The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Example 2:
Java
// Java Program to illustrate Overriding// toString() Method // Class 1public class GFG {         // Main driver method    public static void main(String[] args) {                 // Creating object of class1        // inside main() method        Complex c1 = new Complex(10, 15);                 // Printing the complex number        System.out.println(c1);    }}// Class 2// Helper classclass Complex {         // Attributes of a complex number    private double re, im;         // Constructor to initialize a complex number    // Default    // public Complex() {    //     this.re = 0;    //     this.im = 0;    // }         // Constructor 2: Parameterized    public Complex(double re, double im) {                 // This keyword refers to        // current complex number        this.re = re;        this.im = im;    }    // Getters    public double getReal() {        return this.re;    }    public double getImaginary() {        return this.im ;    }    // Setters    public void setReal(double re) {        this.re = re;    }    public void setImaginary(double im) {        this.im = im;    }    // Overriding toString() method of String class    @Override    public String toString() {        return this.re + " + " + this.im + "i";    }}
  
10.0 + 15.0i
 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
solankimayank
simranarora5sos
java-overriding
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Merge Sort

17 Jan, 2022
Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.  
Python3
# Python program for implementation of MergeSort # Merges two subarrays of arr[].# First subarray is arr[l..m]# Second subarray is arr[m+1..r]  def merge(arr, l, m, r):    n1 = m - l + 1    n2 = r - m     # create temp arrays    L = [0] * (n1)    R = [0] * (n2)     # Copy data to temp arrays L[] and R[]    for i in range(0, n1):        L[i] = arr[l + i]     for j in range(0, n2):        R[j] = arr[m + 1 + j]     # Merge the temp arrays back into arr[l..r]    i = 0     # Initial index of first subarray    j = 0     # Initial index of second subarray    k = l     # Initial index of merged subarray     while i < n1 and j < n2:        if L[i] <= R[j]:            arr[k] = L[i]            i += 1        else:            arr[k] = R[j]            j += 1        k += 1     # Copy the remaining elements of L[], if there    # are any    while i < n1:        arr[k] = L[i]        i += 1        k += 1     # Copy the remaining elements of R[], if there    # are any    while j < n2:        arr[k] = R[j]        j += 1        k += 1 # l is for left index and r is right index of the# sub-array of arr to be sorted  def mergeSort(arr, l, r):    if l < r:         # Same as (l+r)//2, but avoids overflow for        # large l and h        m = l+(r-l)//2         # Sort first and second halves        mergeSort(arr, l, m)        mergeSort(arr, m+1, r)        merge(arr, l, m, r)  # Driver code to test abovearr = [12, 11, 13, 5, 6, 7]n = len(arr)print("Given array is")for i in range(n):    print("%d" % arr[i],end=" ") mergeSort(arr, 0, n-1)print("\n\nSorted array is")for i in range(n):    print("%d" % arr[i],end=" ") # This code is contributed by Mohit Kumra
Given array is
12 11 13 5 6 7 

Sorted array is
5 6 7 11 12 13 
Please refer complete article on Merge Sort for more details! 
the_alphaEye
amartyaghoshgfg
Merge Sort
Python Programs
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Populate null columns in a MySQL table and set values

For this, you can use IS NULL property. Let us first create a table −
mysql> create table DemoTable
(
   ProductPrice int,
   ProductQuantity int,
   TotalAmount int
);
Query OK, 0 rows affected (1.22 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(100,2);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(500,4);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable(ProductPrice,ProductQuantity) values(1000,10);
Query OK, 1 row affected (0.21 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+-----------------+-------------+
| ProductPrice | ProductQuantity | TotalAmount |
+--------------+-----------------+-------------+
|          100 |               2 |        NULL |
|          500 |               4 |        NULL |
|         1000 |              10 |        NULL |
+--------------+-----------------+-------------+
3 rows in set (0.00 sec)
Here is the query to populate NULL columns −
mysql> update DemoTable set TotalAmount=(ProductPrice*ProductQuantity) where
TotalAmount IS NULL;
Query OK, 3 rows affected (0.20 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+--------------+-----------------+-------------+
| ProductPrice | ProductQuantity | TotalAmount |
+--------------+-----------------+-------------+
|          100 |               2 |         200 |
|          500 |               4 |        2000 |
|         1000 |              10 |       10000 |
+--------------+-----------------+-------------+
3 rows in set (0.00 sec)
Python | Ways to check if given string contains only letter

21 Jul, 2021
Given a string, write a Python program to find whether a string contains only letters and no other keywords. Let’s discuss a few methods to complete the task.
Method #1: Using isalpha() method 
Python3
# Python code to demonstrate# to find whether string contains# only letters # Initialising stringini_str = "ababababa" # Printing initial stringprint ("Initial String", ini_str) # Code to check whether string contains only numberif ini_str.isalpha():    print("String contains only letters")else:    print("String doesn't contains only letters")
  Method #2: Using re 
Python3
# Python code to demonstrate# to find whether string contains# only lettersimport re # Initialising stringini_str = "ababababa" # Printing initial stringprint ("Initial String", ini_str) # Code to check whether string contains only numberpattern = re.compile("^[a-zA-Z]+$")if pattern.match(ini_str):    print ("Contains only letters")else:    print ("Doesn't contains only letters")
sagar0719kumar
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
How to find If a given String contains only letters in Java?

To verify whether a given String contains only characters −
Read the String.
Convert all the characters in the given String to lower case using the toLower() method.
Convert it into a character array using the toCharArray() method of the String class.
Find whether every character in the array is in between a and z, if not, return false.
Following Java program accepts a String from the user and displays whether it is valid or not.
import java.util.Scanner;
public class StringValidation{
   public boolean validtaeString(String str) {
      str = str.toLowerCase();
      char[] charArray = str.toCharArray();
      for (int i = 0; i < charArray.length; i++) {
         char ch = charArray[i];
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
         }
      }
      return true;
   }
   public static void main(String args[]) {
      Scanner sc= new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.next();
      StringValidation obj = new StringValidation();
      boolean bool = obj.validtaeString(str);
      if(!bool) {
         System.out.println("Given String is invalid");
      }else{
         System.out.println("Given String is valid");
      }
   }
}
Enter a string value:
24ABCjhon
Given String is invalid
Check if a circle lies inside another circle or not in C++

Suppose we have two circles (center points, and the radius values), we have to check one circle is fit inside another circle or not. There are three possible causes.
The smaller circle lies completely inside the bigger one, without touching each other. In this case, the sum of the distance between the centers, and the smaller radius, is lesser than a bigger radius. So the smaller one will be inside the bigger one.
The smaller circle lies completely inside the bigger one, without touching each other. In this case, the sum of the distance between the centers, and the smaller radius, is lesser than a bigger radius. So the smaller one will be inside the bigger one.
The second case is the smaller circle is inside the bigger ones, but also touches the circumference of the bigger circle.
The second case is the smaller circle is inside the bigger ones, but also touches the circumference of the bigger circle.
The third case is, some part of the smaller circle is inside the bigger one.
The third case is, some part of the smaller circle is inside the bigger one.
To solve this, we have to find the distance between two centers, then using the distance and the radius values, we will determine those cases.
#include <iostream>
#include <cmath>
using namespace std;
void isCircleInside(int x_big, int y_big, int x_small, int y_small, int r_big, int r_small) {
   int distSq = sqrt(((x_big - x_small) * (x_big - x_small)) + ((y_big - y_small) * (y_big - y_small)));
   if (distSq + r_small == r_big)
      cout << "Inside the bigger circle, touching circimferene" << endl;
      else if (distSq + r_small < r_big)
         cout << "Completely inside the bigger circle" << endl;
   else
      cout << "Not inside the bigger circle" << endl;
}
int main() {
   int x1 = 10, y1 = 8;
   int x2 = 1, y2 = 2;
   int r1 = 30, r2 = 10;
   isCircleInside(x1, y1, x2, y2, r1, r2);
}
Completely inside the bigger circle
How to dynamically build MongoDB query?

To build query dynamically, you need to write some script. Let us first create a collection with documents −
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","MySQL"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5cef5c5def71edecf6a1f69a")
}
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["C","C++"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5cef5c73ef71edecf6a1f69b")
}
> db.dynamicQueryDemo.insertOne({"Name":"John","Subject":["MongoDB","Java"]});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5cef5c8bef71edecf6a1f69c")
}
Display all documents from a collection with the help of find() method −
> db.dynamicQueryDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cef5c5def71edecf6a1f69a"),
   "Name" : "John",
   "Subject" : [
      "MongoDB",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5cef5c73ef71edecf6a1f69b"),
   "Name" : "John",
   "Subject" : [
      "C",
      "C++"
   ]
}
{
   "_id" : ObjectId("5cef5c8bef71edecf6a1f69c"),
   "Name" : "John",
   "Subject" : [
      "MongoDB",
      "Java"
   ]
}
Following is the query to dynamically build MongoDB query −
> function findDocument(subject) {
   var find = {};
   if (subject.length == 0)
      find["$nin"] = subject;
   else
      find["$in"] = subject;
   return find;
}
> var sub = ["MySQL","MongoDB"];
> var myDoc = findDocument(sub);

> db.dynamicQueryDemo.aggregate([{
   $match: {
      "Subject": myDoc,
   }
}]);
This will produce the following output −
{ "_id" : ObjectId("5cef5c5def71edecf6a1f69a"), "Name" : "John", "Subject" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5cef5c8bef71edecf6a1f69c"), "Name" : "John", "Subject" : [ "MongoDB", "Java" ] }
Java enum Keyword

❮ Java Keywords

Create an enum with constants (unchangeable variables):
enum Level {
  LOW,
  MEDIUM,
  HIGH
}

You can access enum constants with the dot syntax:
The enum keyword declares an enumerated (unchangeable) type.
An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma. Note that they should be in uppercase letters.
An enum can, just like a class, have attributes and methods. The only 
difference is that enum constants are public, static and final 
(unchangeable - cannot be overridden).
An enum cannot be used to create objects, and it can not extend other classes (but it can implement interfaces).
Use enums when you have values that you know aren't going to change, like month days, days, colors, deck of cards, etc.
Read more about enums in our Java Enum Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
AWT Panel Class

The class Panel is the simplest container class. It provides space in which an application can attach any other component, including other panels. It uses FlowLayout as default layout manager.
Following is the declaration for java.awt.Panel class:
public class Panel
   extends Container
      implements Accessible
Panel()
Creates a new panel using the default layout manager.
Panel(LayoutManager layout) 
Creates a new panel with the specified layout manager.
void addNotify() 
Creates the Panel's peer.
AccessibleContext getAccessibleContext() 
Gets the AccessibleContext associated with this Panel.
This class inherits methods from the following classes:
java.awt.Container
java.awt.Container
java.awt.Component
java.awt.Component
java.lang.Object
java.lang.Object
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >
package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {
   private Frame mainFrame;
   private Label headerLabel;
   private Label statusLabel;
   private Panel controlPanel;
   private Label msglabel;

   public AwtContainerDemo(){
      prepareGUI();
   }

   public static void main(String[] args){
      AwtContainerDemo  awtContainerDemo = new AwtContainerDemo();          
      awtContainerDemo.showPanelDemo();
   }

   private void prepareGUI(){
      mainFrame = new Frame("Java AWT Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);
   
      msglabel = new Label();
      msglabel.setAlignment(Label.CENTER);
      msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }

   private void showPanelDemo(){
      headerLabel.setText("Container in action: Panel");      

      Panel panel = new Panel();
      panel.setBackground(Color.magenta);
      panel.setLayout(new FlowLayout());        
      panel.add(msglabel);

      controlPanel.add(panel);

      mainFrame.setVisible(true);  
   }
}
Compile the program using command prompt. Go to D:/ > AWT  and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo
Verify the following output

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page
Arduino - Keyboard Serial

This example listens for a byte coming from the serial port. When received, the board sends a keystroke back to the computer. The sent keystroke is one higher than what is received, so if you send an "a" from the serial monitor, you will receive a "b" from the board connected to the computer. A "1" will return a "2" and so on.
Warning − When you use the Keyboard.print() command, the Leonardo, Micro or Due board takes over your computer's keyboard. To ensure you do not lose control of your computer while running a sketch with this function, set up a reliable control system before you call Keyboard.print(). This sketch is designed to only send a Keyboard command after the board has received a byte over the serial port.
You will need the following components −
1 × Arduino Leonardo, Micro, or Due board
Just connect your board to the computer using USB cable.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.
Notes − You must include the keypad library in your Arduino library file. Copy and paste the keypad library file inside the file with the name ‘libraries’ highlighted with yellow color.
/*
   Keyboard test
   For the Arduino Leonardo, Micro or Due Reads
      a byte from the serial port, sends a keystroke back. 
   The sent keystroke is one higher than what's received, e.g. if you send a, you get b, send
      A you get B, and so forth.
   The circuit:
   * none
*/

#include "Keyboard.h"

void setup() {
   // open the serial port:
   Serial.begin(9600);
   // initialize control over the keyboard:
   Keyboard.begin();
}

void loop() {
   // check for incoming serial data:
   if (Serial.available() > 0) {
      // read incoming serial data:
      char inChar = Serial.read();
      // Type the next ASCII value from what you received:
      Keyboard.write(inChar + 1);
   }
}
Once programed, open your serial monitor and send a byte. The board will reply with a keystroke, that is one number higher.
The board will reply with a keystroke that is one number higher on Arduino IDE serial monitor when you send a byte.

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2004 | Question 7 - GeeksforGeeks

28 Jun, 2021
Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?

1.    9679, 1989, 4199 hash to the same value
2.    1471, 6171 hash to the same value
3.    All elements hash to the same value
4.    Each element hashes to a different value 
(A) 1 only(B) 2 only(C) 1 and 2 only(D) 3 or 4Answer: (C)Explanation: The hash value for 9679, 1989, 4199 is 9 and hash value for 1471, 6171 is 1.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
How can we implement a scrollable JPanel in Java?

A JPanel is a subclass of JComponent (a subclass of a Container class). Therefore, JPanel is also a Container.
A JPanel is an empty area that can be used either to layout other components including other panels.
In a JPanel, we can add fields, labels, buttons, checkboxes, and images also.
The Layout Managers such as FlowLayout, GridLayout, BorderLayout and other layout managers helps us to control the sizes, positions, and alignment of the components using JPanel.
The important methods of a JPanel class are getAccessibleContext(), getUI(), updateUI() and paramString().
We can also implement a JPanel with vertical and horizontal scrolls by adding the panel object to JScrollPane.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JScrollablePanelTest extends JFrame {
   public JScrollablePanelTest() {
      setTitle("JScrollablePanel Test");
      setLayout(new BorderLayout());
      JPanel panel = createPanel();
      add(BorderLayout.CENTER, new JScrollPane(panel));
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static JPanel createPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(10, 4, 10, 10));
      for (int i=0; i < 10; i++) {
         for (int j=0; j < 4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Arial", Font.PLAIN, 20));
            panel.add(label);
         }
      }
      return panel;
   }
   public static void main(String [] args) {
      new JScrollablePanelTest();
   }
}
JavaScript String - concat() Method

This method adds two or more strings and returns a new single string.
Its syntax is as follows −
string.concat(string2, string3[, ..., stringN]);

string2...stringN − These are the strings to be concatenated.
Returns a single concatenated string.
Try the following example.
<html>
   <head>
      <title>JavaScript String concat() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str1 = new String( "This is string one" );
         var str2 = new String( "This is string two" );
         var str3 = str1.concat( str2 );      
         document.write("Concatenated String :" + str3); 
      </script>      
   </body>
</html>
Concatenated String :This is string oneThis is string two.
How to add a row to R dataframe ?

21 Apr, 2021
In this article, we will see how to add rows to a DataFrame in R Programing Language. To do this we will use rbind() function. This function in R Language is used to combine specified Vector, Matrix or Data Frame by rows.
Syntax:
rbind(dataframe 1, dataframe 2)
Example 1 :
R
# creating a data frame with some datadf9 = data.frame(id=c(1,2,3),                 name=c("karthik","bhagiradh","kethan"))   print("Original data frame")  # printing the data frame print(df9)   # declaring a row of values in # data.frame() functiondf8 = data.frame(4,"shyam")   # adding names to the row valuesnames(df8)=c("id","name")  # passing the original data frame and new # data frame into the rbind() functiondf7=rbind(df9,df8)    print("data frame after adding a new row")print(df7)
Output :
Example 2 :
Python3
# creating a data frame with some datadf = data.frame(id=c(1,2,3),                name=c("maruti suzuki","tata","ford"))   print("Original data frame")print(df)   # declaring a row of values in# data.frame() functiondf1 = data.frame(4,"volkswagen")  # adding names to the row valuesnames(df1)=c("id","name")   # passing the original data frame and # new data frame into the rbind() function df2=rbind(df,df1)   print("data frame after adding a new row")print(df2)
Output :
Example 3:
R
# creating a data frame with some datadf3 = data.frame(id=c(1,2,3),                 name=c("Asus","HP","Acer"))   print("Original data frame")print(df3)   # declaring a row of values in # data.frame() functiondf4 = data.frame(4,"Dell")  # adding names to the row valuesnames(df4)=c("id","name")   # passing the original data frame and # new data frame into the rbind() functiondf5=rbind(df3,df4)   print("data frame after adding a new row")print(df5) 
Output :
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Import CSV into PostgreSQL

23 Sep, 2021
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2.
First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the “create table” SQL command using the cursor.execute() method.
'''CREATE TABLE DETAILS(employee_id int NOT NULL,
                        employee_name char(20), 
                        employee_email varchar(30),
                        employee_salary float);'''
View of the empty table:
Table Description
After creating the table we need to execute the “copy” command in the SQL form. in the copy command, we need to specify the path of the CSV file. 
CSV File Used:
CSV File Used
'''COPY table_name
FROM 'C:\folder\file.csv' 
DELIMITER ',' 
CSV HEADER;'''
Below is the implementation:
Python3
import psycopg2  conn = psycopg2.connect(database="EMPLOYEE_DATABASE",                        user='postgres', password='pass',                         host='127.0.0.1', port='5432')  conn.autocommit = Truecursor = conn.cursor()    sql = '''CREATE TABLE DETAILS(employee_id int NOT NULL,\employee_name char(20),\employee_email varchar(30), employee_salary float);'''    cursor.execute(sql)  sql2 = '''COPY details(employee_id,employee_name,\employee_email,employee_salary)FROM '/private/tmp/details.csv'DELIMITER ','CSV HEADER;'''  cursor.execute(sql2)  sql3 = '''select * from details;'''cursor.execute(sql3)for i in cursor.fetchall():    print(i)  conn.commit()conn.close()
Output:
(1, 'rajesh              ', 'rajesh89@gmail.com', 60000.0)
(2, 'pratyusha           ', 'praty@gmail.com', 75000.0)
(3, 'pratibha            ', 'pratibhaJ@gmail.com', 65000.0)
Picked
Python PostgreSQL
Python Pyscopg2
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Node.js Buffer.toString() Method

13 Oct, 2021
The Buffer.toString() method is used to decode a buffer data to string according to the specified encoding type. The start and end offset is used to decode only particular subset of a buffer. If the byte sequence in the buffer data is not valid according to the provided encoding, then it is replaced by the default replacement character i.e. U+FFFD.
Syntax:
Buffer.toString( encoding, start, end )
Parameters: This method accept two parameters as mentioned above and described below:
encoding: The format in which the buffer data characters has to be encoded. Its default value is ‘utf8’.
start: The beginning index of the buffer data from which encoding has to be start. Its default value is 0.
end: The last index of the buffer data up to which encoding has to be done. Its default value is Buffer.length.
Return Value: It returns decoded string from buffer to string according to specified character encoding.
Example 1:
// Node.js program to demonstrate the   // Buffer.toString() Method          // Creating a buffer var buffer = new Buffer.alloc(5);   // Loop to add value to the bufferfor (var i = 0; i < 5; i++) {    buffer[i] = i + 97;}   // Display the value of buffer// in string formatconsole.log(buffer.toString());console.log(buffer.toString('utf-8', 1, 4));console.log(buffer.toString('hex'));
Output:
abcde
bcd
6162636465

Explanation: In the above example, we have declared a variable buffer with size of 5 and have filled with ASCII value from ‘a’ to ‘e’. Next, we have used toString() method without any parameters, that returns the string with default encoding style i.e. ‘UTF-8’ of complete buffer. On the next line, it returns the string with encoding style of ‘UTF-8’ from index 1 to 3 (here, 4 is excluded). At last, it returns the string representation with encoding style of ‘HEX’.
Example 2:
// Node.js program to demonstrate the   // Buffer.toString() Method          // Creating a buffer var buffer = new Buffer.alloc(5);   // Loop to add value to the bufferfor (var i = 0; i < 5; i++) {    buffer[i] = i + 97;}   // Display the value of buffer// in string formatconsole.log(buffer.toString(undefined));
Output:
abcde

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Python – Find Words with both alphabets and numbers

22 Apr, 2020
Sometimes, while working with Python strings, we can have problem in which we need to extract certain words with contain both numbers and alphabets. This kind of problem can occur in many domains like school programming and web-development. Lets discuss certain ways in which this task can be performed.
Method #1 : Using any() + isdigit() + isalpha()The combination of above functionalities can be used to perform this task. In this, we iterate for all the words and check for required combination using isdigit() and isalpha().
# Python3 code to demonstrate working of # Words with both alphabets and numbers# Using isdigit() + isalpha() + any()  # initializing stringtest_str = 'geeksfor23geeks is best45 for gee34ks and cs'  # printing original stringprint("The original string is : " + test_str)  # Words with both alphabets and numbers# Using isdigit() + isalpha() + any()res = []temp = test_str.split()for idx in temp:    if any(chr.isalpha() for chr in idx) and any(chr.isdigit() for chr in idx):        res.append(idx)          # printing result print("Words with alphabets and numbers : " + str(res)) 
The original string is : geeksfor23geeks is best45 for gee34ks and csWords with alphabets and numbers : [‘geeksfor23geeks’, ‘best45’, ‘gee34ks’]
 
Method #2 : Using regexThis is yet another way by which we can perform this task. In this, we feed the string to findall(), and extract the required result. Returns strings till the numbers only.
# Python3 code to demonstrate working of # Words with both alphabets and numbers# Using regeximport re  # initializing stringtest_str = 'geeksfor23geeks is best45 for gee34ks and cs'  # printing original stringprint("The original string is : " + test_str)  # Words with both alphabets and numbers# Using regexres = re.findall(r'(?:\d+[a-zA-Z]+|[a-zA-Z]+\d+)', test_str)          # printing result print("Words with alphabets and numbers : " + str(res)) 
The original string is : geeksfor23geeks is best45 for gee34ks and csWords with alphabets and numbers : [‘geeksfor23’, ‘best45’, ‘gee34’]
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find the Product of first N Prime Numbers in C++

Suppose we have a number n. We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210.
We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them.
 Live Demo
#include<iostream>
using namespace std;
long PrimeProds(int n) {
   bool prime[n + 1];
   for(int i = 0; i<=n; i++){
      prime[i] = true;
   }
   for (int i = 2; i * i <= n; i++) {
      if (prime[i] == true) {
         for (int j = i * 2; j <= n; j += i)
            prime[j] = false;
      }
   }
   long product = 1;
   for (int i = 2; i <= n; i++)
      if (prime[i])
      product *= i;
   return product;
}
int main() {
   int n = 8;
   cout << "Product of primes up to " << n << " is: " << PrimeProds(n);
}
Product of primes up to 8 is: 210
Java Examples - Detect Face in an Image

How to detect a face in an image using java.
Following is the program to detect a face in an image using java.
import org.opencv.core.Core;  
import org.opencv.core.Mat; 
import org.opencv.core.MatOfRect; 
import org.opencv.core.Point; 
import org.opencv.core.Rect; 
import org.opencv.core.Scalar; 

import org.opencv.imgcodecs.Imgcodecs;  
import org.opencv.imgproc.Imgproc; 
import org.opencv.objdetect.CascadeClassifier;  
  
public class DetectingFaceInAnImage {  
   public static void main (String[] args) {     
      
      //Loading the OpenCV core library  
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); 

      //Reading the Image from the file and storing it in to a Matrix object 
      String file = "C:/opencv/facedetection_input.jpg";
      Mat src = Imgcodecs.imread(file);  
      
      //Instantiating the CascadeClassifier 
      String xmlFile = "C:/EXAMPLES/OpenCV/facedetect/lbpcascade_frontalface.xml"; 
      CascadeClassifier classifier = new CascadeClassifier(xmlFile); 

      //Detecting the face in the snap 
      MatOfRect faceDetections = new MatOfRect(); 
      classifier.detectMultiScale(src, faceDetections);  
      System.out.println(String.format("Detected %s faces", 
         faceDetections.toArray().length));  
      
      //Drawing boxes  
      for (Rect rect : faceDetections.toArray()) { 
         Imgproc.rectangle(src,       //where to draw the box 
         new Point(rect.x, rect.y),   //bottom left 
         new Point(rect.x + rect.width, rect.y + rect.height),  //top right  
         new Scalar(0, 0, 255), 
         3);    //RGB color 
      } 
      //Writing the image     
      Imgcodecs.imwrite("C:/opencv/facedetect_output1.jpg", src); 
      
      System.out.println("Image Processed");  
   }     
}
 Print
 Add Notes
 Bookmark this page