code-rag-bench/online-tutorials huggingface dataset:
std::generate in C++ - GeeksforGeeks

21 Jul, 2017
std::generate, as the name suggests is an STL algorithm, which is used to generate numbers based upon a generator function, and then, it assigns those values to the elements in the container in the range [first, last).
The generator function has to be defined by the user, and it is called successively for assigning the numbers.
Template function:
void generate (ForwardIterator first, ForwardIterator last, Generator gen);

first: Forward iterator pointing to the first element of the container.
last: Forward iterator pointing to the last element of the container.
gen: A generator function, based upon which values will be assigned.

Returns: none
Since, it has a void return type, so it does not return any value.

// C++ program to demonstrate the use of std::generate#include <iostream>#include <vector>#include <algorithm>  // Defining the generator functionint gen(){    static int i = 0;    return ++i;}  using namespace std;int main(){    int i;      // Declaring a vector of size 10    vector<int> v1(10);      // using std::generate    std::generate(v1.begin(), v1.end(), gen);      vector<int>::iterator i1;    for (i1 = v1.begin(); i1 != v1.end(); ++i1) {        cout << *i1 << " ";    }    return 0;}
Output:
1 2 3 4 5 6 7 8 9 10

Next: std::generate_n in C++
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++
Bitwise Operators in C/C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
How to remove non-alphanumeric characters in PHP? - GeeksforGeeks

10 Oct, 2018
Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.
Examples:
Input : !@GeeksforGeeks2018?
Output : GeeksforGeeks2018

Input : Geeks For Geeks
Output : GeeksForGeeks

Syntax:
int preg_match( $pattern, $replacement_string, $original_string )
Parameter: This function accepts three parameter as mentioned above and described below:
$pattern: The pattern that is searched in the string. It must be a regular expression.
$replacement_string: The matched pattern is replaced by the replacement_string.
$original_string: It is the original string in which searching and replacement is done.
Return value:
After the replacement has occurred, the modified string will be returned.
If no matches are found, the original string remains unchanged.
Method 1: The regular expression ‘/[\W]/’ matches all the non-alphanumeric characters and replace them with ‘ ‘ (empty string).
$str = preg_replace( '/[\W]/', '', $str);
In the regular expression W is a meta-character that is preceded by a backslash (\W) that acts to give the combination a special meaning. It means a combination of non-alphanumeric characters.
Example:
<?php   // string containing non-alphanumeric characters$str="!@GeeksforGeeks2018?";  // preg_replace function to remove the// non-alphanumeric characters$str = preg_replace( '/[\W]/', '', $str);  // print the stringecho($str);?>
GeeksforGeeks2018

Method 2: The regular expression ‘/[^a-z0-9 ]/i’ matches all the non-alphanumeric characters and replace them with ‘ ‘ (null string).
$str = preg_replace( '/[^a-z0-9 ]/i', '', $str);
In the regular expression:
i: It is used for case insensitive.
a-z: It is used for all lowercase letters, don’t need to specify A-Z because of i (case insensitive) already mentioned in the statement.
0-9: It is used to match all digits.
Example:
<?php   // string containing non-alphanumeric characters$str="!@GeeksforGeeks2018?";    // preg_replace function to remove the // non-alphanumeric characters$str = preg_replace( '/[^a-z0-9]/i', '', $str);   // print the stringecho($str);?>
GeeksforGeeks2018

Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Check for Presence of Common Elements between Objects in R Programming - is.element() Function - GeeksforGeeks

15 Jun, 2020
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value.
Syntax: is.element(x, y)
Parameters:x and y: Objects with sequence of items
Example 1:
# R program to illustrate # the use of is.element() function     # Vector 1 x1 <- c(1, 2, 3)        # Vector 2  x2 <- c(1:6)         # Calling is.element() Function is.element(x1, x2) is.element(x2, x1)              
Output:
[1] TRUE TRUE TRUE
[1]  TRUE  TRUE  TRUE FALSE FALSE FALSE

Example 2:
# R program to illustrate  # the use of is.element() function     # Data frame 1 data_x <- data.frame(x1 = c(5, 3, 7),                          x2 = c(1, 4, 2))     # Data frame 2 data_y <- data.frame(y1 = c(2, 3, 4),                             y2 = c(1, 4, 2),                     y3 = c(3, 4, 5))     # Calling is.element() Functionis.element(data_x, data_y)   is.element(data_y, data_x)  
Output:
[1] FALSE  TRUE
[1] FALSE  TRUE FALSE

R Array-Functions
R DataFrame-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
Replace Specific Characters in String in R
PostgreSQL - UUID Data Type - GeeksforGeeks

