code-rag-bench/online-tutorials huggingface dataset:
Permutation and Combination in Java

Permutation and Combination are a part of Combinatorics. Permutation is the different arrangements that a set of elements can make if the elements are taken one at a time, some at a time or all at a time. Combination is is the different ways of selecting elements if the elements are taken one at a time, some at a time or all at a time.
An example of this is given as follows −
Permutation = factorial(n) / factorial(n-r);
Combination = factorial(n) / (factorial(r) * factorial(n-r));
n = 5
r = 3
Permutation = 60
Combination = 10
A program that demonstrates this is given as follows −
 Live Demo
public class Example {
   static int factorial(int n) {
      int fact = 1;
      int i = 1;
      while(i <= n) {
         fact *= i;
         i++;
      }
      return fact;
   }
   public static void main(String args[]) {
      int n = 7, r = 3, comb, per;
      per = factorial(n) / factorial(n-r);
      System.out.println("Permutation: " + per);
      comb = factorial(n) / (factorial(r) * factorial(n-r));
      System.out.println("Combination: " + comb);
   }
}
The output of the above program is as follows −
Permutation: 210
Combination: 35
Now let us understand the above program.
The function factorial finds the factorial of the number n using a while loop. Then it returns fact. The code snippet that demonstrates this is given as follows −
static int factorial(int n) {
   int fact = 1;
   int i = 1;
   while(i <= n) {
      fact *= i;
      i++;
   }
   return fact;
}
In the function main(), the permutation and combination of n and r are found using their respective formulas. Then the results are displayed. The code snippet that demonstrates this is given as follows −
public static void main(String args[]) {
   int n = 7, r = 3, comb, per;
   per = factorial(n) / factorial(n-r);
   System.out.println("Permutation: " + per);
   comb = factorial(n) / (factorial(r) * factorial(n-r));
   System.out.println("Combination: " + comb);
}
Program to check if a String in Java contains only whitespaces

22 Jan, 2020
Given a string str, the task is to check if this string contains only whitespaces or some text, in Java.
Examples:
Input: str = "              " 
Output: True

Input: str = "GFG"
Output: False

Approach:
Get the String to be checked in str
We can use the trim() method of String class to remove the leading whitespaces in the string.Syntax:str.trim()

str.trim()

Then we can use the isEmpty() method of String class to check if the resultant string is empty or not. If the string contained only whitespaces, then this method will return trueSyntax:str.isEmpty()

str.isEmpty()

Combine the use of both methods using Method Chaining.str.trim().isEmpty();

str.trim().isEmpty();

Print true if the above condition is true. Else print false.
Below is the implementation of the above approach:
// Java Program to check if// the String is not all whitespaces  class GFG {      // Function to check if the String is all whitespaces    public static boolean isStringAllWhiteSpace(String str)    {          // Remove the leading whitespaces using trim()        // and then check if this string is empty        if (str.trim().isEmpty())            return true;        else            return false;    }      // Driver code    public static void main(String[] args)    {        String str1 = "GeeksforGeeks";        String str2 = "              ";          System.out.println("Is string [" + str1                           + "] only whitespaces? "                           + isStringAllWhiteSpace(str1));        System.out.println("Is string [" + str2                           + "] only whitespaces? "                           + isStringAllWhiteSpace(str2));    }}
Is string [GeeksforGeeks] only whitespaces? false
Is string [              ] only whitespaces? true

Java-String-Programs
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | fabs() vs abs()

09 Aug, 2021
Both the abs() and the fabs() function is used to find the absolute value of a number, i.e., remove the negative sign of a number.  
Syntax of abs(): 
abs(number)
Syntax of fabs():
math.fabs(number)
Both will return the absolute value of a number.
The difference is that math.fabs(number) will always return a floating-point number even if the argument is an integer, whereas abs() will return a floating-point or an integer depending upon the argument.
In case the argument is a complex number, abs() will return the magnitude part whereas fabs() will return an error.To use the fabs() function we need to import the library “math” while the abs() function comes with the standard library of Python.
Python3
# Python code to demonstrate working# of fabs() and abs()import math ################################## When the argument is an integer##################################number = -10 # abs() will return an integer as# the argument is an integerprint(abs(number)) # fabs() will return a floating point numberprint(math.fabs(number)) ############################################ When the input is a floating point number############################################number = -12.08 # abs() will return an floating point number# as the argument is a floating point numberprint(abs(number)) # fabs() will return a floating point numberprint(math.fabs(number)) ##################################### When the input is a complex number#####################################number = complex(3, 4) # abs() will return the magnitudeprint(abs(number)) # fabs() will return an error# print(math.fabs(number))
Output: 
10
10.0
12.08
12.08
5.0
nidhi_biet
sheetal18june
Python-Built-in-functions
Python-Library
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
SQL Natural Join - GeeksforGeeks

