code-rag-bench/online-tutorials huggingface dataset:
Python | Pandas.melt() - GeeksforGeeks

03 Jan, 2022
To make analysis of data in table easier, we can reshape the data into a more computer-friendly form using Pandas in Python. Pandas.melt() is one of the function to do so..Pandas.melt() unpivots a DataFrame from wide format to long format.melt() function is useful to message a DataFrame into a format where one or more columns are identifier variables, while all other columns, considered measured variables, are unpivoted to the row axis, leaving just two non-identifier columns, variable and value.Syntax :
pandas.melt(frame, id_vars=None, value_vars=None,
 var_name=None, value_name='value', col_level=None)
Parameters:
frame : DataFrameid_vars[tuple, list, or ndarray, optional] : Column(s) to use as identifier variables.value_vars[tuple, list, or ndarray, optional]: Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars.var_name[scalar]: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’.value_name[scalar, default ‘value’]: Name to use for the ‘value’ column.col_level[int or string, optional]: If columns are a MultiIndex then use this level to melt.
Example:
Python3
# Create a simple dataframe  # importing pandas as pdimport pandas as pd  # creating a dataframedf = pd.DataFrame({'Name': {0: 'John', 1: 'Bob', 2: 'Shiela'},                   'Course': {0: 'Masters', 1: 'Graduate', 2: 'Graduate'},                   'Age': {0: 27, 1: 23, 2: 21}})df
 
Python3
# Name is id_vars and Course is value_varspd.melt(df, id_vars =['Name'], value_vars =['Course'])
 
Python3
# multiple unpivot columnspd.melt(df, id_vars =['Name'], value_vars =['Course', 'Age'])
Python3
# Names of ‘variable’ and ‘value’ columns can be customizedpd.melt(df, id_vars =['Name'], value_vars =['Course'],              var_name ='ChangedVarname', value_name ='ChangedValname')
surindertarika1234
Python pandas-dataFrame
Python-pandas
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python3 Program for Mean of range in array - GeeksforGeeks

13 Jan, 2022
Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line.
Examples : 
Input : arr[] = {1, 2, 3, 4, 5}
        q = 3
        0 2
        1 3
        0 4
Output : 2
         3
         3
Here for 0 to 2 (1 + 2 + 3) / 3 = 2

Input : arr[] = {6, 7, 8, 10}
        q = 2
        0 3
        1 2
Output : 7
         7
Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query.  
Python3
# Python 3 program to find floor value# of mean in range l to rimport math  # To find mean of range in l to rdef findMean(arr, l, r):          # Both sum and count are    # initialize to 0    sum, count = 0, 0          # To calculate sum and number    # of elements in range l to r    for i in range(l, r + 1):        sum += arr[i]        count += 1      # Calculate floor value of mean    mean = math.floor(sum / count)      # Returns mean of array    # in range l to r    return mean  # Driver Codearr = [ 1, 2, 3, 4, 5 ]      print(findMean(arr, 0, 2))print(findMean(arr, 1, 3))print(findMean(arr, 0, 4))  # This code is contributed # by PrinciRaj1992
Output : 
2
3
3
Time Complexity: O(n)
Efficient Approach: We can find sum of numbers using numbers using prefix sum. The prefixSum[i] denotes the sum of first i elements. So sum of numbers in range l to r will be prefixSum[r] – prefixSum[l-1]. Number of elements in range l to r will be r – l + 1. So we can now print mean of range l to r in O(1). 
Python3
# Python3 program to find floor value# of mean in range l to rimport math as mt  MAX = 1000005prefixSum = [0 for i in range(MAX)]  # To calculate prefixSum of arraydef calculatePrefixSum(arr, n):      # Calculate prefix sum of array    prefixSum[0] = arr[0]      for i in range(1,n):        prefixSum[i] = prefixSum[i - 1] + arr[i]  # To return floor of mean# in range l to rdef findMean(l, r):      if (l == 0):        return mt.floor(prefixSum[r] / (r + 1))      # Sum of elements in range l to    # r is prefixSum[r] - prefixSum[l-1]    # Number of elements in range    # l to r is r - l + 1    return (mt.floor((prefixSum[r] -                       prefixSum[l - 1]) /                          (r - l + 1)))  # Driver Codearr = [1, 2, 3, 4, 5]  n = len(arr)  calculatePrefixSum(arr, n)print(findMean(0, 2))print(findMean(1, 3))print(findMean(0, 4))  # This code is contributed by Mohit Kumar
Output: 
2
3
3
Please refer complete article on Mean of range in array for more details!
array-range-queries
prefix-sum
Arrays
Python
prefix-sum
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
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 program to find Cumulative sum of a list - GeeksforGeeks