22 Feb, 2021
UUID is an abbreviation for Universal Unique Identifier defined by RFC 4122 and has a size of 128-bit. It is created using internal algorithms that always generate a unique value.
PostgreSQL has its own UUID data type and provides modules to generate them. UUID is generally used in distributed systems as it guarantees a singularity better than the SERIAL data type which produces only singular values within a sole database.PostgreSQL enables you to store and compare UUID values but it does not incorporate functions for producing the UUID values in its core. Instead, it depends on the third-party modules that offer certain algorithms to generate UUIDs. For example the uuid-ossp module offers some handy functions that carry out standard algorithms for generating UUIDs.
To install the “uuid-ossp” extension use the below command:
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
For generating a UUID values based on the blend of computer’s MAC address, present timestamp, and a random value, the uuid_generate_v1() function can be used as shown below:
SELECT uuid_generate_v1();
It would result in output similar to the image below:
For generating a UUID value solely based on random numbers, the uuid_generate_v4() function can be used as shown below:
SELECT uuid_generate_v4();
It would result in output similar to the image below:Example:In this example we will make a table whose primary key is a UUID data type. In supplement, the values of the primary key column will be produced automatically through the uuid_generate_v4() function.First, create a contacts table using the following statement:
CREATE TABLE contacts (
    contact_id uuid DEFAULT uuid_generate_v4 (),
    first_name VARCHAR NOT NULL,
    last_name VARCHAR NOT NULL,
    email VARCHAR NOT NULL,
    phone VARCHAR,
    PRIMARY KEY (contact_id)
);
Now we insert some data to our contacts table as below:
INSERT INTO contacts (
    first_name,
    last_name,
    email,
    phone
)
VALUES
    (
        'Raju',
        'Kumar',
        'rajukumar@gmail.com',
        '408-237-2345'
    ),
    (
        'Nikhil',
        'Aggarwal',
        'nikhilaggarwal@gmail.com',
        '408-237-2344'
    ),
    (
        'Anshul',
        'Aggarwal',
        'anagg@hotmail.com',
        '408-237-2343'
    );
Now we query all rows in the contacts table using the below command:
SELECT
    *
FROM
    contacts;
Output:
postgreSQL
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - CREATE PROCEDURE
PostgreSQL - Joins
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - ROW_NUMBER Function
Python Tkinter | Create LabelFrame and add widgets to it - GeeksforGeeks

02 Apr, 2019
Tkinter is a Python module which is used to create GUI (Graphical User Interface) applications. It is a widely used module which comes along with the Python. It consists of various types of widgets which can be used to make GUI more user-friendly and attractive as well as functionality can be increased.
LabelFrame can be created as follows:
-> import tkinter
-> create root
-> create LabelFrame as child of root

label_frame = ttk.LabelFrame(parent, value = options, ...)
Code #1: Creating LabelFrame and adding a message to it.
# Import only those methods# which are mentioned below, this way of# importing methods is efficientfrom tkinter import Tk, mainloop, LEFT, TOPfrom tkinter.ttk import *  # Creating tkinter window with fixed geometryroot = Tk()root.geometry('250x150')  # This will create a LabelFramelabel_frame = LabelFrame(root, text = 'This is Label Frame')label_frame.pack(expand = 'yes', fill = 'both')  label1 = Label(label_frame, text = '1. This is a Label.')label1.place(x = 0, y = 5)  label2 = Label(label_frame, text = '2. This is another Label.')label2.place(x = 0, y = 35)  label3 = Label(label_frame,           text = '3. We can add multiple\n    widgets in it.')  label3.place(x = 0, y = 65)  # This creates an infinite loop which generally# waits for any interrupt (like keyboard or# mouse) to terminatemainloop()
Output: Code #2: Adding Button and CheckButton widgets inside LabelFrame.
# Import only those methods# which are mentioned below, this way of# importing methods is efficientfrom tkinter import Tk, mainloop, LEFT, TOPfrom tkinter.ttk import *  # Creating tkinter window with fixed geometryroot = Tk()root.geometry('250x150')  # This will create a LabelFramelabel_frame = LabelFrame(root, text = 'This is Label Frame')label_frame.pack(expand = 'yes', fill = 'both')  # Buttonsbtn1 = Button(label_frame, text = 'Button 1')btn1.place(x = 30, y = 10)btn2 = Button(label_frame, text = 'Button 2')btn2.place(x = 130, y = 10)  # Checkbuttonschkbtn1 = Checkbutton(label_frame, text = 'Checkbutton 1')chkbtn1.place(x = 30, y = 50)chkbtn2 = Checkbutton(label_frame, text = 'Checkbutton 2')chkbtn2.place(x = 30, y = 80)  # This creates infinite loop which generally# waits for any interrupt (like keyboard or# mouse) to terminatemainloop()
Output:
Note: One can also add another LabelFrame inside another LabelFrame, as well as one can do styling of any LabelFrame like we do the styling of other widgets.
Python-gui
Python-tkinter
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()
Sqrt, sqrtl, and sqrtf in C++ programming