13 Apr, 2021
In this article, we will discuss the overview of SQL Natural Join and then mainly focus to implement query with the help of examples. Let’s discuss it one by one.
Overview :Natural join is an SQL join operation that creates join on the base of the common columns in the tables. To perform natural join there must be one common attribute(Column) between two tables. Natural join will retrieve from multiple relations. It works in three steps.
Syntax :We will perform the natural join query by using the following syntax.
SELECT *
FROM TABLE1
NATURAL JOIN TABLE2;
Features of Natural Join :Here, we will discuss the features of natural join.
It will perform the Cartesian product.It finds consistent tuples and deletes inconsistent tuples.Then it deletes the duplicate attributes.
It will perform the Cartesian product.
It finds consistent tuples and deletes inconsistent tuples.
Then it deletes the duplicate attributes.
Steps to implement SQL Natural Join :Here, we will discuss the steps to implement SQL Natural Join as follows.
Step-1:Creating Database :
create database geeks;
Step-2: Using the database :To use this database as follows.
use geeks;
Step-3: Reference tables into the database :This is our tables in the geeks database as follows.
Table-1: department –
Create Table department
(
   DEPT_NAME Varchar(20),
   MANAGER_NAME Varchar(255)
);
Table-2: employee –
Create Table employee
(
   EMP_ID int,
   EMP_NAME Varchar(20),
   DEPT_NAME Varchar(255)
);
Step-4: Inserting values :Add value into the tables as follows.
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "IT", "ROHAN");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "SALES", "RAHUL");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "HR", "TANMAY");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "FINANCE", "ASHISH");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ("MARKETING", "SAMAY");

INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (1, "SUMIT", "HR");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (2, "JOEL", "IT");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (3, "BISWA", "MARKETING");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (4, "VAIBHAV", "IT");
INSERT INTO EMPLOYEE(EMP_ID, EMP_NAME, DEPT_NAME) VALUES (5, "SAGAR", "SALES");
Step-5: Verifying inserted data :This is our data inside the table as follows.
SELECT * FROM EMPLOYEE;
Output :
SELECT * FROM DEPARTMENT;
Output :
Step-6: Query to implement SQL Natural Join :
SELECT *
FROM EMPLOYEE
NATURAL JOIN DEPARTMENT;
Output :
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL | Subquery
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Convert VARCHAR to INT
SQL Query to Delete Duplicate Rows
SQL Query to Compare Two Dates
Window functions in SQL
Python - Working with PNG Images using Matplotlib

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
#applying pseudocolor
# importing pyplot and image from matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as img  
# reading png image
im = img.imread('imR.png')  
# applying pseudocolor
# default value of colormap is used.
lum = im[:, :, 0]  
# show image
plt.imshow(lum)
#colorbar
# importing pyplot and image from matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as img
# reading png image
im = img.imread('imR.png')
lum = im[:, :, 0]  
# setting colormap as hot
plt.imshow(lum, cmap ='hot')
plt.colorbar()
#interpolation
# importing PIL and matplotlib
from PIL import Image
import matplotlib.pyplot as plt  
# reading png image  file
img = Image.open('imR.png')  
# resizing the image
img.thumbnail((50, 50), Image.ANTIALIAS)
imgplot = plt.imshow(img)
#bicubic value for interpolation
# importing pyplot from matplotlib
import matplotlib.pyplot as plt
# importing image from PIL
from PIL import Image
# reading image
img = Image.open('imR.png')
img.thumbnail((30, 30), Image.ANTIALIAS)
# bicubic used for interpolation
imgplot = plt.imshow(img, interpolation ='bicubic')#sinc value for interpolation
# sinc value for interpolation
# importing PIL and matplotlib
from PIL import Image
import matplotlib.pyplot as plt
# reading image
img = Image.open('imR.png')
img.thumbnail((30, 30), Image.ANTIALIAS)
# sinc used for interpolation
imgplot = plt.imshow(img, interpolation ='sinc')
Erlang - Tuples