20 Aug, 2020
The problem statement asks to produce a new list whose i^{th} element will be equal to the sum of the (i + 1) elements.
Examples :  
Input : list = [10, 20, 30, 40, 50]
Output : [10, 30, 60, 100, 150]

Input : list = [4, 10, 15, 18, 20]
Output : [4, 14, 29, 47, 67]


 
Approach 1 : We will use the concept of list comprehension and list slicing to get the cumulative sum of the list. The list comprehension has been used to access each element from the list and slicing has been done to access the elements from start to the i+1 element. We have used the sum() method to sum up the elements of the list from start to i+1.Below is the implementation of the above approach :  
Python3
# Python code to get the Cumulative sum of a listdef Cumulative(lists):    cu_list = []    length = len(lists)    cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]    return cu_list[1:] # Driver Codelists = [10, 20, 30, 40, 50]print (Cumulative(lists))
Output :  
[10, 30, 60, 100, 150]


Approach 2: 
Python3
list=[10,20,30,40,50]new_list=[]j=0for i in range(0,len(list)):    j+=list[i]    new_list.append(j)     print(new_list)#code given by Divyanshu singh
Output :  
[10, 30, 60, 100, 150]


 
kaushikkakdey
divyanshusingh9314
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.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
PHP | Factorial of a number - GeeksforGeeks

09 Mar, 2018
We already know how to get the factorial of a number in other languages. Let’s see how this is done in PHP using both recursive and non-recursive ways.
Examples:
Input : 5
Output : 120

Input : 10
Output : 3628800

Method 1: Iterative wayIn this method, we simply used the for loop to iterate over the sequence of numbers to get the factorial.
<?php// PHP code to get the factorial of a number// function to get factorial in iterative wayfunction Factorial($number){    $factorial = 1;    for ($i = 1; $i <= $number; $i++){      $factorial = $factorial * $i;    }    return $factorial;}  // Driver Code$number = 10;$fact = Factorial($number);echo "Factorial = $fact";?>
Output:
3628800

Method 2: Use of recursionIn this method we are calling the same method to get the sequence of the factorial.
<?php// PHP code to get the factorial of a number// function to get factorial in iterative wayfunction Factorial($number){    if($number <= 1){          return 1;      }      else{          return $number * Factorial($number - 1);      }  }  // Driver Code$number = 10;$fact = Factorial($number);echo "Factorial = $fact";?>
Output:
3628800

PHP-basics
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between getc(), getchar(), getch() and getche() - GeeksforGeeks

