code-rag-bench/online-tutorials huggingface dataset:
Why require_once() function is so bad to use in PHP ?

15 Nov, 2019
The require_once() function is an inbuilt function in PHP which is useful in case if we want to include a PHP file in another one i.e. when we need to include a file more than once in PHP script. It is used to check if the file is included more than once or not as it ignores all the inclusions while running the script if the file is already included.
Syntax:
require_once('File name with file path');
Parameters: This function accepts a single parameter ‘file name with path’. This is the file that we want to include in our PHP script. It is a string type parameter.
Return Value: If the called file is found and further if the file is already included, then the function would return the Boolean True and if the file is not included, then the function would include the file and return True. But if the called file is not found, then a fatal error will arise and no output will display and the execution halts returning Boolean False.
Below programs illustrate the require_once() function in PHP:
File Name: my_file.inc.php
Program:
<?php   // Content of the PHP fileecho "Welcome To GeeksforGeeks"; ?>
The above file my_file.inc.php included twice with require_once() function in the following file index.php. But from the output, you will get the second instance of inclusion ignored since require_once() function ignores all the similar inclusions after the first one.
File Name: index.php
    <?php   // Include the file  require_once('my_file.inc.php'); require_once('my_file.inc.php');   ?> 
Output:
Welcome To GeeksforGeeks
Why require_once() function is so bad to use?
The require_once() function puts a lot of load on the server while including all the files.
The functionality of require_once() function works inappropriately when used inside repetitive function when storing variables.
File Name: my_file.phpExample:
    <?php   // Content of the file$var = 'GFG';   ?>
File Name: check.php
<?php  function func() {    require_once('my_file.php');    return $var;}  for($i = 1; $i <= 3; $i++) {    echo func() . "<br>";}  ?>
Output:
GFG
By replacing the require_once() function with the require() function in the above example, we can make sure the variable $var is available at each function call.
File Name: check2.php
<?php  function func() {    require('my_file.php');    return $var;}  for($i = 1; $i <= 3; $i++) {    echo func() . "<br>";}  ?>
Output:
GFG
GFG
GFG

The require_once() function is slower in comparison to require() or include() function as it checks if the file is already included or not every time the script calls the function.
PHP-basics
Picked
PHP
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | EQUI Join and NON EQUI JOIN

08 Sep, 2020
Types of SQL Joins are explained in left, right, and full join and SQL | Join (Cartesian Join & Self Join). And Remaining EQUI Join and NON-EQUI will discuss in this article. Let’s discuss one by one.
 SQL JOINS :
EQUI Join
NON-EQUI Join
Example –
Let’s Consider the two tables given below.
Table name — Student
In this table, you have I’d, name, class and city are the fields.  
Select * from Student;
Table name — Record
In this table, you have I’d, class and city are the fields.  
Select * from Record;
1. EQUI JOIN :
EQUI JOIN creates a JOIN for equality or matching column(s) values of the relative tables. EQUI JOIN also create JOIN by using JOIN with ON and then providing the names of the columns with their relative tables to check equality using equal sign (=).
Syntax :
SELECT column_list  
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;  

Example –
SELECT student.name, student.id, record.class, record.city
FROM student, record
WHERE student.city = record.city;
Or 
Syntax :
SELECT column_list
FROM table1  
JOIN table2
[ON (join_condition)]

Example –
SELECT student.name, student.id, record.class, record.city
FROM student
JOIN record
ON student.city = record.city;
Output :
2. NON EQUI JOIN :
NON EQUI JOIN performs a JOIN using comparison operator other than equal(=) sign like >, <, >=, <= with conditions.
Syntax:
SELECT *  
FROM table_name1, table_name2  
WHERE table_name1.column [> |  < |  >= | <= ] table_name2.column;


Example –
SELECT student.name, record.id, record.city
FROM student, record
WHERE Student.id < Record.id ;
Output :
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
Difference between DELETE, DROP and TRUNCATE
CTE in SQL
SQL | Views
SQL Interview Questions
Difference between DELETE and TRUNCATE
Window functions in SQL
SQL | DDL, DML, TCL and DCL
Difference between DDL and DML in DBMS
How to Update Multiple Columns in Single Update Statement in SQL?
p5.js | splitTokens() function