A tuple is a compound data type with a fixed number of terms. Each term in the Tuple is called an element. The number of elements is said to be the size of the Tuple.
An example of how the Tuple data type can be used is shown in the following program.
Here we are defining a Tuple P which has 3 terms. The tuple_size is an inbuilt function defined in Erlang which can be used to determine the size of the Tuple.
-module(helloworld). 
-export([start/0]). 

start() ->
   P = {john,24,{june,25}} , 
   io:fwrite("~w",[tuple_size(P)]).
The output of the above program will be as follows.
3

Let’s look at some more operations which are available for tuples.
is_tuple
This method is used to determine is the term provided is indeed a tuple.
list_to_tuple
This method is to convert a list to a tuple.
tuple_to_list
This method is convert a tuple to a list.
 Print
 Add Notes
 Bookmark this page
Python script to monitor website changes

24 Nov, 2021
In this article, we are going to discuss how to create a python script to monitor website changes. You can code a program to monitor a website and it will notify you if there are any changes. This program has many useful scenarios for example if your school website has updated something you will come to know about it. 
We will follow the following steps to write this program:
Read the URL you want to monitor.Hash the entire website.Wait for a specified amount of seconds.If there are any changes as compared to the previous hash notify me else wait and again and then again take the hash.
Read the URL you want to monitor.
Hash the entire website.
Wait for a specified amount of seconds.
If there are any changes as compared to the previous hash notify me else wait and again and then again take the hash.
Libraries we will be using are:
time: To wait for a specified amount of time.
hashlib: To hash the content of the entire website.
urllib: To perform the get request and load the content of the website.
Python3
# Importing librariesimport timeimport hashlibfrom urllib.request import urlopen, Request # setting the URL you want to monitorurl = Request('https://leetcode.com/',              headers={'User-Agent': 'Mozilla/5.0'}) # to perform a GET request and load the# content of the website and store it in a varresponse = urlopen(url).read() # to create the initial hashcurrentHash = hashlib.sha224(response).hexdigest()print("running")time.sleep(10)while True:    try:        # perform the get request and store it in a var        response = urlopen(url).read()                 # create a hash        currentHash = hashlib.sha224(response).hexdigest()                 # wait for 30 seconds        time.sleep(30)                 # perform the get request        response = urlopen(url).read()                 # create a new hash        newHash = hashlib.sha224(response).hexdigest()         # check if new hash is same as the previous hash        if newHash == currentHash:            continue         # if something changed in the hashes        else:            # notify            print("something changed")             # again read the website            response = urlopen(url).read()             # create a hash            currentHash = hashlib.sha224(response).hexdigest()             # wait for 30 seconds            time.sleep(30)            continue                 # To handle exceptions    except Exception as e:        print("error")
Output:
output
Note: time.sleep() takes seconds as a parameter. You can make changes for notification instead of printing the status on the terminal you can write a program to get an email.
kapoorsagar226
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Prefix extraction before specific character

25 Jun, 2022
Sometimes, we might have a use case in which we need to find a prefix in a string. But sometimes, the requirement can be something dynamic like a specific input character than number of elements for the decision of getting prefix. Let’s discuss certain ways in which we can find the prefix of a string before a certain character.
Method #1: Using rsplit() This method originally performs the task of splitting the string from the rear end rather than the conventional left to right fashion. This can though be limited to 1, for solving this particular problem. 
Python3
# Python3 code to demonstrate working of# Prefix extraction before specific character# Using rsplit() # initializing stringtest_str = "GeeksforGeeks & quot # initializing split characterspl_char = "r & quot # printing original stringprint(& quot       The original string is : & quot       + str(test_str)) # Using rsplit()# Prefix extraction before specific characterres = test_str.rsplit(spl_char, 1)[0] # printing resultprint(& quot       The prefix string is : & quot       + str(res))
The original string is : GeeksforGeeks
The prefix string is : Geeksfo
Method #2: Using rpartition() If we need to solve this particular problem, this inbuilt function is recommended to perform this particular task. This function performs the partition as required just once from the rear end. 
Python3
# Python3 code to demonstrate working of# Prefix extraction before specific character# Using rpartition() # initializing stringtest_str = "GeeksforGeeks & quot # initializing split characterspl_char = "r & quot # printing original stringprint(& quot       The original string is : & quot       + str(test_str)) # Using rpartition()# Prefix extraction before specific characterres = test_str.rpartition(spl_char)[0] # printing resultprint(& quot       The prefix string is : & quot       + str(res))
The original string is : GeeksforGeeks
The prefix string is : Geeksfo
Method #3 : Using find() method.You can also use index() instead of find().
Python3
# Python3 code to demonstrate working of# Prefix extraction before specific character# Using find() # initializing stringtest_str = "GeeksforGeeks" # initializing split characterspl_char = "r" # printing original stringprint("The original string is : " + str(test_str)) # Using find()# Prefix extraction before specific characterind=test_str.find(spl_char)res = test_str[0:ind] # printing resultprint("The prefix string is : " + str(res))
The original string is : GeeksforGeeks
The prefix string is : Geeksfo
kogantibhavya
Python string-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
p5.js | center() Function