This article demonstrates the usage of math class essentials functions sqrt(), sqrtl(), and sqrtf() to calculate the square root of double, long, and float type variables with precision respectively. The Math class of C++ offers a wide range of functions to calculate mathematical calculations
including sin, cos, square root, ceil, floor, etc..It is, therefore, mandatory to import the definition of <cmath> header class library in the program in order to avail all calculative methods.
The double sqrtl () method of the Math class returns the square root of a double variable with precision. The syntax of this function is as follows;
double sqrt(double arg)
The following c++ code constructs define a double type variable with an initialization value to calculate its square root value. Then, the math class method sqrt() accepts these values and yield the result with a precision value as follows;
 Live Demo
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main(){
   double val = 225.0;
   cout << fixed << setprecision(5) << sqrt(val);
   return (0);
}
As seen below, the output of this program is being produced with a precision 5 as follows;
15.00000
The long double sqrtl () method of the Math class returns the square root of a long double variable with precision. The syntax of this function is as follows;
long double sqrtl(long double arg)
An illustration is given below to calculate the square root of a long double variable supplied by the using owing to the Math.sqrtl() method as follows;
 Live Demo
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main(){
   long long int val = 1000000000000000000;
   cout << fixed << setprecision(10) << sqrt(val);
   return (0);
}
After compilation of the program using a code editor, the calculated value of the input long type variable is seen as below;
1000000000.000000000
The float sqrtf () method of the Math class returns the square root of a float type variable with precision. The syntax of this function is as follows;
float sqrtf(float arg)
As per the syntax, the program supply a float type variable in the sqrtf() method in pursuit of calculating the square root as following;
 Live Demo
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
int main(){
   float val = 300.0;
   cout << fixed << setprecision(5) << sqrtf(val);
   return (0);
}
The output of the supplied float type variable is squarely rooted as below;
17.32051
MFC - Timer

A timer is a non-spatial object that uses recurring lapses of time from a computer or from your application. To work, every lapse of period, the control sends a message to the operating system. Unlike most other controls, the MFC timer has neither a button to represent it nor a class. To create a timer, you simply call the CWnd::SetTimer() method. This function call creates a timer for your application. Like the other controls, a timer uses an identifier.
Let us create a new MFC dialog based application.
Step 1 −  Remove the Caption and set its ID to IDC_STATIC_TXT
Step 2 − Add the value variable for text control.
Step 3 − Go to the class view in solution.
Step 4 −  Click the CMFCTimeDlg class.
Step 5 − In the Properties window, click the Messages button.
Step 6 − Click the WM_TIMER field and click the arrow of its combo box. Select  OnTimer and implement the event.
void CMFCTimerDlg::OnTimer(UINT_PTR nIDEvent) { 
   // TODO: Add your message handler code here and/or call default 
   CTime CurrentTime = CTime::GetCurrentTime();  
	
   int iHours = CurrentTime.GetHour(); 
   int iMinutes = CurrentTime.GetMinute(); 
   int iSeconds = CurrentTime.GetSecond(); 
   CString strHours, strMinutes, strSeconds;  
 
   if (iHours < 10) 
      strHours.Format(_T("0%d"), iHours); 
   else 
      strHours.Format(_T("%d"), iHours);  
 
   if (iMinutes < 10) 
      strMinutes.Format(_T("0%d"), iMinutes); 
   else 
      strMinutes.Format(_T("%d"), iMinutes);  
   
   if (iSeconds < 10) 
      strSeconds.Format(_T("0%d"), iSeconds); 
   else 
      strSeconds.Format(_T("%d"), iSeconds);  
 
   m_strTimer.Format(_T("%s:%s:%s"), strHours, strMinutes, strSeconds); 
   
   UpdateData(FALSE); 
   CDialogEx::OnTimer(nIDEvent); 
}
Step 7 −  When the above code is compiled and executed, you will see the following output.
 Print
 Add Notes
 Bookmark this page
How to concatenate variable in a string in jQuery?

You can easily concatenate variable in a string in jQuery, using the jQuery html() method. Try to run the following code to learn how to use variable in a string with jQuery −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(function(){
      $("a").click(function(){
        var id= $(".id").html();
        $('.demo').html("<br><div class='new' id='" + id + "'>Welcome to </div>");            
      });
    });
    </script>