13 Dec, 2018
All of these functions read a character from input and return an integer value. The integer is returned to accommodate a special value used to indicate failure. The value EOF is generally used for this purpose.
getc():It reads a single character from a given input stream and returns the corresponding integer value (typically ASCII value of read character) on success. It returns EOF on failure.
Syntax:
int getc(FILE *stream); 
Example:
// Example for getc() in C#include <stdio.h>int main(){   printf("%c", getc(stdin));   return(0);}
Input: g (press enter key)
Output: g 
An Example Application : C program to compare two files and report mismatches
getchar():The difference between getc() and getchar() is getc() can read from any input stream, but getchar() reads from standard input. So getchar() is equivalent to getc(stdin).
Syntax:
int getchar(void); 
Example:
// Example for getchar() in C#include <stdio.h>int main(){   printf("%c", getchar());   return 0;}
Input: g(press enter key)
Output: g 
getch():getch() is a nonstandard function and is present in conio.h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX (Source: http://en.wikipedia.org/wiki/Conio.h)Like above functions, it reads also a single character from keyboard. But it does not use any buffer, so the entered character is immediately returned without waiting for the enter key.Syntax:
int getch();
Example:
// Example for getch() in C#include <stdio.h>#include <conio.h>int main(){   printf("%c", getch());      return 0;}
Input:  g (Without enter key)
Output: Program terminates immediately.
        But when you use DOS shell in Turbo C, 
        it shows a single g, i.e., 'g'
getche()Like getch(), this is also a non-standard function present in conio.h. It reads a single character from the keyboard and displays immediately on output screen without waiting for enter key.
Syntax:
int getche(void); 
Example:
#include <stdio.h>#include <conio.h>// Example for getche() in Cint main(){  printf("%c", getche());  return 0;}
Input: g(without enter key as it is not buffered)
Output: Program terminates immediately.
        But when you use DOS shell in Turbo C, 
        double g, i.e., 'gg'
This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Input and Output Quiz
c-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
fork() in C
std::string class in C++
Enumeration (or enum) in C
Command line arguments in C/C++
TCP Server-Client implementation in C
Different methods to reverse a string in C/C++
Structures in C
Exception Handling in C++
CSS | #id Selector - GeeksforGeeks

03 Jan, 2019
The #id selector is used to set the style of given id. The id attribute is the unique identifier in HTML document. The id selector is used with # character.
Syntax:
#id {
    // CSS property
}
Example:
<!DOCTYPE html><html>    <head>        <title>#id selector</title>                  <!-- CSS property using id attribute -->        <style>            #gfg1 {                color:green;                text-align:center;            }            #gfg2 {                text-align:center;            }        </style>    </head>          <body>                  <!-- id attribute declare here -->        <h1 id = "gfg1">GeeksforGeeks</h1>        <h2 id = "gfg2">#id selector</h2>    </body></html>
Output:
Supported Browsers: The browser supported by id selector are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Selectors
Picked
Technical Scripter 2018
CSS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
TreeMap lastKey() Method in Java

09 Jul, 2018
The java.util.TreeMap.lastKey() is used to retrieve the last or the highest key present in the map.
Syntax:
 tree_map.lastKey()
Parameters: The method does not take any parameters.
Return Value: The method returns the last key present in the map.
Exception: The method throws NoSuchElementException if the map is empty.
Below programs illustrate the working of java.util.TreeMap.lastKey() method:Program 1:
// Java code to illustrate the lastKey() methodimport java.util.*;  public class Tree_Map_Demo {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>();          // Mapping string values to int keys        tree_map.put(10, "Geeks");        tree_map.put(15, "4");        tree_map.put(20, "Geeks");        tree_map.put(25, "Welcomes");        tree_map.put(30, "You");          // Displaying the TreeMap        System.out.println("The Mappings are: " + tree_map);          // Displaying the lastKey of the map        System.out.println("The last key is " + tree_map.lastKey());    }}
The Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The last key is 30

Program 2:
// Java code to illustrate the lastKey() methodimport java.util.*;  public class Tree_Map_Demo {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>();          // Mapping int values to string keys        tree_map.put("Geeks", 10);        tree_map.put("4", 15);        tree_map.put("Geeks", 20);        tree_map.put("Welcomes", 25);        tree_map.put("You", 30);          // Displaying the TreeMap        System.out.println("The Mappings are: " + tree_map);          // Displaying the lastKey of the map        System.out.println("The last key is " + tree_map.lastKey());    }}
The Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
The last key is You

Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Add an object to the end of the ArrayList

01 Feb, 2019
ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. It also allows dynamic memory allocation, adding, searching and sorting items in the list. ArrayList.Add(Object) method adds an object to the end of the ArrayList.
Properties of ArrayList Class:
Elements can be added or removed from the Array List collection at any point in time.
The ArrayList is not guaranteed to be sorted.
The capacity of an ArrayList is the number of elements the ArrayList can hold.
Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
It also allows duplicate elements.
Using multidimensional arrays as elements in an ArrayList collection is not supported.
Syntax:
public virtual int Add (object value);

Here, value is the Object to be added to the end of the ArrayList. The value can be null.
Return Value: This method returns the ArrayList index at which the value has been added.
Exception: This method will give NotSupportedException if the ArrayList is either read-only or fixed size.
Below are the programs to illustrate the use of ArrayList.Add(Object) Method:
Example 1:
// C# code to add an object to// the end of the ArrayListusing System;using System.Collections;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating an ArrayList        ArrayList myList = new ArrayList();          // Adding elements to ArrayList        myList.Add("A");        myList.Add("B");        myList.Add("C");        myList.Add("D");        myList.Add("E");        myList.Add("F");          // Displaying the elements in the ArrayList        foreach(string str in myList)        {            Console.WriteLine(str);        }    }}
A
B
C
D
E
F