20 Aug, 2019
The center() function is used to set the alignment of element into the center either vertically, horizontally, or both, relative to its parent element or according to the body if the element has no parent. If this function does not contain any parameters then the element will align both vertically and horizontally.
Note: This function requires the p5.dom library. So add the following line in the head section of the index.html file.
<script language="javascript"    type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:
center( align )
Parameters: This function accepts single parameter align which holds the string ‘vertical’ or ‘horizontal’ to align the element.
Below examples illustrate the center() function in p5.js:
Example 1:
function setup() {          // Create canvas of given size    createCanvas(1000, 200);          // Set background color    background('green');          var div = createDiv('').size(200, 70);          div.html('Welcome to GeeksforGeeks', true);           // Set the position of div into center    div.center();        // Set font-size of text    div.style('font-size', '24px');        // Set font-color of text    div.style('color', 'white');        div.style('border', '1px solid white');        div.style('text-align', 'center');  } 
Output:
Example 2:
function setup() {          // Create canvas of given size    createCanvas(1000, 200);          // Set background color    background('green');          // Create an input element    var input_val = createInput('');              // Set the attribute and its value        input_val.attribute('value', 'Welcome to GeeksforGeeks');             // Set the position of div into center    input_val.center();        // Set font-size of text    input_val.style('font-size', '24px');          // Set the width of input area    input_val.style('width', '300px');  } 
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
D3.js | d3.select() Function

17 Jul, 2019
The d3.select() function in D3.js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.
Syntax:
d3.select("element")
Parameters: This function accepts single parameter which holds the element name.
Return Value: This function returns the selected elements.
Below programs illustrate the d3.select() function in D3.js:
Example 1:
<!DOCTYPE html><html>  <head>    <title>        D3.js | d3.select() Function    </title>          <script src = "https://d3js.org/d3.v4.min.js"></script></head>  <body>          <div>GeeksforGeeks</div>          <script>              // Calling the select() function        var a = d3.select("div").text();                  // Getting the selected element        console.log(a);    </script></body>  </html>                    
Output:
GeeksforGeeks 

Example 2:
<!DOCTYPE html><html>  <head>             <title>        D3.js | d3.select() Function    </title>          <script src="https://d3js.org/d3.v4.min.js"></script></head>   <body>    <p>GeeksforGeeks</p>             <p>A computer science portal for geeks</p>             <script>                 // Calling the select() function        var a = d3.select("p").text();                    // Getting the selected element        console.log(a);    </script></body>     </html>
Output:
GeeksforGeeks
Reference: https://devdocs.io/d3~5/d3-selection#select
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
MongoDB – copyTo() Method

16 Mar, 2021
In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name. This method uses eval command internally.     
Important Note: As CopyTo() uses eval() internally & eval() is deprecated since version 3.0, so CopyTo() is also deprecated since version 3.0.
Syntax:
db.sourceCollection.copyTo(targetCollection)                                                                   
Parameter:
It takes only the name of the target collection where you want to copy the documents of the source collection. The type of this parameter is string.
Return: 
This method returns the number of documents copied and if that process fails it throws an exception.
Example 1: In the following example, we are working with:
Database: gfg
Collections: collectionA and collectionB
The collectionA contains three documents:
The collectionB contains two documents:
Now we copy the documents of collectionA to collectionB using copyTo() method.
db.collectionA.copyTo("collectionB")
Example 2: In the following example, we are working with:
Database: gfg
Collection: sCollection
Documents: Three documents contains name and age of the students
Now we going to copy the documents of sCollection to a new collection i.e., tCollection using copyTo() method. Here, the tCollection is not present in gfg database so MongoDB create this collection.
db.sCollection.copyTo("tCollection")
MongoDB-method
Picked
MongoDB
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
Mongoose | updateOne() Function
Aggregation in MongoDB
Mongoose | findOne() Function
MongoDB - Check the existence of the fields in the specified collection
Upsert in MongoDB
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
Google Interview Experience | Set 4

04 Jun, 2019
Though I didn’t clear google but I want to share my Google interview experience , so it can help other’s . Please find my interview experience below:
My Google Interview Experience for Software Developer Position [Android Core Team], London, United Kingdom
Like many other enthusiastic engineers, I too applied for a job at Google. I know that its very difficult that a resume gets noticed by google.Suddenly, one fine day I received a Mail( “Hello from Google !”) from Google’s HR saying that they are interested in my profile and asked me if I was ready to go ahead with the interview process[Come on! you cant say no to Google].
Round1(Phone interview) :
By:Talent Scout @Google:
* Questions from Project :Spell Corrector:How it works , Bigram and ngram model approach, etc.
* Why should one use merge sort over quick sort and vice-versa.
* You have a very large array of ‘Person’ objects .Sort the people in increasing order of age .
General :
Then came the exciting part when he asked me to choose location b/w Google Paris(Text-Speech Team) or Google London(Android Core Team).
He explained how Google work’s on their projects !
About Google interview process ( 2-3 phone interview + 4-5 onsite interview in London ).
Round2:(Phone interview + coding on shared google doc)
By:Software Developer @Google :
* Questions from Project:Bi-directional Sync b/w mysql and sqilte db.
* Given a number , check if it can be represented in 5^n form , where n is positive integer .
* Given a string of words with lots of spaces between the words , remove all the unnecessary spaces like
  input:  I   live   on     earth  
  output: I live on earth
Round3:(Phone interview + coding on shared google doc)
By:Software developer @Google :
* Optimize a^b
* How would you split a search query across multiple machines?
* You need to develop the game Snake. What data structures will you use? Code your solution.
Some additional hints for the interview:
Clarify the question – make sure you understand everything.
Try to find the most efficient solution.
Come up with solutions quickly: even if its a brute force solution. Always iterate away from the original solution.
Before you start coding explain why you’re approaching it that way ,its ok to start off with a naive solution and try to make it more efficient.
Explain the rationale behind the steps you are doing.
Think out loud, keep things technical. The engineers will give you hints: take a hint! They are there to help you!
Always write “compilable” code.
Mind edge cases. Find bugs in your code.
 
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Google
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert an item at the beginning of an array in PHP ?

06 Jun, 2021
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data type under a single variable thereby saving us the effort of creating a different variable for every data. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. There are two methods to insert an item at the beginning of an array which are discussed below:Using array_merge() Function: The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.  
Create an array containing array elements.
Create another array containing one element which needs to insert at the beginning of another array.
Use array_merge() function to merge both arrays to create a single array.
Example:  
php
<?php // Declare an array$arr1 = array(    "GeeksforGeeks",    "Computer",    "Science",    "Portal"); // Declare another array containing// element which need to insert at// the beginning of $arr1$arr2 = array(    "Welcome"); // User array_merge() function to// merge both array$mergeArr = array_merge( $arr1, $arr2 ); print_r($mergeArr); ?>
Array
(
    [0] => GeeksforGeeks
    [1] => Computer
    [2] => Science
    [3] => Portal
    [4] => Welcome
)
 
Using array_unshift() function: The array_unshift() function is used to add on or more elements at the beginning of the array. Example 1:  
php
<?php // Declare an array$array = array(    "GeeksforGeeks",    "Computer",    "Science",    "Portal"); // Declare a variable containing element$element = "Welcome"; // User array_unshift() function to// insert element at beginning of arrayarray_unshift( $array, $element ); print_r($array); ?>
Array
(
    [0] => Welcome
    [1] => GeeksforGeeks
    [2] => Computer
    [3] => Science
    [4] => Portal
)
 
Example 2:  
php
<?php // Declare an associative array$array = array(    "p" => "GeeksforGeeks",    "q" => "Computer",    "r" => "Science",    "s" => "Portal"); // Declare a variable containing element$element = "Welcome"; // User array_unshift() function to// insert element at beginning of arrayarray_unshift( $array, $element ); print_r($array); ?>
Array
(
    [0] => Welcome
    [p] => GeeksforGeeks
    [q] => Computer
    [r] => Science
    [s] => Portal
)
 
arorakashish0911
PHP-array
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check if all elements in a List are same

08 Dec, 2018
Given a list, write a Python program to check if all the elements in given list are same.
Example:
Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]
Output: Yes

Input: ['Geeks', 'Is', 'all', 'Same', ]
Output: No
There are various ways we can do this task. Let’s see different ways we can check if all elements in a List are same.
Method #1: Comparing each element.
# Python program to check if all # ments in a List are same   def ckeckList(lst):      ele = lst[0]    chk = True          # Comparing each element with first item     for item in lst:        if ele != item:            chk = False            break;                  if (chk == True): print("Equal")    else: print("Not equal")              # Driver Codelst = ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]ckeckList(lst)
Output:
Equal
 But In Python, we can do the same task in much interesting ways.
Method #2: Using all() method
# Python program to check if all # elements in a List are same res = False  def chkList(lst):    if len(lst) < 0 :        res = True    res = all(ele == lst[0] for ele in lst)          if(res):        print("Equal")    else:        print("Not equal")  # Driver Code        lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']chkList(lst)
Output:
Equal
 Method #3: Using count() method
# Python program to check if all # elements in a List are same res = False  def chkList(lst):    if len(lst) < 0 :        res = True    res = lst.count(lst[0]) == len(lst)          if(res):        print("Equal")    else:        print("Not equal")  # Driver Code        lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']chkList(lst)
Output:
Equal
 Method #4: Using set data structureSince we know there cannot be duplicate elements in a set, we can use this property to check whether all the elements are same or not.
# Python program to check if all # elements in a List are same   def chkList(lst):    return len(set(lst)) == 1    # Driver Code        lst = ['Geeks', 'Geeks', 'Geeks', 'Geeks']  if chkList(lst) == True: print("Equal")else: print("Not Equal")
Output:
Equal
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Python's Sys Module

The sys module in Python provides valuable information about the Python interpreter. You can also use it to obtain details about the constants, functions and methods of the Python interpreter.
The sys module comes packaged with Python, which means you do not need to download and install it separately using the PIP package manager.
In order to start using the sys module and its various functions, you need to import it. You can do that using the below line of code,
import sys
In python, we can execute the script directly from our terminal using various arguments. Sometimes it is nice to display the user the different arguments they’ve used while executing the script or to store it for other purposes.
We can achieve this with ease using the argv function present in the sys module.
# Creating a Python script named example.py
import sys
print("You entered: ", sys.argv[1], sys.argv[2])
Now, if you run the above program through a terminal with arguments, we first change the directory to the one where the script is present and then use,
python example.py Hello World
Typing the above line in the terminal will then execute the program which will then in turn print out the arguments we’ve entered.
Hello World
Note − In the above example we started with sys.argv[1] and not sys.argv[0], because sys.argv[0] prints the name of script we are currently executing and not the argument provided.
If you want to force quit the application or stop it from executing at any point, we can use the exit() function within the sys module.
import sys
print(“Hello there!”)
sys.exit()
print(“This line is not even executed because the program exited in the last line”)
Hello there!
In the above example, we use the sys.exit() function to stop the execution of the program, thus not printing the last line.
Wondered what version of python you are working on? Or just wanted the user to know what version of Python they are using to execute your script?
You can use the sys.version method to do so.
import sys
print(“You are currently using Python version”, sys.version)
You are currently using Python version 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)]
If you want to know where all your Python modules are downloaded and installed, you can use the sys.path folder.
import sys
sys.path
Input() is not the only way to read user input. You can use the sys module’s stdin function to read input as well.
import sys
data = sys.stdin.readline()
print(“You have entered −> ” + data)
The above line of code will read in the data entered until the user hits Enter and then print it back.
You now have a basic understanding of how and where we use the sys module in python.
There are a lot more functions in the sys module with more features and functionalities. To explore and read more about each of them, you can go through its official documentation at https://docs.python.org/3/library/sys.html.
Python | Pandas dataframe.idxmax()

