code-rag-bench/online-tutorials huggingface dataset:
How to create a JMenuBar Component in Java?

To create a JMenuBar component, use the JMenuBar class −
JMenuBar menuBar = new JMenuBar();
Now, create menus inside the MenuBar −
JMenu fileMenu = new JMenu("File");
Add the above menu to the MenuBar −
menuBar.add(fileMenu);
The following is an example to create a JMenuBar Component in Java −
package my;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class SwingDemo {
   public static void main(final String args[]) {
      JFrame frame = new JFrame("MenuBar Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JMenuBar menuBar = new JMenuBar();
      JMenu fileMenu = new JMenu("File");
      fileMenu.setMnemonic(KeyEvent.VK_F);
      menuBar.add(fileMenu);
      JMenuItem menuItem1 = new JMenuItem("New", KeyEvent.VK_N);
      fileMenu.add(menuItem1);
      JMenuItem menuItem2 = new JMenuItem("Open File", KeyEvent.VK_O);
      fileMenu.add(menuItem2);
      JMenu editMenu = new JMenu("Edit");
      editMenu.setMnemonic(KeyEvent.VK_E);
      menuBar.add(editMenu);
      frame.setJMenuBar(menuBar);
      frame.setSize(550, 350);
      frame.setVisible(true);
   }
}
How to add 2 hours to a JavaScript Date object?

To add hours to a JavaScript Date object, use the setHours() method. Under that, get the current hours and 2 hours to it. JavaScript date setHours() method sets the hours for a specified date according to local time.
You can try to run the following code to add 2 hours to date.
 Live Demo
<html>
   <head>
      <title>JavaScript setHours Method</title>
   </head>
   <body>
      <script>
         var dt = new Date();
         dt.setHours( dt.getHours() + 2 );
         document.write( dt );
      </script>
   </body>
</html>
Sat Dec 15 2018 15:49:50 GMT+0530 (India Standard Time)
How to extract all the .txt files from a zip file using Python?

In order to extract all .txt files from a zip, you'll need to loop over all files in the zipfile, check if a file is txt file or not. If it is a txt file then extract it. For this we'll use the zipfile module and its extract function.
import zipfile
my_zip = zipfile.Zipfile('my_zip_file.zip') # Specify your zip file's name here
storage_path = '.'
for file in my_zip.namelist():
    if my_zip.getinfo(file).filename.endswith('.txt'):
        my_zip.extract(file, storage_path) # extract the file to current folder if it is a text file
Running the above code will open the my_zip_file.zip and extract all txt files from it and store them in the current directory.
Bokeh - Server

Bokeh architecture has a decouple design in which objects such as plots and glyphs are created using Python and converted in JSON to be consumed by BokehJS client library.
However, it is possible to keep the objects in python and in the browser in sync with one another with the help of Bokeh Server. It enables response to User Interface (UI) events generated in a browser with the full power of python. It also helps automatically push server-side updates to the widgets or plots in a browser.
A Bokeh server uses Application code written in Python to create Bokeh Documents. Every new connection from a client browser results in the Bokeh server creating a new document, just for that session.
First, we have to develop an application code to be served to client browser. Following code renders a sine wave line glyph. Along with the plot, a slider control is also rendered to control the frequency of sine wave. The callback function update_data() updates ColumnDataSource data taking the instantaneous value of slider as current frequency.
import numpy as np
from bokeh.io import curdoc
from bokeh.layouts import row, column
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Slider, TextInput
from bokeh.plotting import figure
N = 200
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
source = ColumnDataSource(data = dict(x = x, y = y))
plot = figure(plot_height = 400, plot_width = 400, title = "sine wave")
plot.line('x', 'y', source = source, line_width = 3, line_alpha = 0.6)
freq = Slider(title = "frequency", value = 1.0, start = 0.1, end = 5.1, step = 0.1)
def update_data(attrname, old, new):
   a = 1
   b = 0
   w = 0
   k = freq.value
   x = np.linspace(0, 4*np.pi, N)
   y = a*np.sin(k*x + w) + b
   source.data = dict(x = x, y = y)
freq.on_change('value', update_data)
curdoc().add_root(row(freq, plot, width = 500))
curdoc().title = "Sliders"
Next, start Bokeh server by following command line −
Bokeh serve –show sliders.py

Bokeh server starts running and serving the application at localhost:5006/sliders. The console log shows the following display −
C:\Users\User>bokeh serve --show scripts\sliders.py
2019-09-29 00:21:35,855 Starting Bokeh server version 1.3.4 (running on Tornado 6.0.3)
2019-09-29 00:21:35,875 Bokeh app running at: http://localhost:5006/sliders
2019-09-29 00:21:35,875 Starting Bokeh server with process id: 3776
2019-09-29 00:21:37,330 200 GET /sliders (::1) 699.99ms
2019-09-29 00:21:38,033 101 GET /sliders/ws?bokeh-protocol-version=1.0&bokeh-session-id=VDxLKOzI5Ppl9kDvEMRzZgDVyqnXzvDWsAO21bRCKRZZ (::1) 4.00ms
2019-09-29 00:21:38,045 WebSocket connection opened
2019-09-29 00:21:38,049 ServerConnection created

Open your favourite browser and enter above address. The Sine wave plot is displayed as follows −
You can try and change the frequency to 2 by rolling the slider.
 Print
 Add Notes
 Bookmark this page
Class getField() method in Java with Examples - GeeksforGeeks

16 Dec, 2019
The getField() method of java.lang.Class class is used to get the specified field of this class, which is the field that is public and its members. The method returns the specified field of this class in the form of Field objects.
Syntax:
public Field getField(String fieldName)
       throws NoSuchFieldException,
              SecurityException

Parameter: This method accepts a parameter fieldName which is the Field to get.
Return Value: This method returns the specified field of this class in the form of Field objects.
Exception This method throws:
NoSuchFieldException if a field with the specified name is not found.
NullPointerException if name is null
SecurityException if a security manager is present and the security conditions are not met.
Below programs demonstrate the getField() method.
Example 1:
// Java program to demonstrate getField() method  import java.util.*;  public class Test {      public Object obj;      public static void main(String[] args)        throws ClassNotFoundException, NoSuchFieldException    {          // returns the Class object for this class        Class myClass = Class.forName("Test");          System.out.println("Class represented by myClass: "                           + myClass.toString());          String fieldName = "obj";          // Get the field of myClass        // using getField() method        System.out.println(            fieldName + " Field of myClass: "            + myClass.getField(fieldName));    }}
Class represented by myClass: class Test
obj Field of myClass: public java.lang.Object Test.obj

Example 2:
// Java program to demonstrate getField() method  import java.util.*;  class Main {      private Object obj;      Main()    {          class Arr {        };          obj = new Arr();    }      public static void main(String[] args)        throws ClassNotFoundException, NoSuchFieldException    {        Main t = new Main();          // returns the Class object        Class myClass = t.obj.getClass();          String fieldName = "obj";          try {            // Get the field of myClass            // using getField() method            System.out.println(                fieldName + " Field of myClass: "                + myClass.getField(fieldName));        }        catch (Exception e) {            System.out.println(e);        }    }}
java.lang.NoSuchFieldException: obj

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getField-java.lang.String-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java
Python String rsplit() Method

19 Aug, 2021
Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator.
Syntax: 
str.rsplit(separator, maxsplit)
Parameters:  
separator: The is a delimiter. The string splits at this specified separator starting from the right side. It is not provided then any white space is a separator.
maxsplit: It is a number, which tells us to split the string into a maximum of provided number of times. If it is not provided then there is no limit.  
Return:
Returns a list of strings after breaking the given string from the right side by the specified separator.
Error:  
We will not get any error even if we are not passing any argument.
Python3
# Python code to split a string# using rsplit.  # Splits at spaceword = 'geeks for geeks'print(word.rsplit())  # Splits at 'g'. Note that we have# provided maximum limit as 1. So# from right, one splitting happens# and we get "eeks" and "geeks, for, "word = 'geeks, for, geeks'print(word.rsplit('g', 1))  # Splitting at '@' with maximum splitting# as 1word = 'geeks@for@geeks'print(word.rsplit('@', 1))
Output: 
['geeks', 'for', 'geeks']
['geeks, for, ', 'eeks']
['geeks@for', 'geeks']
Python3
word = 'geeks, for, geeks, pawan'  # maxsplit: 0print(word.rsplit(', ', 0))  # maxsplit: 4print(word.rsplit(', ', 4))  word = 'geeks@for@geeks@for@geeks'  # maxsplit: 1print(word.rsplit('@', 1))  # maxsplit: 2print(word.rsplit('@', 2))
Output: 
['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']
['geeks@for@geeks@for', 'geeks']
['geeks@for@geeks', 'for', 'geeks']
Python3
word = 'geeks for geeks'  # Since separator is 'None', # so, will be splitted at spaceprint(word.rsplit(None, 1))  print(word.rsplit(None, 2))  # Also observe theseprint('@@@@@geeks@for@geeks'.rsplit('@'))print('@@@@@geeks@for@geeks'.rsplit('@', 1))print('@@@@@geeks@for@geeks'.rsplit('@', 3))print('@@@@@geeks@for@geeks'.rsplit('@', 5))
Output: 
['geeks for', 'geeks']
['geeks', 'for', 'geeks']
['', '', '', '', '', 'geeks', 'for', 'geeks']
['@@@@@geeks@for', 'geeks']
['@@@@', 'geeks', 'for', 'geeks']
['@@', '', '', 'geeks', 'for', 'geeks']
anikakapoor
AmiyaRanjanRout
Python-Built-in-functions
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is currying function in JavaScript ?

29 Sep, 2021
It is a technique in functional programming, transformation of the function of multiple arguments into several functions of a single argument in sequence. The translation of function happens something like this,
function simpleFunction(param1, param2, param3, .....) => function curriedFunction(param1)(param2)(param3)(....
We simply wrap function inside a function, which means we are going to return a function from another function to obtain this kind of translation. The parent function takes the first provided argument and returns the function that takes the next argument and this keeps on repeating till the number of arguments ends. Hopefully, the function that receives the last argument returns the expected result.  
Note: An American mathematician named Haskell Curry developed this technique, that’s why it is called as currying.
Example 1: Let’s say we have the length, breadth, and height of a cuboid and we want to construct a function that can calculate the volume. The function is being called which consequently executes its code by provided arguments and returns the appropriate result, FInally console.log prints the returned value on console.
JavaScript
<script>    function calculateVolume(length, breadth, height) {        return length * breadth * height;    }    console.log(calculateVolume(4, 5, 6));</script>
Output:
120
Example 2: This example explains the currying technique with the help of closures. During the thread of execution, the calculateVolume() function will be invoked. Inside there is an anonymous function, receiving a parameter and returning some code. We are exposing our function from another function, so the closure will be created. Closure always contains the function definition along with the lexical environment of the parent, both things remain connected as a bundle. Hence, it does not matter where we invoke them, the all inner functions will always hold access to the variable of their parent.As soon as we have got the returned result as a function the next argument is ready to be passed, this process will continue till the second last function. Finally, the innermost return keyword returns the expected result.
JavaScript
<script>    function calculateVolume(length) {        return function (breadth) {            return function (height) {                return length * breadth * height;            }        }    }    console.log(calculateVolume(4)(5)(6));</script>
Output:
120
javascript-functions
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
sqrt() function for complex number in C++

30 Oct, 2020
The complex version of sqrt() function is defined in the complex header file. This function is used to calculate the square root of the complex number z with a branch cut along the negative real axis.
Syntax:  
template <class T> complex<T>
    sqrt(const complex<T>& z);


Parameters: This method takes a mandatory parameter z which represents the complex number whose square root is to be calculated.Return Value: This function returns the square root of the complex number z.
Below program illustrate the sqrt() function for complex number in C++:
cpp
// C++ program to demonstrate// example of sqrt() function. #include <math.h>#include <iostream>#include <complex>using namespace std; int main(){    cout << "Square root of -9 is ";    cout << sqrt(complex<double>(-9.0, 0.0)) << endl;     cout << "Square root of (-9, -0) is ";    cout << sqrt(complex<double>(-9.0, -0.0)) << endl;     return 0;}
Square root of -9 is (0,3)
Square root of (-9, -0) is (0,-3)

tobiasgrothmann
CPP-Functions
cpp-template
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Inheritance in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Test Bed

The test execution environment configured for testing. Test bed consists of specific hardware, software, Operating system, network configuration, the product under test, other system software and application software.
It is the combination of hardware and software environment on which the tests will be executed. It includes hardware configuration, operating system settings, software configuration, test terminals and other support to perform the test.
A typical test bed for a web-based application is given below:
Web Server - IIS/Apache
Database - MS SQL
OS - Windows/ Linux
Browser - IE/FireFox
Java version : version 6
JavaScript | Reflect.apply() Method

29 Sep, 2021
The Reflect.apply() method is a standard build-in object in JavaScript which is used to call a function using the specified argument. It works similar to the Function.prototype.apply() method to call a function, but in a efficient manner and easy to understand.Syntax:  
Reflect.apply(target, thisArgument, argumentsList)
Parameter: This method accepts three parameters as mentioned above and described below:  
target: This parameter is the target function which is going to be called.
thisArgument: This parameter has the this value which is required for the calling the target function.
ArgumentsList: This parameter is an array-like object specifying the argument with which target should be called.
Return Value: Calling the given Target function resulted in the specified this value and arguments.Exceptions: A TypeError is exception given as the result, when the target is not callable.Below examples illustrate the Reflect.apply() Method in JavaScript:Example 1: List argument is passed and dictionary – object is created.  
javascript
function geeks1 (a, b, c) {     this.x = a;     this.y = b;     this.z = c; }const obj = {}; Reflect.apply ( geeks1 , obj, [12,42,32] ); console.log( obj ); 
Output:  
{ x: 12, y: 42, z: 32 }
Example 2: In this example, the empty list argument is passed and the function is called. And the second portion contains mathematical computation, finding the minimum element from the list.  
javascript
var geeks2 = function() { console.log(this); } Reflect.apply(geeks2, 'GeeksforGeeks', []);    var list= [31, 45, 143, 5]; console.log(Reflect.apply(Math.min, undefined, list));
Output:  
String { "GeeksforGeeks" }
5
Example 3:  
javascript
// Converting the list of integer into char stringconsole.log(Reflect.apply(String.fromCharCode,    undefined, [103, 101, 101, 107, 115, 102,          111, 114, 103, 101, 101, 107, 115]))  // Extract the indexed value of string(character)console.log(Reflect.apply(''.charAt, 'shubham', [3]))
Output:  
geeksforgeeks
b
Supported Browsers: The browsers supported by JavaScript Reflect.apply() Method are listed below:  
Google Chrome 49 and above
Edge 12 and above
Firefox 42 and above
Opera 36 and above
Safari 10 and above
 
Akanksha_Rai
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How I can replace a JavaScript alert pop up with a fancy alert box?

To design a custom JavaScript alert box, try to run the following code. The code uses a JavaScript library jQuery and CSS to create a fancy alert box different from the standard JavaScript alert box −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #91FF00;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 80px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id = "confirm">
         <div class = "message">This is a warning message.</div>
         <button class  ="yes">OK</button>
      </div>
      <input type = "button" value = "Click Me" onclick = "functionAlert();" />
   </body>
</html>
Which is faster, a MySQL CASE statement or a PHP if statement?

The MySQL CASE statement is faster in comparison to PHP if statement. The PHP if statement takes too much time because it loads data and then process while CASE statement does not.
Let us first create a table and work around an example of MySQL CASE statement −
mysql> create table DemoTable (Value int);
Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(500);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(1000);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
| 100   |
| 500   |
| 1000  |
+-------+
3 rows in set (0.00 sec)
Following is the query for MySQL CASE statement −
mysql> select Value, case when Value > 500 THEN "It is greater than or equal to 1000"
   else
   "It is lower than 1000"
   end as comparison from DemoTable;
This will produce the following output −
+-------+-------------------------------------+
| Value | comparison                          |
+-------+-------------------------------------+
|   100 | It is lower than 1000               |
|   500 | It is lower than 1000               |
| 1000 | It is greater than or equal to 1000  |
+-------+-------------------------------------+
3 rows in set (0.00 sec)
Explain Compile time and Run time initialization in C programming?

Let’s take the concept of arrays to about compile time and run time initialization −
Array is a collection of items stored at contiguous memory locations and elements can access by using indices.
In compile time initialization, user has to enter the details in the program itself.
Compile time initialization is same as variable initialization. The general form of initialization of array is as follows −
type name[size] = { list_of_values };
//integer array initialization
int rollnumbers[4]={ 2, 5, 6, 7};
//float array initialization
float area[5]={ 23.4, 6.8, 5.5,7.3,2.4 };
//character array initialization
char name[9]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', '\0' };
Following is a C program to display array −
 Live Demo
#include<stdio.h>
void main(){
   //Declaring array with compile time initialization//
   int array[5]={1,2,3,4,5};
   //Declaring variables//
   int i;
   //Printing O/p using for loop//
   printf("Displaying array of elements :");
   for(i=0;i<5;i++){
      printf("%d ",array[i]);
   }
}
Displaying array of elements :1 2 3 4 5
Using runtime initialization user can get a chance of accepting or entering different values during different runs of program.
It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf() function.
Following is a C program to calculate sum and product of all elements in an array using run time compilation −
 Live Demo
#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
   //Reading elements into the array's A and B using for loop//
   printf("Enter elements into the array A: \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] :",i,j);
         scanf("%d",&A[i][j]);
      }
      printf("\n");
   }
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("B[%d][%d] :",i,j);
         scanf("%d",&B[i][j]);
      }
      printf("\n");
   }
   //Calculating sum and printing output//
   printf("Sum array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         sum[i][j]=A[i][j]+B[i][j];
         printf("%d\t",sum[i][j]);
      }
      printf("\n");
   }
   //Calculating product and printing output//
   printf("Product array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         product[i][j]=A[i][j]*B[i][j];
         printf("%d\t",product[i][j]);
      }
      printf("\n");
   }
}
Enter elements into the array A:
A[0][0] :A[0][1] :A[0][2] :
A[1][0] :A[1][1] :A[1][2] :
B[0][0] :B[0][1] :B[0][2] :
B[1][0] :B[1][1] :B[1][2] :
Sum array is :
000
000
Product array is :
000
000
Add new header files in Arduino IDE