Example 2:
// C# code to add an object to// the end of the ArrayListusing System;using System.Collections;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating an ArrayList        ArrayList myList = new ArrayList();          // Adding elements to ArrayList        myList.Add(1);        myList.Add(2);        myList.Add(3);        myList.Add(4);        myList.Add(5);        myList.Add(6);          // Displaying the elements in the ArrayList        foreach(int i in myList)        {            Console.WriteLine(i);        }    }}
1
2
3
4
5
6

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.add?view=netframework-4.7.2
CSharp-Collections-ArrayList
CSharp-Collections-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Arrays - GeeksforGeeks

07 Mar, 2018
0
0
garbage value
garbage value
class Test {
   public static void main(String args[]) {
     int arr[5];   //Error
   }
}
0
0
garbage value
garbage value
 0
 1 2
 3 4 5
 6 7 8 9 
 0
 0 0
 0 0 0
 0 0 0 0 
 9
 7 8
 4 5 6
 0 1 2 3 
for(j = 0; j < 4; ++j){
     t = M[i][j];
     M[i][j] = M[j][i];
     M[j][i] = t;
}
for(j = 0; j < 4; ++j){
     M[i][j] = t;
     t = M[j][i];
     M[j][i] = M[i][j];
}
for(j = i; j < 4; ++j){
     t = M[i][j];
     M[i][j] = M[j][i];
     M[j][i] = t;
}
for(j = i; j < 4; ++j){
     M[i][j] = t;
     t = M[j][i];
     M[j][i] = M[i][j];
}
To compute transpose j needs to be started with i,so A and B are WRONG
In D, given statement is wrong as temporary variable t needs to be assigned some value and NOT vice versa M[i][j] = t; 
 M[i][j] = t; 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Python program to build flashcard using class in Python

20 Jun, 2022
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its meaning.
Let’s see some examples of flashcard:
Example 1:
Approach :
Take the word and its meaning as input from the user.
Create a class named flashcard, use the __init__() function to assign values for Word and Meaning.
Now we use the __str__() function to return a string that contains the word and meaning.
Store the returned strings in a list named flash.
Use a while loop to print all the stored flashcards.
Below is the full implementation:
Python3
class flashcard:    def __init__(self, word, meaning):        self.word = word        self.meaning = meaning    def __str__(self):               #we will return a string        return self.word+' ( '+self.meaning+' )'       flash = []print("welcome to flashcard application") #the following loop will be repeated until#user stops to add the flashcardswhile(True):    word = input("enter the name you want to add to flashcard : ")    meaning = input("enter the meaning of the word : ")         flash.append(flashcard(word, meaning))    option = int(input("enter 0 , if you want to add another flashcard : "))         if(option):        break         # printing all the flashcardsprint("\nYour flashcards")for i in flash:    print(">", i)
Output:
Example 2:
Approach :
Create a class named flashcard.
Initialize dictionary fruits using __init__() method.
Now randomly choose a pair from fruits using choice() method and store the key in variable fruit and value in variable color.
Now prompt the user to answer the color of the randomly chosen fruit.
If correct print correct else print wrong.
Python3
import random class flashcard:    def __init__(self):               self.fruits={'apple':'red',                     'orange':'orange',                     'watermelon':'green',                     'banana':'yellow'}             def quiz(self):        while (True):                       fruit, color = random.choice(list(self.fruits.items()))                         print("What is the color of {}".format(fruit))            user_answer = input()                         if(user_answer.lower() == color):                print("Correct answer")            else:                print("Wrong answer")                             option = int(input("enter 0 , if you want to play again : "))            if (option):                break print("welcome to fruit quiz ")fc=flashcard()fc.quiz()
Output:
jainlovely450
Picked
Python Oops-programs
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert dataframe column to list in R