19 Nov, 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 dataframe.idxmax() function returns index of first occurrence of maximum over requested axis. While finding the index of the maximum value across any index, all NA/null values are excluded.
Syntax: DataFrame.idxmax(axis=0, skipna=True)
Parameters :axis : 0 or ‘index’ for row-wise, 1 or ‘columns’ for column-wiseskipna : Exclude NA/null values. If an entire row/column is NA, the result will be NA
Returns : idxmax : Series
Example #1: Use idxmax() function to function to find the index of the maximum value along the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[4, 5, 2, 6],                    "B":[11, 2, 5, 8],                   "C":[1, 8, 66, 4]})  # Print the dataframedf
Now apply the idxmax() function along the index axis.
# applying idxmax() function.df.idxmax(axis = 0)
Output :
If we look at the values in the dataframe, we can verify the result returned by the function. The function returned a pandas series object containing the index of maximum value in each column. 
Example #2: Use idxmax() function to find the index of the maximum value along the column axis. The dataframe contains NA values.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[4, 5, 2, None],                   "B":[11, 2, None, 8],                    "C":[1, 8, 66, 4]})  # Skipna = True will skip all the Na values# find maximum along column axisdf.idxmax(axis = 1, skipna = True)
Output :
The output is a pandas series containing the column label for each row which has the maximum value.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TypeScript | String search() Method