Sometimes, you may feel the need to define your own custom header files, for organizing your code better. Say you want to create a global_variables.h file for storing all your global variables.
You can create the file within Arduino IDE by clicking on the bottom arrow at the top right of the screen, and selecting 'New Tab'. (Alternatively, you can press Ctrl+Shift+N on your keyboard)
Name your file in the prompt and press OK.
The new file gets created, and can be found in your Sketch folder.
In order to include this file in your main .ino code, you can simply add the following line at the top of your application −
#include "global_variables.h"
You can replace global_variables.h with the file name you provided in the prompt.
Now you can go ahead and add all global variables in this new .h file. In general, this feature helps a lot when you try to organize lengthy codes.
How to make a Tkinter window jump to the front?

In order to make the tkinter window or the root window jump above all the other windows, we can use attributes method that will generally take two values specifying the “topmost” value and the other is a Boolean value.
#Importing the library
from tkinter import *

#Create an instance of tkinter window or frame
win= Tk()

#Setting the geometry of window
win.geometry("600x250")

#Create a Label
Label(win, text= "Hello Everyone!",font=('Helvetica bold',
15)).pack(pady=20)

#Make the window jump above all
win.attributes('-topmost',1)

win.mainloop()
Running the above code will make the window stay above all other windows,
Use of explicit keyword in C++