23 May, 2021
In this article, we will learn how to convert a dataframe into a list by columns in R Programming language. We will be using as.list() function, this function is used to convert an object to a list. These objects can be Vectors, Matrices, Factors, and data frames.
Syntax: as.list( object )
Parameter: Dataframe object in our case
After passing the complete dataframe as an input to the function, nothing much has to be done, the function will responsibly convert each column to a separate list, with column elements as elements of the list.
Example 1:
R
df<-data.frame(c1=c(11:15),            c2=c(16:20),            c3=c(5:9),            c4=c(1:5))  print("Sample Dataframe")print (df)  list=as.list(df)  print("After Conversion of Dataframe into list")print(list)
Output:
[1] "Sample Dataframe"
  c1 c2 c3 c4
1 11 16  5  1
2 12 17  6  2
3 13 18  7  3
4 14 19  8  4
5 15 20  9  5
[1] "After Conversion of Dataframe into list"
$c1
[1] 11 12 13 14 15
$c2
[1] 16 17 18 19 20
$c3
[1] 5 6 7 8 9
$c4
[1] 1 2 3 4 5
Example 2:
R
df <- data.frame(sr_num = c(200, 400, 600),                memory=c(128,256,1024),                text = c("Geeks", "for", "Geeks"))  print("Sample Dataframe")print (df)  list=as.list(df)  print("After Conversion of Dataframe into list")print(list)
Output:
[1] "Sample Dataframe"
  sr_num memory  text
1    200    128 Geeks
2    400    256   for
3    600   1024 Geeks
[1] "After Conversion of Dataframe into list"
$sr_num
[1] 200 400 600
$memory
[1]  128  256 1024
$text
[1] Geeks for   Geeks
Levels: for Geeks
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
Ruby | String empty? Method

08 Jan, 2020
empty? is a String class method in Ruby which is used to check whether the string length is zero or not.
Syntax: str.empty?
Parameters: Here, str is the given string which is to be checked.
Returns: It returns true if str has a length of zero, otherwise false.
Example 1:
# Ruby program to demonstrate# the empty? method   # Taking a string and# using the methodputs "checking".empty?puts "method".empty?
Output:
false
false

Example 2:
# Ruby program to demonstrate# the empty? method   # Taking a string and# using the methodputs "".empty?puts ".".empty?
Output:
true
false

Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | Array class find_index() operation
JavaScript | array.flatMap()

29 Oct, 2021
The array.flatMap() is an inbuilt function in JavaScript which is used to flatten the input array element into a new array. This method first of all map every element with the help of mapping function, then flattens the input array element into a new array. Syntax:  
var A = array.flatMap(function callback(current_value, index, Array))
{
    // It returns the new array's elements.
}
Parameters:  
current_value: It is the input array elements.index:It is optional.It is the index of the input element.Array: It is optional.It is used when array map is called.
current_value: It is the input array elements.
index:It is optional.It is the index of the input element.
It is optional.
It is the index of the input element.
Array: It is optional.It is used when array map is called.
It is optional.
It is used when array map is called.
Return Values: It returns a new array whose elements are the return value of the callback function. JavaScript code to show the functionality of the above function: Code #1:
javascript
<script> // Taking input as an array A having some elements.var A = [ 1, 2, 3, 4, 5 ]; // Mapping with map function.b = A.map(x => [x * 3]);document.write(b); // Mapping and flatting with flatMap() function.c = arr1.flatMap(x => [x * 3]);document.write(c); // Mapping and flatting with flatMap() function.d = arr1.flatMap(x => [[ x * 3 ]]);document.write(d);</script>
Output:  
[[3], [6], [9], [12], [15]]
[3, 6, 9, 12, 15]
[[3], [6], [9], [12], [15]]
Code #2: This flatting can also be done with the help of reduce and concat.  
javascript
<script> // Taking input as an array A having some elements.var A = [ 1, 2, 3, 4, 5 ];array.flatMap(x => [x * 3]); // is equivalent tob = A.reduce((acc, x) => acc.concat([ x * 3 ]), []);document.write(b);</script>
Output:  
[3, 6, 9, 12, 15]
Supported Browser:
Google Chrome 69 and above
Edge 79 and above
Firefox 62 and above
Opera 56 and above
Safari 12 and above
Note: This function is available in Firefox Nightly only. 
ysachin2314
javascript-array
javascript-math
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
Lodash _.groupBy() Method
How to convert an Integer Into a String in PHP ?