17 Feb, 2021
The search() is an inbuilt function in TypeScript that is used to search for a match between a regular expression and this String object. Syntax:
string.search(regexp);
Parameter: This methods accept a single parameter as mentioned above and described below: 
regexp: This parameter is a RegExp object.
Return Value: This method returns the index of the regular expression inside the string. Otherwise, it returns -1. Below example illustrate the  String search() method in TypeScriptJS:
Example 1:
Javascript
// This is TypeScript// Original stringsvar str = "Geeksforgeeks - Best Platform"; var re = /Best/gi; // use of String search() Methodif (str.search(re) == -1 ) {  console.log("Not Found" );} else {  console.log("Found" );}
Output: 
Found
Example 2:
JavaScript
// This is TypeScript// Original stringsvar str = "Geeksforgeeks - Best Platform"; var re = /geeek/gi; // use of String search() Methodif (str.search(re) == -1 ) {    console.log("Not Found" );} else {    console.log("Found" );}
Output:
Not Found 
pratikraut0000
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Set equal_range() function in C++ STL

In this article we are going to discuss the set::equal_range() function in C++ STL, their syntax, working and their return values.
Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in a set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.
equal_range() function is an inbuilt function in C++ STL, which is defined in header file. This function returns the range of the set container which contains value passed as the argument of the function. The set contain all the unique values so the equivalent value in the found range will be single. If the value is not present in the container the range will be zero, with both iterators pointing to the first position.
Set1.equal_range(const type_t& value);
This function accepts one parameter, i.e., element which is to be found.
This function returns the pair or we can say iterator range starting from the lower bound of the container till the element which is to be found in the container.
Input: set<int> myset = {10, 20, 30, 40};
Output: lower bound of 30 is 30
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> mySet;
   mySet.insert(10);
   mySet.insert(20);
   mySet.insert(30);
   mySet.insert(40);
   mySet.insert(50);
   cout<<"Elements before applying range() Function : ";
   for (auto i = mySet.begin(); i != mySet.end(); i++)
      cout << *i << " ";
   auto i = mySet.equal_range(30);
   cout<<"\nlower bound of 30 is "<< *i.first;
   cout<<"\nupper bound of 30 is "<< *i.second;
   i = mySet.equal_range(40);
   cout<<"\nlower bound of 40 is " << *i.first;
   cout<<"\nupper bound of 40 is " << *i.second;
   i = mySet.equal_range(10);
   cout<<"\nlower bound of 10 is " << *i.first;
   cout<<"\nupper bound of 10 is " << *i.second;
   return 0;
}
If we run the above code then it will generate the following output −
Elements before applying range() Function : 10 20 30 40 50
lower bound of 30 is 30
upper bound of 30 is 40
lower bound of 40 is 40
upper bound of 40 is 50
lower bound of 10 is 10
upper bound of 10 is 20
Apply changes to all the images in given folder - Using Python PIL - GeeksforGeeks