</head>
<body>
   <div class="wrap">
      <a href="#">Click me</a>
      <div class="demo"></div>
      <div class="id">Qries</div>
   </div>
</body>
</html>
How can we print all the capital letters of a given string in Java?

The Character class is a subclass of Object class and it wraps a value of the primitive type char in an object. An object of type Character class contains a single field whose type is char.
We can print all the uppercase letters by iterating the characters of a string in a loop and check individual characters are uppercase letters or not using isUpperCase() method and it is a static method of a Character class.
public static boolean isUpperCase(char ch)
public class PrintUpperCaseLetterStringTest {
   public static void main(String[] args) {
      String str = "Welcome To Tutorials Point India";
      for(int i = 0; i < str.length(); i++) {
         if(Character.isUpperCase(str.charAt(i))) {
             System.out.println(str.charAt(i));
         }
       }
   }
}
W
T
T
P
I
Getting the remainder value after division in Julia - mod() Method - GeeksforGeeks

21 Apr, 2020
The mod() is an inbuilt function in julia which is used to return remainder when the specified dividend is divided by divisor.
Syntax: mod(x, y)
Parameters:
x: Specified dividend.
y: Specified divisor.
Returns: It returns remainder when the specified dividend is divided by divisor.
Example 1:
# Julia program to illustrate # the use of mod() method  # Getting remainder when the specified# dividend is divided by divisor.println(mod(0, 3))println(mod(1, 1))println(mod(7, 2))
Output:
0
0
1

Example 2:
# Julia program to illustrate # the use of mod() method  # Getting remainder when the specified# dividend is divided by divisor.println(mod(5, 3))println(mod(10, 2))println(mod(7.3, 2))println(mod(1.8, 0))println(mod(-6, 4))println(mod(-3, -2))
Output:
2
0
1.2999999999999998
NaN
2
-1

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Searching in Array for a given element in Julia
Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods
Exception handling in Julia
Find maximum element along with its index in Julia - findmax() Method
Get number of elements of array in Julia - length() Method
Working with Date and Time in Julia
Getting last element of an array in Julia - last() Method
Working with Excel Files in Julia
Find the first repeated character in a string using C++.

Suppose we have a string; we have to find the first character that is repeated. So is the string is “Hello Friends”, the first repeated character will be l. As there are two l’s one after another.
To solve this, we will use the hashing technique. Create one hash table, scan each character one by one, if the character is not present, then insert into a hash table, if it is already present, then return that character.
 Live Demo
#include<iostream>
#include<unordered_set>
using namespace std;
char getFirstRepeatingChar(string &s) {
   unordered_set<char> hash;
   for (int i=0; i<s.length(); i++) {
      char c = s[i];
      if (hash.find(c) != hash.end())
         return c;
      else
         hash.insert(c);
   }
   return '\0';
}
int main () {
   string str = "Hello Friends";
   cout << "First repeating character is: " << getFirstRepeatingChar(str);
}
First repeating character is: l
OpenCV - Laplacian Transformation

Laplacian Operator is also a derivative operator which is used to find edges in an image. It is a second order derivative mask. In this mask we have two further classifications one is Positive Laplacian Operator and other is Negative Laplacian Operator.
Unlike other operators Laplacian didn’t take out edges in any particular direction but it takes out edges in following classification.
Inward Edges
Outward Edges
You can perform Laplacian Transform operation on an image using the Laplacian() method of the imgproc class, following is the syntax of this method.
Laplacian(src, dst, ddepth)

This method accepts the following parameters −
src − A Mat object representing the source (input image) for this operation.
src − A Mat object representing the source (input image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
dst − A Mat object representing the destination (output image) for this operation.
ddepth − A variable of the type integer representing depth of the destination image.
ddepth − A variable of the type integer representing depth of the destination image.
The following program demonstrates how to perform Laplace transform operation on a given image.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class LaplacianTest {
   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 ="E:/OpenCV/chap18/laplacian_input.jpg";
      Mat src = Imgcodecs.imread(file);

      // Creating an empty matrix to store the result
      Mat dst = new Mat();

      // Applying GaussianBlur on the Image
      Imgproc.Laplacian(src, dst, 10);

      // Writing the image
      Imgcodecs.imwrite("E:/OpenCV/chap18/laplacian.jpg", dst);

      System.out.println("Image Processed");
   }
}
Assume that following is the input image laplacian_input.jpg specified in the above program.
On executing the program, you will get the following output −
Image Processed