Here we will see what will be the effect of explicit keyword in C++. Before discussing that, let us see one example code, and try to find out its output.
#include <iostream>
using namespace std;
class Point {
   private:
      double x, y;
   public:
      Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
         //constructor
      }
      bool operator==(Point p2) {
         if(p2.x == this->x && p2.y == this->y)
         return true;
         return false;
      }
};
int main() {
   Point p(5, 0);
   if(p == 5)
      cout << "They are same";
   else
      cout << "They are not same";
}
They are same
This is working fine because we know that if one constructor can be called using one argument only, then it will be converted into conversion constructor. But we can avoid this kind of conversion, as this may generate some unreliable results.
To restrict this conversion, we can use the explicit modifier with the constructor. In that case, it will not be converted. If the above program is used using explicit keyword, then it will generate compilation error.
#include <iostream>
using namespace std;
class Point {
   private:
      double x, y;
   public:
      explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
         //constructor
      }
      bool operator==(Point p2) {
         if(p2.x == this->x && p2.y == this->y)
         return true;
         return false;
      }
};
int main() {
   Point p(5, 0);
   if(p == 5)
      cout << "They are same";
   else
      cout << "They are not same";
}
[Error] no match for 'operator==' (operand types are 'Point' and 'int')
[Note] candidates are:
[Note] bool Point::operator==(Point)
We can still typecast a value to the Point type by using explicit casting.
#include <iostream>
using namespace std;
class Point {
   private:
      double x, y;
   public:
      explicit Point(double a = 0.0, double b = 0.0) : x(a), y(b) {
         //constructor
      }
      bool operator==(Point p2) {
         if(p2.x == this->x && p2.y == this->y)
         return true;
         return false;
      }
};
int main() {
   Point p(5, 0);
   if(p == (Point)5)
      cout << "They are same";
   else
      cout << "They are not same";
}
They are same
vector data() function in C++ STL