21 Nov, 2019
Given a dataset of raw images, which usually need some pre-processing, which one person has to do physically. It is generally a task that requires some repetitive operation to perform for each image. Well, we can easily automate this process using some simple Python code and some libraries with it. So without further adieu, let’s see how to apply changes to all the images in given folder and save it to some destination folder using Python PIL.
Let’s install all the required modules –
pip3 install pillow
pip3 install os-sys
We will be parsing all the images in the folder to apply changes/operations to all of them simultaneously.
# Code to apply operations on all the images# present in a folder one by one# operations such as rotating, cropping, from PIL import Imagefrom PIL import ImageFilterimport os  def main():    # path of the folder containing the raw images    inPath ="E:\\GeeksforGeeks\\images"      # path of the folder that will contain the modified image    outPath ="E:\\GeeksforGeeks\\images_rotated"      for imagePath in os.listdir(inPath):        # imagePath contains name of the image         inputPath = os.path.join(inPath, imagePath)          # inputPath contains the full directory name        img = Image.open(inputPath)          fullOutPath = os.path.join(outPath, 'invert_'+imagePath)        # fullOutPath contains the path of the output        # image that needs to be generated        img.rotate(90).save(fullOutPath)          print(fullOutPath)  # Driver Functionif __name__ == '__main__':    main()
Sample images from the folder –
Input :
image_sample1
invert_image_sample1
Image-Processing
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
BigDecimal signum() Method in Java - GeeksforGeeks