If you open the specified path, you can observe the output image as follows −

    70 Lectures 
     9 hours 

 Abhilash Nelson

    41 Lectures 
     4 hours 

 Abhilash Nelson

    20 Lectures 
     2 hours 

 Spotle Learn

    12 Lectures 
     46 mins

 Srikanth Guskra

    19 Lectures 
     2 hours 

 Haithem Gasmi

    67 Lectures 
     6.5 hours 

 Gianluca Mottola
 Print
 Add Notes
 Bookmark this page
H2 Database - Backup

BACKUP is the command used to take database backup into a separate .zip file. Objects are not locked, and when it takes backup the transaction log is also copied. Admin rights are required to execute this command.
Following is the generic syntax of the Backup command.
BACKUP TO fileNameString;

In this example, let us take a backup of the current database into backup.zip file. Use the following command for the same.
BACKUP TO 'backup.zip';
On executing the above command, you will get the backup.zip file in your local file system.

    14 Lectures 
     1 hours 

 Mahesh Kumar

    100 Lectures 
     9.5 hours 

 Hari Om Singh

    108 Lectures 
     8 hours 

 Pavan Lalwani

    10 Lectures 
     1 hours 

 Deepti Trivedi

    20 Lectures 
     2 hours 

 Deepti Trivedi

    14 Lectures 
     1 hours 

 Deepti Trivedi
 Print
 Add Notes
 Bookmark this page
Extract arrays separately from array of Objects in JavaScript

Suppose, we have an array of objects like this −
const arr = [{
   name : 'Client 1',
   total: 900,
   value: 12000
}, {
   name : 'Client 2',
   total: 10,
   value: 800
}, {
   name : 'Client 3',
   total: 5,
   value : 0
}];
We are required to write a JavaScript function that takes in one such array and extracts a separate array for each object property.
Therefore, one array for the name property of each object, one for total and one for value. If there existed more properties, we would have separated more arrays.
The code for this will be −
const arr = [{
   name : 'Client 1',
   total: 900,
   value: 12000
}, {
   name : 'Client 2',
   total: 10,
   value: 800
}, {
   name : 'Client 3',
   total: 5,
   value : 0
}];
const separateOut = arr => {
   if(!arr.length){
      return [];
   };
   const res = {};
   const keys = Object.keys(arr[0]);
   keys.forEach(key => {
      arr.forEach(el => {
         if(res.hasOwnProperty(key)){
            res[key].push(el[key])
         }else{
            res[key] = [el[key]];
         };
      });
   });
   return res;
};
console.log(separateOut(arr));
And the output in the console will be −
{
   name: [ 'Client 1', 'Client 2', 'Client 3' ],
   total: [ 900, 10, 5 ],
   value: [ 12000, 800, 0 ]
}
Equivalence Partitioning Testing

Equivalence Partitioning also called as equivalence class partitioning. It is abbreviated as ECP. It is a software testing technique that divides the input test data of the application under test into each partition at least once of equivalent data from which test cases can be derived.
An advantage of this approach is it reduces the time required for performing testing of a software due to less number of test cases.
The Below example best describes the equivalence class Partitioning:
Assume that the application accepts an integer in the range 100 to 999
Valid Equivalence Class partition: 100 to 999 inclusive.
Non-valid Equivalence Class partitions: less than 100, more than 999, decimal numbers and alphabets/non-numeric characters.

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
Python Program to print the diamond shape

The looping features in python can be used to create many nicely formatted diagrams using various characters from the keyboard. One such shape is diamond shape which will involve multiple loops. This is because we have to print the character both vertically and horizontally. Also we have to take care of the shape gradually growing from top till middle and then gradually shrinking from middle till the bottom. For this reason, we will use two for loops each containing one more for loop inside it.
Below is the code for creating the diamond shape.
def Shape_of_Diamond(shape):
a = 0
for m in range(1, shape + 1):

for n in range(1, (shape - m) + 1):
print(end=" ")

while a != (2 * m - 1):
print("@", end="")
a = a + 1
a = 0

print()

s = 1
c = 1
for m in range(1, shape):

for n in range(1, s + 1):
print(end=" ")
s = s + 1

while c <= (2 * (shape - m) - 1):
print("@", end="")
c = c + 1
c= 1
print()

shape = 8
Shape_of_Diamond(shape)

Running the above code gives us the following result:
           @
          @@@
         @@@@@
        @@@@@@@
       @@@@@@@@@  
      @@@@@@@@@@@
     @@@@@@@@@@@@@
    @@@@@@@@@@@@@@@
     @@@@@@@@@@@@
     @@@@@@@@@@@
      @@@@@@@@@
       @@@@@@@
       @@@@@
        @@@
         @
java.time.LocalDate.of() Method Example