30 Apr, 2021
The PHP strval() function is used to convert an Integer Into a String in PHP. There are many other methods to convert an integer into a string. 
In this article, we will learn many methods.
Methods:
Using strval() function.
Using inline variable parsing.
Using explicit Casting.
Method 1: Using strval() function.
Note:  The strval() function is an inbuilt function in PHP and is used to convert any scalar value (string, integer, or double) to a string. We cannot use strval() on arrays or on object, if applied then this function only returns the type name of the value being converted.
Syntax:
strval( $variable ) 
Return value: This function returns a string. This string is generated by typecasting the value of the variable passed to it as a parameter.
Example: 
PHP
<?php    $var_name = 2;  // converts integer into string$str =  strval($var_name);  // prints the value of above variable as a stringecho "Welcome $str GeeksforGeeks";  ?>
Welcome 2 GeeksforGeeks
Method 2: Using Inline variable parsing.
Note: When you use Integer inside a string, then the Integer is first converted into a string and then prints as a string.
Syntax: 
$integer = 2;
echo "$integer";
Example:
PHP
<?php    $var_name = 2;    // prints the value of above variable// as a stringecho "Welcome $var_name GeeksforGeeks";  ?>
Welcome 2 GeeksforGeeks
Method 3: Using Explicit Casting.
Note: Explicit Casting is the explicit conversion of data type because the user explicitly defines the data type in which he wants to cast. We will convert Integer into String.
Syntax:
$str = (string)$var_name
Example:
PHP
<?php    $var_name = 2;  //Typecasting Integer into string$str = (string)$var_name;  // prints the value of above variable as a stringecho "Welcome $str GeeksforGeeks";  ?>
Welcome 2 GeeksforGeeks
 
PHP-function
PHP-Questions
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
PHP Cookies
How to generate PDF file using PHP ?
How to pass variables and data from PHP to JavaScript ?
PHP | strtotime() Function
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
Python | Ways to concatenate boolean to string

29 Jun, 2019
Given a string and a boolean value, write a Python program to concatenate the string with a boolean value, given below are few methods to solve the task.
Method #1: Using format()
# Python code to demonstrate # to concatenate boolean value# with string  # Initialising string and boolean valueini_string = "Facts are"value = True  # Concatenate using formatres = str(ini_string+" {}").format(value)  # Printing resultant stringprint ("Resultant String : ", res)
Resultant String :  Facts are True

 Method #2: Using str
# Python code to demonstrate # to concatenate boolean value# with string  # Initialising string and boolean valueini_string = "Facts are"value = True  # Concatenate using strres = ini_string +" "+str(value)  # Printing resultant stringprint ("Resultant String : ", res)           
Resultant String :  Facts are True

 Method #3: Using %s
# Python code to demonstrate # to concatenate boolean value# with string  # Concatenate using % sanswer = Trueres = "Facts are %s" %answer  # Printing resultant stringprint ("Resultant String : ", res)           
Resultant String :  Facts are True

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 Pygame on Windows ?

05 Oct, 2021
In this article, we will learn how to Install PyGame module of Python on Windows. PyGame is a library of python language. It is used to develop 2-D games and is a platform where you can set python modules to develop a game. It is a user-friendly platform that helps to build games quickly and easily. 
In order to install Pygame, Python must be installed already in your system. To check whether Python is installed or not in your system, open the command prompt and give the command as shown below.
If this command runs successfully, and we are able to get a Python version then we are good to go. Otherwise, we have to install Python in our system, to do this refer How to install Python on Windows?
PIP is a tool that is used to install python packages. PIP is automatically installed with Python 2.7. 9+ and Python 3.4+. Open the command prompt and enter the command shown below to check whether pip is installed or not. 
Note: Refer to How to install PIP on Windows ? for detailed information.
To install Pygame, open the command prompt and give the command as shown below:
pip install pygame
Pygame is successfully installed as shown in the image above.
Now open a new terminal and import the Pygame library to see whether it is working fine or not in our system. The library is imported successfully means we got success.
In this way, we can install the pygame module in Python.
how-to-install
Picked
Python-PyGame
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install and Use NVM on Windows?
Installation of Node.js on Windows
How to Install and Run Apache Kafka on Windows?
How to Install FFmpeg on Windows?
How to Install Flutter on Visual Studio Code?
Iterate over a list in Python
Read JSON file using Python
Python map() function
How to iterate through Excel rows in Python?
Taking input in Python
Simple Input/Output Program in MATLAB - GeeksforGeeks