09 Jun, 2022
The std::vector::data() is an STL in C++ which returns a direct pointer to the memory array used internally by the vector to store its owned elements. 
Syntax: 
vector_name.data()
Parameters: The function does not accept any parameters.Return value: The function returns a pointer to the first element in the array which is used internally by the vector.
Time Complexity – Constant O(1)
Below program illustrate the above function:
CPP
// C++ program to demonstrate the// vector::date() function#include <bits/stdc++.h>using namespace std; int main(){    // initialising vector    vector<int> vec = { 10, 20, 30, 40, 50 };     // memory pointer pointing to the    // first element    int* pos = vec.data();     // prints the vector    cout << "The vector elements are: ";    for (int i = 0; i < vec.size(); ++i)        cout << *pos++ << " ";     return 0;}
The vector elements are: 10 20 30 40 50 
sunilpanda20022002
utkarshgupta110092
CPP-Functions
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
Python NLTK | nltk.WhitespaceTokenizer - GeeksforGeeks

07 Jun, 2019
With the help of nltk.tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from string of words or sentences without whitespaces, new line and tabs by using tokenize.WhitespaceTokenizer() method.
Syntax : tokenize.WhitespaceTokenizer()Return : Return the tokens from a string
Example #1 :In this example we can see that by using tokenize.WhitespaceTokenizer() method, we are able to extract the tokens from stream of words.
# import WhitespaceTokenizer() method from nltkfrom nltk.tokenize import WhitespaceTokenizer     # Create a reference variable for Class WhitespaceTokenizertk = WhitespaceTokenizer()     # Create a string inputgfg = "GeeksforGeeks \nis\t for geeks"     # Use tokenize methodgeek = tk.tokenize(gfg)     print(geek)
Output :
[‘GeeksforGeeks’, ‘is’, ‘for’, ‘geeks’]
Example #2 :
# import WhitespaceTokenizer() method from nltkfrom nltk.tokenize import WhitespaceTokenizer     # Create a reference variable for Class WhitespaceTokenizertk = WhitespaceTokenizer()     # Create a string inputgfg = "The price\t of burger \nin BurgerKing is Rs.36.\n"     # Use tokenize methodgeek = tk.tokenize(gfg)     print(geek)
Output :
[‘The’, ‘price’, ‘of’, ‘burger’, ‘in’, ‘BurgerKing’, ‘is’, ‘Rs.36.’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
What is the difference between field, variable, attribute, and property in Java - GeeksforGeeks

28 Mar, 2022
Variable A variable is the name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. Each variable has a type, such as int, double or Object, and a scope. Class variable may be instance variable, local variable or constant. Also, you should know that some people like to call final non-static variables. In Java, all the variables must be declared before use.  Field A data member of a class. Unless specified otherwise, a field can be public, static, not static and final. 
JAVA
public class Customer {     // Fields of customer    final String field1 = "Fixed Value";    int name;}
Attribute An attribute is another term for a field. It’s typically a public field that can be accessed directly. Let’s see a particular case of Array, the array is actually an object and you are accessing the public constant value that represents the length of the array. In NetBeans or Eclipse, when we type object of a class and after that dot(.) they give some suggestion those suggestion is called Attribute. Note: Here Never Show Private Fields  Property It is also used for fields, it typically has getter and setter combination. Example: 
JAVA
public class Test {    private int number;     public int getNumber()    {        return this.number;    }     public void setNumber(int num)    {        this.number = num;    }}
 
 
JAVA
public class Variables {     // Constant    public final static String name = "robot";     // Value    final String dontChange = "India";     // Field    protected String river = "GANGA";     // Property    private String age;     // Still the property    public String getAge()    {        return this.age;    }     // And now the setter    public void setAge(String age)    {        this.age = age;    }}
sagartomar9927
java-basics
Technical Scripter 2018
Java
Technical Scripter
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
How to Install Ruby on Termux? - GeeksforGeeks

11 Apr, 2022
Ruby is an open-source programming language. It can be installed in any operating system. It is an interpreted, high-level object-oriented programming language. It was first implemented in the mid-1990s in Japan. It was developed & designed by Yukihiro “Martz” Matsumoto. The developer wants a programming language that is completely object-oriented. As he could not find any he developed Ruby.
Ruby is completely an object-oriented programming language.
In Ruby, it has been seen that the development code is much faster than other programming languages.
Follow the below steps to install Ruby on Termux:
Step 1: To install Ruby in termux first you have to install termux in your android.
Step 2: Open termux in mobile.
Step 3: Then we have to write the below commands like
$ cd . .
$ cd usr/
$ cd etc/
$ cd apt
$ ls
Then we have to wait for some time.
Step 4: Again we have to write the below command:
$ nano sources.list
Step 5:Now enter the below link  as :
deb https://termux.net stable main
Step 6: Now again run the below command:
$ cd sources.list.d/
$ mv *.list ../
$ ls
$ cd . .
$ apt update
Step 7: Then run the below command to install Ruby:
$ pkg install ruby
Step 8: Now enter “Y” when prompted:
Step 9: Then we have to run the following link:
echo "export LD_LIBRARY_PATH=/data/data/com.termux/files/usr/lib">>-/.bashrc
Step 10: Then we have to run the below command  to exit from termux:
$ exit
Use the below command to verify the Ruby installation on Termux:
$ ruby
$ ruby -v
Congratulation. At this point, you have successfully installed Ruby on Termux.
sumitgumber28
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Install Jupyter Notebook on MacOS?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
Python | Check for float string - GeeksforGeeks

29 May, 2019
One of the most notable breakthrough that Python brought was that the interconversion between the datatypes was done in a very easy manner and hence making it quite powerful. String can be converted to integers easily, but converting a float value is still difficult task. Let’s discuss certain ways in which one can check if string is a float to avoid potential errors.
Method #1 : Using isdigit() + replace()The combination of above function is used to perform this task and hence. This works in 2 steps, first the point value is erased and the string is joined to form a digit and then is checked. The drawback is that this doesn’t check for potential exponent values that can also form a float number.
# Python3 code to demonstrate# Check for float string# using isdigit() + replace()  # initializing string test_string = "45.657"  # printing original string print("The original string : " + str(test_string))  # using isdigit() + replace()# Check for float stringres = test_string.replace('.', '', 1).isdigit()  # print resultprint("Is string a possible float number ? : " + str(res))
The original string : 45.657
Is string a possible float number ? : True

 
Method #2 : Using float() + Exception handlingThis task can also be achieved using the float function which tries to convert the string to floating point value, and it’s failure guarantees that it’s not potential float value.
# Python3 code to demonstrate# Check for float string# using float()  # initializing string test_string = "45.657"  # printing original string print("The original string : " + str(test_string))  # using float()# Check for float stringtry :     float(test_string)    res = Trueexcept :    print("Not a float")    res = False      # print resultprint("Is string a possible float number ? : " + str(res))
The original string : 45.657
Is string a possible float number ? : True

Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Create a Pandas DataFrame from Lists
Python program to count the number of spaces in string - GeeksforGeeks

12 Jul, 2021
Given a string, the task is to write a Python program to count the number of spaces in the string.
Examples:
Input: "my name is geeks for geeks"
Output: number of spaces = 5

Input: "geeksforgeeks"
Output: number of spaces=0
Approach:
Input string from the user
Initialize count variable with zero
Run a for loop i from 0 till the length of the string
Inside for loop, check if s[i] == blank, then increment count by 1
Outside for loop, print count
Example 1:
Python3
# create function that# return space countdef check_space(string):         # counter    count = 0         # loop for search each index    for i in range(0, len(string)):                 # Check each char        # is blank or not        if string[i] == " ":            count += 1             return count # driver nodestring = "Welcome to geeksforgeeks" # call the function and displayprint("number of spaces ",check_space(string))
Output:
number of spaces  2
Example 2:
Python3
# create function that# return space countdef check_space(string):         # counter    count = 0         # loop for search each index    for i in string:                 # Check each char        # is blank or not        if i == " ":            count += 1             return count # driver nodestring = "Welcome to geeksforgeeks, Geeks!" # call the function and displayprint("number of spaces ",check_space(string))    
Output:
number of spaces  3
Example 3: Using the count() function.
Python3
# Create function that# return space countdef check_space(Test_string):    return Test_string.count(" ")  # Driver functionif __name__ == "__main__":    Test_string = "Welcome to geeksforgeeks, Geeks!"     # Call the function and display    print(f"Number of Spaces: {check_space(Test_string)}")
Output: 
Number of Spaces: 3
gittysatyam
pradiptamukherjee
ruhelaa48
Python string-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
PHP | Check if all characters are lower case - GeeksforGeeks

30 Sep, 2021
Given a string, check if all characters of it are in lowercase.Examples:  
Input  : gfg123
Output : No
Explanation : There are characters
'1', '2' and '3' that are not lower-
case

Input  : geeksforgeeks
Output : Yes
Explanation : The string "geeksforgeeks" 
consists of all lowercase letters.
 
The above problem can be solved using the in-built functions in PHP. We store multiple values in an array and check using the in-built function in php to check whether all the characters are lowercase. 
We solve the given problem using the in-built functions in PHP and iterate from a given array of strings.We use the following in-built function in PHP: 
ctype_lower : Returns true if all of the characters in the provided string, text, are lowercase letters. Otherwise returns false.
PHP
<?php// PHP program to check if a string has all// lower case characters $strings = array('gfg123', 'geeksforgeeks', 'GfG'); // Checking for above three strings one by one.foreach ($strings as $testcase) {    if (ctype_lower($testcase)) {        echo "Yes\n";    } else {        echo "No\n";    }}?>
Output : 
No
Yes
No
adnanirshad158
PHP-function
PHP-string
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
Different ways for passing data to view in Laravel
How to pass form variables from one page to other page in PHP ?
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?
numpy.ndarray.byteswap() in Python - GeeksforGeeks

28 Nov, 2018
numpy.ndarray.byteswap() function toggle between low-endian and big-endian data representation by returning a byteswapped array, optionally swapped in-place.
Syntax: ndarray.byteswap(inplace=False)
Parameters:inplace : [bool, optional] If True, swap bytes in-place, default is False.
Returns:out : [ndarray] The byteswapped array. If inplace is True, this is a view to self.
Code #1:
# Python program explaining # byteswap() function import numpy as geek  # a is an array of integers.a = geek.array([1, 256, 100], dtype = np.int16)   print(a.byteswap(True))
Output :
[256  1  25600]
 
Code #2: byteswap() function does not work on arrays of strings.
# Python program explaining # byteswap() function import numpy as geek  # a is an array of stringsa = geek.array(["arka","soumen","simran"],dtype = np.int16)  print(a.byteswap(True))
Output :
ValueError                                Traceback (most recent call last)
 in ()
      1 import numpy as geek
----> 2 a = geek.array(["arka","soumen","simran"],dtype = np.int16)
      3 
      4 #a is an array of strings
      5 

ValueError: invalid literal for int() with base 10: 'arka'
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
MathF.Floor() Method in C# with Examples - GeeksforGeeks

04 Apr, 2019
In C#, MathF.Floor(Single) is a MathF class method. This method is used to find the largest integer , which is less than or equal to the specified float value in the argument list.
Syntax: public static float Floor (float x);Here, x is the float(Single) value whose floor value has to be calculated.
Return Type: This method return the largest integral value which will be less than or equal to x.
Example:
// C# program to illustrate the// MathF.Floor(Single) Methodusing System;  class GFG {      // Main method    static void Main()    {          // taking float values        float x1 = 37.00f;        float x2 = 99.99f;        float x3 = 0.2154f;         float x4 = 123.123f;         float x5 = -2.2f;         float x6 = -123.123f;                   // calling the method        result(x1);        result(x2);        result(x3);        result(x4);        result(x5);        result(x6);    }           public static void result(float t1)     {        // Print the original values        // and Floor values        Console.WriteLine("Input Value = " + t1);                  // using the MathF.Floor() Method        Console.WriteLine("Floor value = " + MathF.Floor(t1));     }}
Input Value = 37
Floor value = 37
Input Value = 99.99
Floor value = 99
Input Value = 0.2154
Floor value = 0
Input Value = 123.123
Floor value = 123
Input Value = -2.2
Floor value = -3
Input Value = -123.123
Floor value = -124

CSharp-MathF-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Pointer to an Array in C

It is most likely that you would not understand this section until you are through with the chapter 'Pointers'.
Assuming you have some understanding of pointers in C, let us start: An array name is a constant pointer to the first element of the array. Therefore, in the declaration −
double balance[50];

balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance −
double *p;
double balance[10];

p = balance;

It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate way of accessing the data at balance[4].
Once you store the address of the first element in 'p', you can access the array elements using *p, *(p+1), *(p+2) and so on. Given below is the example to show all the concepts discussed above −
#include <stdio.h>

int main () {

   /* an array with 5 elements */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;
   int i;

   p = balance;
 
   /* output each array element's value */
   printf( "Array values using pointer\n");
	
   for ( i = 0; i < 5; i++ ) {
      printf("*(p + %d) : %f\n",  i, *(p + i) );
   }

   printf( "Array values using balance as address\n");
	
   for ( i = 0; i < 5; i++ ) {
      printf("*(balance + %d) : %f\n",  i, *(balance + i) );
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
Array values using pointer
*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000

In the above example, p is a pointer to double, which means it can store the address of a variable of double type. Once we have the address in p, *p will give us the value available at the address stored in p, as we have shown in the above example.
 Print
 Add Notes
 Bookmark this page