The java.time.LocalDate.of(int year, Month month, int dayOfMonth) method obtains an instance of LocalDate from a year, month and day.
Following is the declaration for java.time.LocalDate.of(int year, Month month, int dayOfMonth) method.
public static LocalDate of(int year, Month month, int dayOfMonth)

year − the year to represent, from MIN_YEAR to MAX_YEAR
year − the year to represent, from MIN_YEAR to MAX_YEAR
month − the month-of-year to represent
month − the month-of-year to represent
dayOfMonth − the day-of-month to represent, from 1 to 31
dayOfMonth − the day-of-month to represent, from 1 to 31
the local date, not null.
The following example shows the usage of java.time.LocalDate.of(int year, Month month, int dayOfMonth) method.
package com.tutorialspoint;

import java.time.LocalDate;
import java.time.Month;

public class LocalDateDemo {
   public static void main(String[] args) {
	  
      LocalDate date = LocalDate.of(2017,Month.FEBRUARY,3);
      System.out.println(date);  
   }
}
Let us compile and run the above program, this will produce the following result −
2017-02-03

 Print
 Add Notes
 Bookmark this page
move_to_element method - Action Chains in Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around move_to_element method on Action Chains in Python Selenium. move_to_element method is used to move the mouse to the middle of an element.Syntax –
move_to_element(to_element)
to_element: The WebElement to move to.
Example –
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")element = driver.find_element_by_name("passwd")
Now one can use move_to_element method as an Action chain as below –
move_to_element(to_element=element)

To demonstrate, move_to_element method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # get  element element = driver.find_element_by_link_text("Courses")  # create action chain objectaction = ActionChains(driver)  # perform the operationaction.move_to_element(element).click().perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Selecting rows in pandas DataFrame based on conditions
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
Optional of() method in Java with examples - GeeksforGeeks

30 Jul, 2019
The of() method of java.util.Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type.
Syntax:
public static <T> 
  Optional<T> of(T value)

Parameters: This method accepts value as parameter of type T to create an Optional instance with this value.
Return value: This method returns an instance of this Optional class with the specified value of the specified type.
Exception: This method throws NullPointerException if the specified value is null.
Below programs illustrate of() method:Program 1:
// Java program to demonstrate// Optional.of() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          // create a Optional        Optional<Integer> op            = Optional.of(9455);          // print value        System.out.println("Optional: "                           + op);    }}
Optional: Optional[9455]

Program 2:
// Java program to demonstrate// Optional.of() method  import java.util.*;  public class GFG {      public static void main(String[] args)    {          try {            // create a Optional            Optional<Integer> op                = Optional.of(null);              // print value            System.out.println("Optional: "                               + op);        }        catch (Exception e) {            System.out.println(e);        }    }}
java.lang.NullPointerException

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#of-T-
Java - util package
Java-Functions
Java-Optional
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
Public vs Protected in C++ with Examples

29 Oct, 2019
Public
All the class members declared under public will be available to everyone. The data members and member functions declared public can be accessed by other classes too. The public members of a class can be accessed from anywhere in the program using the direct member access operator (.) with the object of that class.
Example:
// C++ program to demonstrate public// access modifier  #include <iostream>using namespace std;  // class definitionclass Circle {public:    double radius;      double compute_area()    {        return 3.14 * radius * radius;    }};  // main functionint main(){    Circle obj;      // accessing public data member outside class    obj.radius = 5.5;      cout << "Radius is: " << obj.radius << "\n";    cout << "Area is: " << obj.compute_area();    return 0;}
Radius is: 5.5
Area is: 94.985

In the above program, the data member radius is public so we are allowed to access it outside the class.
Protected
Protected access modifier is similar to that of private access modifiers, the difference is that the class member declared as Protected are inaccessible outside the class but they can be accessed by any subclass(derived class) of that class.Example:
// C++ program to demonstrate// protected access modifier#include <bits/stdc++.h>using namespace std;  // base classclass Parent {    // protected data membersprotected:    int id_protected;};  // sub class or derived classclass Child : public Parent {  public:    void setId(int id)    {          // Child class is able to access the inherited        // protected data members of base class          id_protected = id;    }      void displayId()    {        cout << "id_protected is: " << id_protected << endl;    }};  // main functionint main(){      Child obj1;      // member function of the derived class can    // access the protected data members of the base class      obj1.setId(81);    obj1.displayId();    return 0;}
Difference between Public and Protected
access modifiers
C++ Programs
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Timestamp.year