10 Feb, 2021
The splitTokens() function in p5.js is used to break the input string into pieces of data using a delimiter. This delimiter could be any string or symbol used between each piece of the input string. Syntax:  
splitTokens( string, delimiter )
Parameters: This function accepts two parameters as mentioned above and described below:  
String: This is the input string which are to be splitted.
Delimiter: This is any string or symbol used to separate the data of the input string.
Return Value: It returns the splitted data of the input string separated by commas (, ).Below programs illustrate the splitTokens() function in p5.js:Example 1: This example uses splitTokens() function to break the input string into pieces of data using a delimiter.  
javascript
function setup() {      // Create Canvas    createCanvas(500, 60);}function draw() {          // Set the background color    background(220);        // Initializing the Strings    let String = 'GeeksforGeeks/Geeks/Geek/gfg';          // Calling to splitTokens() function    let A = splitTokens(String, '/');         // Set the size of text    textSize(16);          // Set the text color    fill(color('red'));        // Getting splitted string    text("Splitted string is: " + A, 50, 30); }
Output:  
Example 2: This example uses splitTokens() function to break the input string into pieces of data using a delimiter.  
javascript
function setup() {      // Create Canvas    createCanvas(450, 60);}function draw() {          // Set the background color    background(220);        // Initializing the Strings    let String = '0&11&222&3333';          // Calling to splitTokens() function.    let A = splitTokens(String, '&');         // Set the size of text    textSize(16);          // Set the text color    fill(color('red'));        // Getting splitted string    text("Splitted string is: " + A, 50, 30); }
Output:  
Note: The difference between splitTokens() and split() is that splitTokens() function splits using a range of characters while split() function uses a specific character or sequence. Reference: https://p5js.org/reference/#/p5/splitTokens 
arorakashish0911
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | hash_hmac() Function

29 Oct, 2018
The hash_hmac() function is an inbuilt function in PHP which is used to generate the keyed hash value using the HMAC method.
Syntax:
string hash_hmac( $algo, $msg, $key, $raw_opt )
Parameters: This function accepts four parameters as mention above and describe below.
$algo: It is the required parameter which is used to specify the selected hashing algorithm Ex. “md5”, “sha256”, “sha1”.
$msg: This parameter is used to hold the message to be hashed.
$key: This parameter is used to specify the shared secret key used for generating the HMAC variant of the message digest.
$raw_opt: This parameter is used to hold the Boolean value. If it set to True then it returns raw binary data and if it set to False then it returns output lowercase hexits.
Return Value: This function returns a string containing the calculated message digest as lowercase hexits.
Below programs illustrate the hash_hmac() function in PHP:Program 1:
<?php  // PHP program to illustrate// the hash_hmac functionecho hash_hmac('md5', 'GeeksforGeeks A Computer Science Portal',                                'GFG_DATA');?>
65f3fc3c9085077f44ade6ce2d21eba4

Program 2:
<?php  // PHP program to illustrate// the hash_hmac functionecho hash_hmac('md5', 'GeeksforGeeks A Computer Science Portal',                                'GFG_DATA', false). "\n";echo hash_hmac('md5', 'GeeksforGeeks A Computer Science Portal',                                'GFG_DATA', true);                                ?>
65f3fc3c9085077f44ade6ce2d21eba4
eóü<?u0007D­æÎ-!ë¤

Reference: http://php.net/manual/en/function.hash-hmac.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between HTTP GET and POST Methods
How to fetch data from localserver database and display on HTML table using PHP ?
How to convert array to string in PHP ?
PHP Cookies
How to get parameters from a URL string in PHP?
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
Python program to print the elements of an array in reverse order

When it is required to print the elements of an array in reverse order, the list can be iterated over from the end.
Below is a demonstration of the same −
 Live Demo
my_list = [21, 32, 43, 54, 75]
print("The list is : ")
for i in range(0, len(my_list)):
   print(my_list[i])
print("The list after reversal is : ")
for i in range(len(my_list)-1, -1, -1):
   print(my_list[i])
The list is :
21
32
43
54
75
The list after reversal is :
75
54
43
32
21
A list is defined, and is displayed on the console.
A list is defined, and is displayed on the console.
The list is iterated over, and displayed.
The list is iterated over, and displayed.
It is reversed by iterating it from the last element.
It is reversed by iterating it from the last element.
Every element is displayed on the console.
Every element is displayed on the console.
Python Dictionary Methods - GeeksforGeeks

04 Aug, 2021
Python Dictionary is like a map that is used to store data in the form of a key:value pair. Python provides various in-built functions to deal with dictionaries. In this article, we will see a list of all the functions provided by the Python to work with dictionaries.
Below functions can be used to access dictionary items (both key and value).
get(): This function returns the value for the given key
keys(): This function returns a view object that displays a list of all the keys in the dictionary in order of insertion
values(): This function returns a list of all the values available in a given dictionary
items(): This function returns the list with all dictionary keys with values
Example: Accessing Dictionary Items.
Python3
# Python program to demonstrate working# of dictionary copydic = {1:'geeks', 2:'for', 3:'geeks'}print('original: ', dic) # Accessing value for keyprint(dic.get(1)) # Accessing keys for the dictionaryprint(dic.keys()) # Accessing keys for the dictionaryprint(dic.values()) # Printing all the items of the Dictionaryprint(dic.items())
original:  {1: 'geeks', 2: 'for', 3: 'geeks'}
geeks
dict_keys([1, 2, 3])
dict_values(['geeks', 'for', 'geeks'])
dict_items([(1, 'geeks'), (2, 'for'), (3, 'geeks')])
 
Note: For more information on Python Dictionary refer to Python Dictionary Tutorial.
 
surinderdawra388
julia-dictionary-methods
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Read a file line by line in Python
Taking input in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
How to send button value to PHP backend via POST using ajax ? - GeeksforGeeks

24 May, 2021
The purpose of this article is to send the value of the button to PHP back-end using AJAX in an HTML document.
Approach: Create a button in HTML document and assign an Id to it. In JavaScript file add an event listener to button i.e click. Then the request is made to PHP file using jQuery Ajax.
HTML code:
HTML
<!-- HTML Code --><!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">     <!-- JavaScript file -->    <script src="script.js"></script>     <!-- jQuery Ajax CDN -->    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script></head> <body>     <!-- Button -->    <button id="btn" value="hello world">        Click On me!    </button></body> </html>
JavaScript code: The following is the code for “script.js” file.
Javascript
// Button DOMlet btn = document.getElementById("btn"); // Adding event listener to buttonbtn.addEventListener("click", () => {     // Fetching Button value    let btnValue = btn.value;     // jQuery Ajax Post Request    $.post('action.php', {        btnValue: btnValue    }, (response) => {        // response from PHP back-end        console.log(response);    });});
PHP code: The following is the code for “action.php” file.
PHP
<?php     // Checking, if post value is    // set by user or not    if(isset($_POST['btnValue']))    {        // Getting the value of button        // in $btnValue variable        $btnValue = $_POST['btnValue'];                // Sending Response        echo "Success";    }?>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
gabaa406
HTML-Misc
HTML5
JavaScript-Misc
PHP-Misc
Picked
Technical Scripter 2020
HTML
JavaScript
JQuery
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
HTML | <img> align Attribute
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
MergeSort - GeeksforGeeks

30 Jul, 2021
MergeSort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merg() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes ... More on Merge Sort 
Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above.
Time complexity of merge sort is Θ(nLogn)

c*64Log64 is 30
c*64*6 is 30
c is 5/64

For time 6 minutes

5/64*nLogn = 6*60

nLogn = 72*64 = 512 * 9

n = 512. 
 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
C Program For Finding Length Of A Linked List
How to calculate MOVING AVERAGE in a Pandas DataFrame?
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
How to Fix: KeyError in Pandas
C Program to read contents of Whole File
How to Append Pandas DataFrame to Existing CSV File?
How to Replace Values in a List in Python?
How to add Skeleton Loading in NextJS ? - GeeksforGeeks

15 Dec, 2021
In this article, we are going to learn how we can add Skeleton Loading in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac.
Approach: To add our skeleton loading we are going to use the react-loading-skeleton package. The react-loading-skeleton package helps us to add a skeleton loading anywhere in our app. So first, we will install the react-loading-skeleton package and then we will add a loading screen on our homepage.
Create NextJS Application: You can create a new NextJs project using the below command:
npx create-next-app gfg
 
Install the required package: Now we will install the react-loading-skeleton package using the below command:
npm i react-loading-skeleton
Project Structure: It will look like this.
Adding the Skeleton Loading: After installing the package we can easily add loading to our app. For this example, we are going to add a skeleton loading to our homepage.
index.js
import React, { useState } from 'react';import Skeleton from 'react-loading-skeleton'import 'react-loading-skeleton/dist/skeleton.css'  export default function SkeletonLoading(){  const [checked, setChecked] = React.useState(false);    const handleChange = () => {    setChecked(!checked);  };  return (    <div>      <label>        <input          type="checkbox"          checked={checked}          onChange={handleChange}        />        Loading      </label>      <p>{checked?<Skeleton />:            <h2>           NextJs Skeleton Loading - GeeksforGeeks           </h2>}</p>      </div>  )}
Explanation: In the above example first, we are importing our Skeleton component from the installed package. After that, we are using the Skeleton component inside a new function. We are also using react hook to check the current value in the checkbox. If the checkbox is checked then we are showing our loading screen.
Steps to run the application: Run the below command in the terminal to run the app.
npm run dev
Nextjs
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to add new colors to tailwind-css and keep the originals ones ?

18 Jun, 2021
You can easily add new colors to Tailwind CSS and keep the originals ones using customization configuration. You can configure your colors under the colors key in the theme section of your tailwind.config.js file. 
Follow the below step to add the tailwind.config.js file in your folder.
Step 1: Run the below code to your folder’s terminal. This will create a package.json file.
npm init 
 
Step 2: Copy and paste the below code to your folder’s terminal. This will create the required node module for tailwind.
npm install tailwindcss@latest postcss@latest autoprefixer@latest
Step 3: Create a public folder and add index.html, style.css, and tailwind.css inside the public folder.
Step 4: Add the below code in the tailwind.css file. Using this file you can customize your tailwind CSS along with the default style. Tailwind will swap these directives out at build-time with all the styles it generates based on your configured design system.
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 5: Open package.json file and under scripts section, add the below code
“scripts”: {“build:css”: “tailwind build public/tailwind.css -o public/style.css”},
Step 6: Run the below code in the terminal. This will populate your style.css file with predefined Tailwind CSS code.
npm run build:css
Step 7: Finally, run the below code. This will generate a Tailwind config file for your project using the Tailwind CLI utility included at the time of installation of the tailwindcss npm package.
npx tailwindcss init
Syntax:
colors: {
    // each color has a specific name. you can replace 
    // 'custom-color' with the name you like
    // replace '#66bbfa' with the colors you like.
    'custom-color': '#66bbfa'
}
Add the below code to your tailwind.config.js file, and now you can customize your color by adding your own color code.
tailwind.config.js
const colors = require('tailwindcss/colors')  module.exports = {  mode: 'jit',  theme: {    extend: {      colors: {      // Configure your color palette here       'custom-green':'#66bb6a',      },    },  },  variants: {},  plugins: [],}
Example :
HTML
<!DOCTYPE html><html><body class="text-center mx-4 space-y-2">    <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>    <b>Tailwind CSS Customize colors</b>          <div class="h-60 w-25 m-5 bg-custom-green">        GEEKSFORGeeks    </div></body>  </html>
Output:
Tailwind CSS-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert a scale bar in a map in Matplotlib?

To insert a scale bar in a map in matplotlib, we can use AnchoredBar() class to instantiate the scalebar object.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create random data using numpy.
Create random data using numpy.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Use imshow() method to display data as an image, i.e., on a 2D regular raster.
Get the current axis using gca() method.
Get the current axis using gca() method.
Draw a horizontal scale bar with a center-aligned label underneath.
Draw a horizontal scale bar with a center-aligned label underneath.
Add a scalebar artist to the current axis.
Add a scalebar artist to the current axis.
Turn off the axes.
Turn off the axes.
To display the figure, use show() mthod.
To display the figure, use show() mthod.
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
import numpy as np

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

data = np.random.rand(5, 5)

img = plt.imshow(data, cmap="YlGnBu")
ax = plt.gca()
scalebar = AnchoredSizeBar(ax.transData, 1, "1 Meter", 9)

ax.add_artist(scalebar)
ax.axis('off')
plt.show()
Separators in Java

25 Sep, 2021
Be it a programmer who is unaware of this concept but is indulging in every program. Separators help us defining the structure of a program. In Java, There are few characters used as separators. The most commonly used separator in java is a semicolon(;). Let us explore more with the help of an illustration with the “Hello World” program to put more emphasis on separators.
Illustration: Hello World
Java
// Java Program to Illustrate Separators in Java // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Print statement        System.out.println("Hello World");    }}
Observations drawn are as follows:
In line 3, ‘{‘ is used to define starting of block class GFG
In line 6, ‘{‘ is used to define starting of block main method
In line 10, ‘;’ is used to terminate the sentence
In line 11, ‘}’ is used to define the ending of the block main method
In line 12, ‘}’ is used to define the ending of block class GFG
These separators are pictorially depicted below as follows: 
This article is contributed by Swati Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
swatijha0829
java-basics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
How to select text input fields using CSS selector ?

08 Mar, 2019
CSS attribute selector is used to targeting an input text fields. The input text fields of type ‘text’ can be targeting by using input[type=text].
Note: It is specified that the default attribute values may not always be selectable with attribute selectors, one could try to cover other cases of markup for which text inputs are rendered.
input:not([type]): It is used when type attribute is not present in the markup.
input[type = “”]: It is used when type attribute is present, but empty.
input[type = text]: It is used when type attribute is explicitly defined as ‘text’.
Example 1: This example selects the input text fields and use some CSS property.
<!DOCTYPE html><html>  <head>    <style>        input[type="text"] {            width: 400PX;            display: block;            background:lightgreen;            color:black;             text-align:justiy;             font-size: 150%;        }                  form {            display:table-cell;             width:50%;             padding:10px;         }    </style></head>  <body>    <form name="input" action="" method="get">              Bestplatform :                <input type="text" name="Name"                         value="GfG" size="20">                  Fullform :                <input type="text" name="Name"                     value="GeeksforGeeks" size="20">    </form></body>  </html>                    
Output:
Example 2: This example selects the input text fields and use some CSS property.
<!DOCTYPE html><html>  <head>          <!-- CSS style to select type attribute -->    <style>        input[type="text"] {            width: 400PX;            display: block;            background:green;            color:white;             text-align:justiy;             font-size: 150%;        }                  form {            display:table-cell;             width:50%;             padding:10px;         }    </style></head>  <body>    <form name="input" action="" method="get">          USER : <input type="text" name="Name"                 value="GeeksforGeeks" size="20">          PASSWORD : <input type="text" name="Name"                 value="geeksforgeeks" size="20">          CATEGORY : <input type="text" name="Name"                 value="Studying platform" size="20">    </form></body>  </html>                    
Output:
CSS-Misc
CSS-Selectors
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Output of Java Program | Set 4

27 Sep, 2018
Predict the output of following Java Programs:
Question 1
// file name: Main.java  class Base {    protected void foo() {}} class Derived extends Base {    void foo() {}} public class Main {    public static void main(String args[]) {        Derived d = new Derived();        d.foo();    }}
Output: Compiler Errorfoo() is protected in Base and default in Derived. Default access is more restrictive. When a derived class overrides a base class function, more restrictive access can’t be given to the overridden function. If we make foo() public, then the program works fine without any error. The behavior in C++ is different. C++ allows to give more restrictive access to derived class methods.
Question 2
// file name: Main.java  class Complex {    private double re, im;        public String toString() {        return "(" + re + " + " + im + "i)";    }    Complex(Complex c) {        re = c.re;        im = c.im;    }}  public class Main {    public static void main(String[] args) {        Complex c1 = new Complex();        Complex c2 = new Complex(c1);        System.out.println(c2);    }}
Output: Compiler Error in line “Complex c1 = new Complex();”In Java, if we write our own copy constructor or parameterized constructor, then compiler doesn’t create the default constructor. This behavior is same as C++.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Java-Output
Output of Java Program
Java
Program Output
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Arrow operator -> in C/C++ with Examples
Output of C Programs | Set 1
Output of Java Program | Set 1
delete keyword in C++
Output of C++ programs | Set 50
Python list() Function

11 Nov, 2021
Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object you can iterate over. Some examples of iterables are tuples, strings, and lists.
Syntax:
list(iterable)
Parameter:
iterable:  an object that could be a sequence (string, tuples) or collection (set, dictionary) or any iterator object.
Note: If we don’t pass any parameter then the list() function will return a list with zero elements (empty list).
Lets see some examples for better understanding.
Python
# initializing a stringstring = "ABCDEF" # using list() function to create a listlist1 = list(string) # printing list1print(list1)
Output:
['A', 'B', 'C', 'D', 'E', 'F']
Python
# initializing a tupletuple1 = ('A', 'B', 'C', 'D', 'E') # using list() function to create a listlist1 = list(tuple1) # printing list1print(list1)
Output:
['A', 'B', 'C', 'D', 'E']
Python
# initializing a setset1 = {'A', 'B', 'C', 'D', 'E'}  # initializing a dictionarydictionary = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}  # using list() to create a listlist1 = list(set1)list2 = list(dictionary) # printingprint(list1)print(list2)
Output:
['C', 'E', 'D', 'B', 'A']
['A', 'B', 'C', 'D', 'E']
We can also use list() function while taking input from user to directly take input in form of a list.
Python
# Taking input from user as listlist1 = list(input("Please Enter List Elements: ")) # printingprint(list1)
Output:
Please Enter List Elements: 12345
['1', '2', '3', '4', '5']
sweetyty
Picked
Python-Functions
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
LocalDate withDayOfMonth() method in Java with Examples

07 Dec, 2018
The withDayOfMonth() method of LocalDate class in Java returns a copy of this LocalDate with the day-of-month altered.
Syntax:
public LocalDate withDayOfMonth(int dayOfMonth)
Parameter: This method accepts a mandatory parameter dayOfMonth whicthe day-of-month to set in the result, from 1 to 28-31.
Returns: The function returns a LocalDate based on this date with the requested day, not null.
Exceptions: The function throws a DateTimeException when the day of the month value is invalid.
Below programs illustrate the LocalDate.withDayOfMonth() method:
Program 1:
// Program to illustrate the withDayOfMonth() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {          // Parses the date        LocalDate dt1 = LocalDate.parse("2018-12-07");        LocalDate result = dt1.withDayOfMonth(01);          // Prints the date with year        System.out.println("The date with day of the month is: " + result);    }}
The date with day of the month is: 2018-12-01

Program 2:
// Program to illustrate the withDayOfMonth() method// Exceptionsimport java.util.*;import java.time.*;import java.time.temporal.ChronoField;  public class GfG {    public static void main(String[] args)    {          try {            // Parses the date            LocalDate dt1 = LocalDate.parse("2018-12-07");            LocalDate result = dt1.withDayOfMonth(35);              // Prints the date with year            System.out.println("The date with day of the month is: " + result);        }        catch (Exception e) {            System.out.println(e);        }    }}
java.time.DateTimeException: Invalid value for DayOfMonth (valid values 1 - 28/31): 35

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#withDayOfMonth(int)
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
How to make Triangle in Python Turtle using onscreenclick?

21 Jun, 2022
“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Turtle is also Known as Logo Programming language which commands for movement and drawing produced line or vector graphics, either on screen or with a small robot termed a turtle.
Turtle(): This Method is used to make object. 
onscreenclick(functionname,1):  This turtle function which sends the current coordinate to function which further utilise to form triangle, 1 is for left click and 3 is for Right click 
speed(): This is used to increase or decrease the speed of turtle pointer. 
listen(): This allows the server to listen to incoming connections. 
done(): This is used to hold the screen.   
penup(): This is built in function in turtle library to draw out the line. 
pendown(): This is built in function in turtle library to draw in the line. 
forward(): This is built in function in turtle library to move turtle forward direction.it takes pixel unit as an argument 
left(): This is built in function in turtle library to turn turtle left direction.it takes angle in degree as an argument 
Python3
import turtle  # Screen() method to get screenwn=turtle.Screen()  # creating tess objecttess=turtle.Turtle()   def triangle(x,y):       # it is used to draw out the pen    tess.penup()         # it is used to move cursor at x    # and y position    tess.goto(x,y)         # it is used to draw in the pen    tess.pendown()    for i in range(3):                 # move cursor 100 unit        # digit forward        tess.forward(100)                 # turn cursor 120 degree left        tess.left(120)                 # Again,move cursor 100 unit        # digit forward        tess.forward(100)         # special built in function to send current# position of cursor to triangleturtle.onscreenclick(triangle,1) turtle.listen() # hold the screenturtle.done()
Output :
As we can see cursor forms triangle where we can
 
varshagumber28
sooda367
simmytarika5
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Item-to-Item Based Collaborative Filtering

16 Jul, 2020
Collaborative Filtering is a technique or a method to predict a user’s taste and find the items that a user might prefer on the basis of information collected from various other users having similar tastes or preferences. It takes into consideration the basic fact that if person X and person Y have a certain reaction for some items then they might have the same opinion for other items too.
The two most popular forms of collaborative filtering are:
User Based: Here, we look for the users who have rated various items in the same way and then find the rating of the missing item with the help of these users.
Item Based: Here, we explore the relationship between the pair of items (the user who bought Y, also bought Z). We find the missing rating with the help of the ratings given to the other items by the user.
Let’s talk about Item-Based Collaborative Filtering in detail. It was first invented and used by Amazon in 1998. Rather than matching the user to similar customers, item-to-item collaborative filtering matches each of the user’s purchased and rated items to similar items, then combines those similar items into a recommendation list. Now, let us discuss how it works.
Item to Item Similarity: The very first step is to build the model by finding similarity between all the item pairs. The similarity between item pairs can be found in different ways. One of the most common methods is to use cosine similarity.
Formula for Cosine Similarity:
Step 1: Finding similarities of all the item pairs.
Form the item pairs. For example in this example the item pairs are (Item_1, Item_2), (Item_1, Item_3), and (Item_2, Item_3). Select each item to pair one by one. After this, we find all the users who have rated for both the items in the item pair. Form a vector for each item and calculate the similarity between the two items using the cosine formula stated above.
Sim(Item1, Item2)
In the table, we can see only User_1 and User_2 have rated for both items 1 and 2. 
Thus, let I1 be vector for Item_1 and I2 be for Item_2. Then,
I1 = 5U2 +  3U3 and,
I2 = 2U2 +  3U3


Sim(Item2, Item3)
In the table we can see only User_3 and User_4 have rated for both the items 1 and 2. 
Thus, let I2 be vector for Item_2 and I3 be for Item_3. Then,
I2 = 3U3 +  2U4 and,
I3 = 1U3 +  2U4



Sim(Item1, Item3)
In the table we can see only User_1 and User_3 have rated for both the items 1 and 2. 
Thus, let I1 be vector for Item_1 and I3 be for Item_3. Then,
I1 = 2U1 +  3U3 and,
I3 = 3U1 +  1U3


Now, in this step we calculate the ratings that are missing in the table.
Rating of Item_2 for User_1


Rating of Item_3 for User_2


Rating of Item_1 for User_4


References:
https://en.wikipedia.org/wiki/Collaborative_filtering
https://www.cs.umd.edu/~samir/498/Amazon-Recommendations.pdf
data mining
data-science
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas MultiIndex.reorder_levels()

24 Dec, 2018
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 MultiIndex.reorder_levels() function is used to rearrange levels using input order. It may not drop or duplicate levels. The function take list as an input which contains the desired order of the levels of the MultiIndex.
Syntax: MultiIndex.reorder_levels(order)
Parameters :order : list containing the order of levels
Returns : A new MultiIndex
Example #1: Use MultiIndex.reorder_levels() function to reorder the levels of the MultiIndex.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Networking', 'Cryptography',                                      'Anthropology', 'Science'],                                              [88, 84, 98, 95]])  # Print the MultiIndexprint(midx)
Output :
Now let’s reorder the level of the MultiIndex.
# reorder the levels such that# 1st level appears before the 0thmidx.reorder_levels([1, 0])
Output :As we can see in the output, the function has returned a new MultiIndex having the levels set in the passed order. Example #2: Use MultiIndex.reorder_levels() function to reorder the levels of the MultiIndex.
# importing pandas as pdimport pandas as pd  # Create the MultiIndexmidx = pd.MultiIndex.from_arrays([['Beagle', 'Sephard', 'Labrador', 'Retriever'],                                        [8, 4, 11, 3], ['A1', 'B1', 'A2', 'C1']])  # Print the MultiIndexprint(midx)
Output :
Now let’s reorder the levels of the MultiIndex.
# reorder the levelsmidx.reorder_levels([0, 2, 1])
Output :As we can see in the output, the function has returned a new MultiIndex having the levels set in the passed order.
Python pandas-multiIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Mongoose | remove() Function

20 May, 2020
The remove() function is used to remove the documents from the database according to the condition.
Installation of mongoose module:
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file, for example index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose');  // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {    name: { type: String },    age: { type: Number }});  User.remove({age:{$gte:30}}, function (err, result) {    if (err){        console.log(err)    }else{        console.log("Result :", result)     }});
Steps to run the program:
The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see the database as shown below:
The project structure will look like this:
Make sure you have installed mongoose module using following command:npm install mongoose
npm install mongoose
Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:
Run index.js file using below command:node index.js
node index.js
After the function is executed, You can see the database as shown below:
So this is how you can use the mongoose remove() function which removes the documents from the database according to the condition.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
MongoDB - Check the existence of the fields in the specified collection
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
pwnedOrNot – OSINT Tool to Find Passwords for Compromised Email Addresses

28 Jul, 2021
pwnedOrNot is an OSINT tool written in Python which checks the email account that has been compromised in a data breach and finds the password of the compromised account.
Name of Breach
Domain Name
Date of Breach
Fabrication status
Verification Status
Retirement status
Spam Status
First clone the tool from the GitHub repository.
git clone https://github.com/thewhiteh4t/pwnedOrNot.git
Change directory.
cd pwnedOrNot
Install requests using pip command.
pip3 install requests
pip3 cfscrape
Fig 1: Cloning Tool from GitHub repo.
Run the tool using the command,
python3 pwnedornot.py
python3 pwnedornot.py -h (To display optional arguments)
Fig 2: pwnedornot tool.
To check if a domain was breached or not.
www.google.com
Fig 3: Domain not breached.
Another example with yahoo.
Fig 4: Domain breached.
Output: Breached on 2012-07-11 (Email address and passwords were compromised in that breach)
To get a list of all pwned domains, use -l flag:
python3 pwnedornot.py -l
Fig 5: List of pwned domains.
Output: pwnedornot found 552 breached domains including big market players like zomato, yahoo.
To check if an email was compromised or not, use -e flag.
python3 pwnedornot.py -e jeyzetaservices@protonmail.com
Fig 6: Email address not breached.
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.