20 Aug, 2020
Let us see how to input and output data in MATLAB.
Syntax : input(PROMPT, “s”)
Parameters :
PROMPT : text prompted
“s” : optional, to input a string
Returns : the data entered
The input() function is used to input data in MATLAB.Example :
% entering an integerinput("Enter an integer : ")  % entering a stringinput("Enter a string : ", "s")
Output :
Enter an integer : 10
ans =  10
Enter a string : GeeksforGeeks
ans = GeeksforGeeks

Syntax : display(OBJ)
Parameters :
OBJ : the object to be displayed
Returns : Nothing
The display() function is used to output data in MATLAB.
Example :
% output a stringdisplay("GeeksforGeeks")  % output a variablevar = 10;display(var)
Output :
GeeksforGeeks
var =  10

MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Markov Decision Process
Fuzzy Logic | Introduction
Q-Learning in Python
Principal Component Analysis with Python
Basics of API Testing Using Postman
ML | What is Machine Learning ?
OpenCV - Overview
Deep Learning | Introduction to Long Short Term Memory
Getting Started with System Design
Python | Pandas dataframe.equals() - GeeksforGeeks

20 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.equals() function is used to determine if two dataframe object in consideration are equal or not. Unlike dataframe.eq() method, the result of the operation is a scalar boolean value indicating if the dataframe objects are equal or not.
Syntax: DataFrame.equals(other)
Parameters:other : DataFrame
Returns: Scalar : boolean value
Example #1: Use equals() function to find the result of comparison between two different dataframe objects.
# importing pandas as pdimport pandas as pd  # Creating the first dataframe df1 = pd.DataFrame({"A":[1,5,7,8],                  "B":[5,8,4,3],                  "C":[10,4,9,3]})  # Creating the second dataframedf2 = pd.DataFrame({"A":[5,3,6,4],                  "B":[11,2,4,3],                  "C":[4,3,8,5]})  # Print the first dataframedf1  # Print the second dataframedf2
Let’s find the result of comparison between both the data frames.
# To find the comparison resultdf1.equals(df2)
Output :
The output is False because the two dataframes are not equal to each other. They have different elements. 
Example #2: Use equals() function to test for equality between two data frame object with NaN values.Note : NaNs in the same location are considered equal.
# importing pandas as pdimport pandas as pd  # Creating the first dataframedf1 = pd.DataFrame({"A":[1,2,3],                  "B":[4,5,None],                  "C":[7,8,9]})  # Creating the second dataframedf2 = pd.DataFrame({"A":[1,2,3],                  "B":[4,5,None],                  "C":[7,8,9]})  # Print the first dataframedf1  # Print the second dataframedf2
Let’s perform comparison operation on both the dataframes.
# To find the comparison between two dataframesdf1.equals(df2)
Output :
The output scalar boolean value. True indicates that both the dataframes has equal values in the corresponding cells.
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.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
std::find_if , std::find_if_not in C++ - GeeksforGeeks

28 Apr, 2022
std :: find_if
Returns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns true. If no such element is found, the function returns last. Function Template :
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

first, last :range which contains all the elements between first
and last, including the element pointed by first but
not the element pointed by last.

pred : Unary function that accepts an element in the range
as argument and returns a value in boolean.

Return value :
Returns an iterator to the first element in the range
[first, last) for which pred(function) returns true. If
no such element is found, the function returns last.
std :: find_if_not
Returns an iterator to the first element in the range [first, last) for which pred(Unary Function) returns false. If no such element is found, the function returns last. Function Template :
InputIterator find_if_not (InputIterator first, InputIterator last, UnaryPredicate pred);