08 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.year attribute return the year in which the date in the given Timestamp object lies.
Syntax : Timestamp.year
Parameters : None
Return : year
Example #1: Use Timestamp.year attribute to find the year in which the date present in the given Timestamp object lies.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,           hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.year attribute to find the year value of the date.
# return the yearts.year
Output :
As we can see in the output, the Timestamp.year attribute has returned 2011 indicating that the year value of the date in the give Timestamp object is 2011.
Example #2: Use Timestamp.year attribute to find the year in which the date present in the given Timestamp object lies.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009,  month = 5, day = 31,         hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.year attribute to find the year value of the date.
# return the yearts.year
Output :
As we can see in the output, the Timestamp.year attribute has returned 2009 indicating that the year value of the date in the give Timestamp object is 2009.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Meta Class in Models – Django

27 May, 2022
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source. Do also go through Django Models prior to moving ahead. 
Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It’s completely optional to add a Meta class to your model. In order to use model meta you have to add class Meta in your model as shown below as follows: 
class student(models.Model):
    class Meta:
        options........
Model Meta has a lot of options that you can give your model in its internal class meta
1. abstract
If abstract = True, this model will be an abstract  base class
Python3
class student(models.Model):  class Meta:      abstract = True
2. app_label
If a model is defined outside of applications in INSTALLED_APPS, it must declare which app  it belongs to:
Python3
class student(models.Model):  class Meta:      app_label = 'myapp' # add app name here
3. verbose_name
verbose_name is basically a human-readable name for your model
Python3
class student(models.Model):  class Meta:      verbose_name = "stu" # add verbose_name  here
4. ordering 
Ordering is basically used to change the order of your model fields.
Python3
class student(models.Model):  class Meta:      ordering = [-1]
Add ordering like this [-1] it changes the order in descending order
5. proxy
If we add proxy = True a model which subclasses another model will be treated as a proxy model
Python3
class Teacher(models.Model):  pass class Student(Teacher):  class Meta:      proxy = True
This is how can we make a  proxy model.
6. permissions 
Extra permissions to enter into the permissions table when creating this object. Add, change, delete and view permissions are automatically created for each model.
Python3
class student(models.Model):  class Meta:      permissions = []    
You can add extra permission inside the list.
7. db_table
We can overwrite the table name by using db_table in meta class.
Python3
class student(models.Model):  class Meta:      db_table = 'X'
This will change the table name to X.
8. get_latest_by
It returns the latest object in the table based on the given field, used for typically DateField, DateTimeField, or IntegerField.
Python3
class student(models.Model):  class Meta:      get_latest_by = "order_date"
Return the latest by ascending order_date.
isha307
Python Django
Python Framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
INSERT ON DUPLICATE KEY UPDATE in MySQL

23 Dec, 2020
INSERT ON DUPLICATE KEY UPDATE statement is available in MySQL as an extension to the INSERT statement. Whenever a new row is inserted into a table in case the row causes a duplicate entry in the UNIQUE index or PRIMARY KEY, MySQL will throw an error.
When the ON DUPLICATE KEY UPDATE option is defined in the INSERT statement, the existing rows are updated with the new values instead.
Syntax :
INSERT INTO table (column_names)
VALUES (values)
ON DUPLICATE KEY UPDATE
  col1 = val1,  
  col2 = val2 ;

Along with the INSERT statement, ON DUPLICATE KEY UPDATE statement defines a list of column & value assignments in case of duplicate.
How it works :The statement first attempts to insert a new row into the table. When a duplicate entry is their error occurs, MySQL will update the existing row with the value specified in the ON DUPLICATE KEY UPDATE clause.
Example –Let us create a table named ‘geek_demo’ as follows.
CREATE TABLE geek_demo
(
id INT AUTO_INCREMENT PRIMARY KEY, 
name VARCHAR(100) 
);

Inserting data into geek_demo :
INSERT INTO geek_demo (name)
VALUES('Neha'), ('Nisha'), ('Sara') ;

Reading data from table :
SELECT id, name
FROM geek_demo;
Output :
Now, one row will insert into the table.
INSERT INTO geek_demo(name) 
VALUES ('Sneha') 
ON DUPLICATE KEY UPDATE name = 'Sneha';

As there was no duplicate, MySQL inserts a new row into the table. The output of the above statement is similar to the output below statement as follows.
INSERT INTO geek_demo(name)
VALUES ('Sneha');

Reading data :
SELECT id, name
FROM geek_demo; 

Output :
Let us insert a row with a duplicate value in the id column as follows.
INSERT INTO geek_demo (id, name) 
VALUES (4, 'Mona')
ON DUPLICATE KEY UPDATE name = 'Mona';

Below is the output :
2 row(s) affected

Because a row with id 4 already exists in the geek_demo table, the statement updates the name from Sneha to Mona.Reading data :
SELECT id, name
FROM geek_demo;