04 Dec, 2018
The java.math.BigDecimal.signum() is an inbuilt method in Java that returns the signum function of this BigDecimal. The sign function or signum function is an odd mathematical function that extracts the sign of a real number. In mathematical expressions, the sign function is often represented as sgn.
Syntax:
public int signum()

Parameters: This method does not accepts any parameter.
Return value: This method can return three types of values:
-1 if this BigDecimal < 0
0 if this BigDecimal = 0
1 if this BigDecimal is > 0
Below program illustrates the working of the above mentioned method:
Program 1:
// Program to demonstrate signum() method of BigDecimal   import java.math.*;  public class Gfg {      public static void main(String[] args)    {          BigDecimal b1 = new BigDecimal("12743");        BigDecimal b2 = new BigDecimal("0");        BigDecimal b3 = new BigDecimal("-4512");          // Assigning the signum values of  BigDecimal objects b1, b2, b3        // to  int objects i1, i2, i3 respectively        int i1 = b1.signum();        int i2 = b2.signum();        int i3 = b3.signum();          // Printing i1, i2, i3 values        System.out.println("Signum function on " + b1 + " is " + i1);        System.out.println("Signum function on " + b2 + " is " + i2);        System.out.println("Signum function on " + b3 + " is " + i3);    }}
Signum function on 12743 is 1
Signum function on 0 is 0
Signum function on -4512 is -1

Program 2:
// Program to demonstrate signum() method of BigDecimal   import java.math.*;  public class Gfg {      public static void main(String[] args)    {          BigDecimal b1 = new BigDecimal("17845452743");        BigDecimal b2 = new BigDecimal("000");        BigDecimal b3 = new BigDecimal("-444512");          // Assigning the signum values of  BigDecimal objects b1, b2, b3        // to  int objects i1, i2, i3 respectively        int i1 = b1.signum();        int i2 = b2.signum();        int i3 = b3.signum();          // Printing i1, i2, i3 values        System.out.println("Signum function on " + b1 + " is " + i1);        System.out.println("Signum function on " + b2 + " is " + i2);        System.out.println("Signum function on " + b3 + " is " + i3);    }}
Signum function on 17845452743 is 1
Signum function on 0 is 0
Signum function on -444512 is -1

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#signum()
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
JavaScript Date getMonth() Method - GeeksforGeeks

12 Oct, 2021
Below is the example of Date getMonth() method.  
Example:  
javascript
<script type="text/javascript">   // Creating a Date Object   var DateObj = new Date('October 15, 1996 05:35:32');    // Month from above Date Object is   // Being extracted using getMonth()   var months = DateObj.getMonth();    // Printing month.   document.write(months);</script>
Output:  
9
The date.getMonth() method is used to fetch the month(0 to 11) from given Date object.Syntax:  
DateObj.getMonth()
Parameter: This function does not accept any parameter. Return Value: It returns the Month for the given Date object. The month is an integer value ranging from 0 to 11. Zero (0) means January, 1 means February, and so on till 11 means December.More codes for the above method are as follows:Program 1: Here the date of the month should lie in between 1 to 31 because no date can have month greater than 31. That is why it returns NaN i.e, Not a Number if the month in the Date object is greater than 31.  
javascript
<script type="text/javascript">   // Creating a Date Object   var DateObj = new Date('October 33, 1996 05:35:32');    // Month from above Date Object is being   // Extracted using getMonth()   var months = DateObj.getMonth();    // Printing month.   document.write(months);</script>
Output:  
NaN
Program 2: If month is not given, it returns zero (0).  
javascript
<script type="text/javascript">   // Creating a Date Object   var DateObj = new Date('1996 05:35:32');    // Month from above Date Object is being   // Extracted using getMonth()   var months = DateObj.getMonth();    // Printing month.   document.write(months);</script>
Output:  
0
Program 3: If nothing as parameter is given, it returns current month.  
javascript
<script type="text/javascript">   // Creating a Date Object   var DateObj = new Date();    // Month from above Date Object is being   // Extracted using getMonth()   var months = DateObj.getMonth();    // Printing month.  document.write(months);</script>
Output:  
2
Supported Browsers: The browsers supported by JavaScript Date getMonth() method are listed below:  
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 3 and above
Safari 1 and above
 
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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 append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?