Return value :
Returns an iterator to the first element in the range
[first, last) for which pred(function) returns false.
CPP
// CPP program to illustrate// std::find_if and std::find_if_not#include <bits/stdc++.h> // Returns true if argument is oddbool IsOdd(int i){    return i % 2;} // Driver codeint main(){    std::vector<int> vec{ 10, 25, 40, 55 };     // Iterator to store the position of element found    std::vector<int>::iterator it;     // std::find_if    it = std::find_if(vec.begin(), vec.end(), IsOdd);    std::cout << "The first odd value is " << *it << '\n';         // Iterator to store the position of element found        std::vector<int>::iterator ite;     // std::find_if_not    ite = std::find_if_not(vec.begin(), vec.end(), IsOdd);     std::cout << "The first non-odd(or even) value is " << *ite << '\n';         return 0;}
Output:
The first odd value is 25
The first non-odd(or even) value is 10
Related Articles: 
std::search
std::find
std::nth_element
std::find_end
This article is contributed by Sachin Bisht. 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.
tomsaalex
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
list unique() in C++ STL - GeeksforGeeks

04 Feb, 2021
list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list. It works only on sorted list.
Syntax: 
list_name.unique(BinaryPredicate name)
Parameters:  The function accepts a single and optional parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax: 
bool name(data_type a, data_type b);
Return value: This function does not return anything.
Below is the implementation of above function: 
CPP
// C++ program to illustrate the// unique() function#include <bits/stdc++.h>using namespace std; // Function for binary_predicatebool compare(double a, double b){    return ((int)a == (int)b);} // Driver codeint main(){    list<double> list = { 2.55, 3.15, 4.16, 4.16,                          4.77, 12.65, 12.65, 13.59 };     cout << "List is: ";           //sort the list    list.sort();     // unique operation on list with no parameters    list.unique();     // starts from the first element    // of the list to the last    for (auto it = list.begin(); it != list.end(); ++it)        cout << *it << " ";     // unique operation on list with parameter    list.unique(compare);     cout << "\nList is: ";     // starts from the first element    // of the list to the last    for (auto it = list.begin(); it != list.end(); ++it)        cout << *it << " ";     return 0;}
List is: 2.55 3.15 4.16 4.77 12.65 13.59 
List is: 2.55 3.15 4.16 12.65 13.59 
syvs
pk1853894
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Bitwise Operators in C/C++
Virtual Function in C++
Templates in C++ with Examples
Constructors in C++
Operator Overloading in C++
Socket Programming in C/C++
Object Oriented Programming in C++
Copy Constructor in C++
jQuery UI Draggable revert Option - GeeksforGeeks

10 Mar, 2021
The jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Draggable revert Option is used to set the revert property of an element. If this option is set to true the helper element to be used for dragging display.
Syntax:
$( ".selector" ).draggable({
    revert: true
});
CDN Link: First, add jQuery UI scripts needed for your project.
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css”><script src=”//code.jquery.com/jquery-1.12.4.js”></script><script src=”//code.jquery.com/ui/1.12.1/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en">  <head>    <meta charset="utf-8">    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">    <script src="//code.jquery.com/jquery-1.12.4.js">    </script>    <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js">    </script>    <style>        h1 {            color: green;        }          #div_element {            width: 150px;            height: 150px;            background: green;            display: flex;            justify-content: center;            align-items: center;            text-align: center;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h3>jQuery UI Draggable revert Option</h3>      <div id="div_element">Div content</div>      <script>        $(function () {            $("#div_element").draggable({                revert: true            });        });    </script></body>  </html>
Output:
Reference:https://api.jqueryui.com/draggable/#option-revert
jQuery-UI
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
wxPython – change size of Button

26 Jun, 2020
In this article we are going to lean about SetSize() function associated with wx.Button class of wxPython. SetSize() function is simply used to change the size of the button present in the frame. SetSize function takes a wxSize argument to change the size of button.
Syntax: wx.Button.SetSize(self, size)
Parameters:
Code Example:
import wx    class Example(wx.Frame):      def __init__(self, *args, **kwargs):        super(Example, self).__init__(*args, **kwargs)        self.InitUI()      def InitUI(self):        self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)          # create parent panel for button        self.pnl = wx.Panel(self)          # create button at point (20, 20)        self.st = wx.Button(self.pnl, id = 1, label ="Button", pos =(20, 20),                                          size =(300, 40),  name ="button")          # change size of button        self.st.SetSize((100, 50))          self.SetSize((350, 250))        self.SetTitle('wx.Button')        self.Centre()  def main():    app = wx.App()    ex = Example(None)    ex.Show()    app.MainLoop()    if __name__ == '__main__':    main()
Output Window:
Python wxPython-Button
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.