Output :
almut77
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2021 | Set 2 | Question 42

23 May, 2021
Let S be the following schedule of operations of three transactions T1, T2 and T3 in a relational database system:
R2(Y),R1(X),R3(Z),R1(Y)W1(X),R2(Z),W2(Y),R3(X),W3(Z) 
Consider the statements P and Q below:
P: S is conflict-serializable.
Q: If T3 commits before T1 finishes, then S is recoverable.
Which one of the following choices is correct?(A) Both P and Q are true(B) P is true and Q is false(C) P is false and Q is true(D) Both P and Q are falseAnswer: (B)Explanation:
Hence, Statement P is conflict serializable.
Schedule S is recoverable, if Tj creating the dirty read by reading the written data by Ti and Tj commits after Ti commits.
T1 and T2 must be commit before T3 as T3 dirty reads the value at T1 and T2, so if T3 commits before T1 finishes, then S will not recoverable.
Hence Statement Q is false. 
Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2001 | Question 50
GATE | Gate IT 2005 | Question 52
GATE | GATE CS 2012 | Question 18
GATE | GATE-CS-2014-(Set-1) | Question 51
Standard Normal Distribution (SND) – Java Program

06 Feb, 2018
The standard normal distribution is a special case of the normal distribution. It occurs when a normal random variable has a mean of 0 and a standard deviation of 1. The normal random variable of a standard normal distribution is called a standard score or a z score.A conversion from Normally distributed to Standard Normally distributed value occurs via the formula,
Z = (X - u) / s
where:
Z = value on the standard normal distribution
X = value on the original distribution
u = mean of the original distribution
s = standard deviation of the original distribution

Code –
// Java code to demonstrate the naive method// of finding Z-value  import java.io.*;import java.util.*;  class SDN {    public static void main(String[] args)    {          // initialization of variables        double Z, X, s, u;        X = 26;        u = 50;        s = 10;          // master formula        Z = (X - u) / s;          // print the z-value        System.out.println("the Z-value obtained is: " + Z);    }}
Output –
the Z-value obtained is: -2.4

Generating a Random Standard Normal Function – Using nextGaussian() in Java :The nextGaussian() method is used to get the next random, Normally distributed double value with mean 0.0 and standard deviation 1.0.
Declaration :
public double nextGaussian()
Parameters :
NA
Return Value :
The method call returns the random, Normally distributed double value
with mean 0.0 and standard deviation 1.0.
Exception :
NA

The following example shows the usage of java.util.Random.nextGaussian():
Code –
// Java code to demonstrate the working// of nextGaussian()import java.util.*;  public class NextGaussian {      public static void main(String[] args)    {          // create random object        Random ran = new Random();          // generating integer        double nxt = ran.nextGaussian();          // Printing the random Number        System.out.println("The next Gaussian value generated is : " + nxt);    }}
Output –
The next Gaussian value generated is : -0.24283691098606316

Java
Java Programs
Mathematical
Mathematical
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Merge Range Characters in List

19 Feb, 2020
Sometimes, we require to merge some of the elements as single element in the list. This is usually with the cases with character to string conversion. This type of task is usually required in development domain to merge the names into one element. Let’s discuss certain ways in which this can be performed.
Method #1 : Using join() + List SlicingThe join function can be coupled with list slicing which can perform the task of joining each character in a range picked by the list slicing functionality.
# Python3 code to demonstrate # Merge Range Characters in List# using join() + list slicing  # initializing list test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']  # printing original listprint ("The original list is : " + str(test_list))  # initializing Range, i, ji, j = 3, 7  # using join() + list slicing# Merge Range Characters in Listtest_list[i : j] = [''.join(test_list[i : j])]  # printing result print ("The list after merging elements : " + str(test_list))
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

 
Method #2 : Using reduce() + lambda + list slicingThe task of joining each element in a range is performed by reduce function and lambda. reduce function performs the task for each element in the range which is defined by the lambda function. It works with Python2 only.
# Python code to demonstrate # Merge Range Characters in List# using reduce() + lambda + list slicing  # initializing list test_list = ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']  # printing original listprint ("The original list is : " + str(test_list))  # initializing strt, end strt, end = 3, 7  # using reduce() + lambda + list slicing# Merge Range Characters in Listtest_list[strt : end] = [reduce(lambda i, j: i + j, test_list[strt : end])]  # printing result print ("The list after merging elements : " + str(test_list))
The original list is : ['I', 'L', 'O', 'V', 'E', 'G', 'F', 'G']
The list after merging elements : ['I', 'L', 'O', 'VEGF', 'G']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.