code-rag-bench/online-tutorials huggingface dataset:
Passing a function as a parameter in JavaScript - GeeksforGeeks

02 May, 2019
Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. Below examples describes to passing a function as a parameter to another function.
Example 1: This example passes a function geeks_inner to the function geeks_outer as an argument.
<!DOCTYPE html> <html>     <head>         <title>             JavaScript | Pass a function as parameter         </title>     </head>           <body style = "text-align:center;">                   <h1 style = "color:green;" >             GeeksForGeeks         </h1>                   <p>             Passing function as arguments.         </p>                   <!-- Function call after clicking the button -->        <button onclick = "geeks_outer(geeks_inner)">             Click Here         </button>                       <script>             function geeks_inner(value){                return 'hello User!';            }            function geeks_outer(func){                alert(func());            }        </script>     </body> </html>                    
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example passes a function geeks_inner alongwith a argument ‘Geeks!’ to the function geeks_outer as a argument.
<!DOCTYPE html> <html>     <head>         <title>             JavaScript | Pass a function as parameter         </title>     </head>               <body style = "text-align:center;">                   <h1 style = "color:green;" >             GeeksForGeeks         </h1>               <p>             Passing function as arguments.         </p>                               <button onclick = "geeks_outer('Geeks!', geeks_inner)">             Click Here         </button>                           <!-- Script to uses function call using            function as argument -->        <script>             function geeks_inner(value){                return 'hello '+value;            }            function geeks_outer(a, func){                alert(func(a));        }                 </script>     </body> </html>                    
Output:
Before clicking on the button:
After clicking on the button:
javascript-functions
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to change color of PNG image using CSS?

12 Feb, 2019
Given an image and the task is to change the image color using CSS. Use filter function to change the png image color. Filter property is mainly used to set the visual effect to the image. There are many property value exist to the filter function.
filter: none|blur()|brightness()|contrast()|drop-shadow()|grayscale()
        |hue-rotate()|invert()|opacity()|saturate()|sepia()|url();
Example 1: This example use grayscale filter to change the colored image into grayscale image.
<!-- HTML code to change the png image color         using filter property --><!DOCTYPE html> <html>     <head>         <title>Convert into grayscale image</title>         <style>             img {                 filter: grayscale(10);             }         </style>     </head>           <body>         <h2>Grayscale Image</h2>         <img src= "https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png"        width="500px" height="250px" alt="filter applied" />     </body> </html> 
Output:Original Image:After applying filter:
Example 2: This example use many filter to the image.
<!-- HTML code to change the png image color         using filter property --><!DOCTYPE html> <html>     <head>         <title>Convert image into different color</title>         <style>             img {                 width:40%;                float:left;            }            .image1 {                filter: invert(100%);            }            .image2 {                filter: sepia(100%);               }        </style>     </head>           <body>         <img class = "image1" src= "https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png"        width="500px" height="250px" alt="filter applied" />                   <img class = "image2" src= "https://media.geeksforgeeks.org/wp-content/uploads/interview-preparation-2.png"        width="500px" height="250px" alt="filter applied" />     </body> </html> 
Output:
CSS-Misc
Picked
Web-Programs
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the color of an image to black and white using CSS ?

30 Sep, 2021
The approach of this article is to change the color of an image to black and white using a filter property in CSS. It is used to set the visual effect of an element. This property is mostly used in image content.  
Basically we use a grayscale() method to convert the element colors into black and white. The grayscale 0% indicates the original element and 100% indicate completely grayscale element.  
Syntax:  
filter: grayscale(100%)
Example:  
HTML
<!DOCTYPE html><html>  <head>    <title>        How to change the color of an images         to black and white using CSS?    </title>      <style>        .gfg {            -webkit-filter: grayscale(100%);            filter: grayscale(100%);        }    </style></head>  <body>    <h2>GeeksForGeeks</h2>      <h2>        How to change the color of an images         to black and white using CSS?    </h2>      <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png" >    <br>      <b>After Convert to Black and White</b> <br>    <img class="gfg" src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20191121162913/s11.png"></body>  </html>
Output:
CSS-Properties
CSS-Questions
HTML-Questions
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
How to auto-resize an image to fit a div container using CSS?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Difference between ALTER and UPDATE Command in SQL

14 Aug, 2020
1. ALTER Command :
ALTER SQL command is a DDL (Data Definition Language) statement. ALTER is used to update the structure of the table in the database (like add, delete, modify the attributes of the tables in the database).
Syntax :
// add a column to the existing table

ALTER TABLE tableName

ADD columnName columnDefinition;

 

// drop a column from the existing table

ALTER TABLE tableName

DROP COLUMN columnName;



// rename a column in the existing table

ALTER TABLE tableName

RENAME COLUMN olderName TO newName;



// modify the datatype of an already existing column in the table

ALTER TABLE table_name

ALTER COLUMN column_name column_type;


2. UPDATE Command :
UPDATE SQL command is a DML (Data manipulation Language) statement. It is used to manipulate the data of any existing column. But can’t be change the table’s definition.
Syntax :
// table name that has to update

UPDATE tableName

// which columns have to update

SET column1 = value1, column2 = value2, ...,columnN=valueN.

// which row you have to update

WHERE condition


Note :  Without WHERE clause, all records in the table will be updated.
Difference Between ALTER and UPDATE Command in SQL :  
 
badger_666
DBMS-SQL
SQL-basics
DBMS
Difference Between
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of B-Tree
SQL | Views
SQL Interview Questions
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Linked List Data Structure - GeeksQuiz

29 Sep, 2020
void fun1(struct node* head)
{
  if(head == NULL)
    return;
  
  fun1(head->next);
  printf("%d  ", head->data);
}

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
smatch | Regex (Regular Expressions) in C++

04 Sep, 2018
smatch is an instantiation of the match_results class template for matches on string objects.Functions that can be called using smatch:str(), position(), and length() member functions of the match_results object can be called to get the text that was matched, or the starting position and its length of the match relative to the subject string.
Call these member functions without a parameter or with 0 as the parameter to get the overall regex match.
Call them passing 1 or greater to get the match of a particular capturing group.
The size() member function indicates the number of capturing groups plus one for the overall match.
Thus you can pass a value up to size()-1 to the other three member functions(str(), position(), length() ).
What is capturing group ?Examples:
Example-1:
Suppose you create a regex object like : regex re("(geeks)(.*)") 
Here no of capturing group is = 2 
[ one is "geeks" and second is any character after "geeks" ].

Example-2:
regex re("a(b)c")
Here no of capturing group is = 1[ 'b' is the capturing group].
whatever within '(' and ')' braces is treated as capturing group.

Below is the program to show the working of smatch:
#include <bits/stdc++.h>using namespace std;int main(){    string sp("geeksforgeeks");    regex re("(geeks)(.*)");      // flag type for determining the matching behavior    // && here it is for matches on strings.    smatch match;      // we can use member function on match    // to extract the matched pattern.    if (regex_search(sp, match, re) == true) {          // The size() member function indicates the        // number of capturing groups plus one for the overall match        // match size = Number of capturing group + 1        // (.*) which "forgeeks" ).        cout << "Match size = " << match.size() << endl;          // Capturing group is index from 0 to match_size -1         // .....here 0 to 2        // pattern at index 0 is the overall match "geeksforgeeks"        // pattern at index 1 is the first capturing group "geeks"        // pattern at index 2 is the 2nd capturing group "forgeeks"          cout << "Whole match : " << match.str(0) << endl;        cout << "First capturing group is '" << match.str(1)             << "' which is captured at index " << match.position(1)             << endl;        cout << "Second capturing group is '" << match.str(2)             << "' which is captured at index " << match.position(2)             << endl;    }    else {        cout << "No match is found" << endl;    }    return 0;}
Match size = 3
Whole match : geeksforgeeks
First capturing group is 'geeks' which is captured at index 0
Second capturing group is 'forgeeks' which is captured at index 5

CPP-Library
CPP-regex
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Smallest K digit number divisible by X

22 Jun, 2022
Integers X and K are given. The task is to find smallest K-digit number divisible by X. Examples:
Input : X = 83, K = 5
Output : 10043
10040 is the smallest 5 digit
number that is multiple of 83.

Input : X = 5, K = 2
Output : 10
An efficient solution would be :
Compute MIN : smallest K-digit number (1000...K-times)
If, MIN % X is 0, ans = MIN
else, ans = (MIN + X) - ((MIN + X) % X))
This is because there will be a number in 
range [MIN...MIN+X] divisible by X.
Python3
# Python code to find smallest K-digit # number divisible by X def answer(X, K):         # Computing MAX    MIN = pow(10, K-1)         if(MIN%X == 0):        return (MIN)         else:        return ((MIN + X) - ((MIN + X) % X))      X = 83;K = 5; print(answer(X, K)); # Code contributed by Mohit Gupta_OMG <(0_o)>
Output :
10043
Time Complexity: O(logk)
Auxiliary Space: O(1) 
Please refer complete article on Smallest K digit number divisible by X for more details!
chandramauliguptach
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if an array is descending, ascending or not sorted in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers. The function
should check whether the numbers in the array are in increasing order, or in decreasing order or
in no specific order.
If the array contains only one element then we should return a message saying not enough
elements.
And if the array has all the elements equal, we should return a message saying all elements are equal.
The code for this will be −
const arr1 = [7, 2, 1, 3, 2, 1];
const arr2 = [1, 1, 2, 3, 7, 7];
const determineOrder = arr => {
   if(arr.length < 2){
      return 'not enough items';
   };
   let ascending = null;
   let nextArr = arr.slice(1);
   for(var i = 0; i < nextArr.length; i++) {
      if(nextArr[i] === arr[i]){
         continue;
      }else if(ascending === null) {
         ascending = nextArr[i] > arr[i];
      }else if (ascending !== nextArr[i] > arr[i]){
         return 'unsorted';
      };
   }
   if(ascending === null){
      return 'all items are equal';
   };
   return ascending ? 'ascending' : 'descending';
};
console.log(determineOrder(arr1));
console.log(determineOrder(arr2));
console.log(determineOrder([1, 1, 1, 1]));
console.log(determineOrder([7, 2, 2, 1]));
The output in the console −
unsorted
ascending
all items are equal
descending
C++ program for Find sum of odd factors of a number

Given with a positive integer and the task is to generate the odd factors of a number and finding out the sum of given odd factors.
Input-: number = 20
Output-: sum of odd factors is: 6
Input-: number = 18
Output-: sum of odd factors is: 13
So, result = 1 + 5 = 6
Approach used in the below program is as follows −
Input the number for calculating the sum of odd factors of that number
Ignore the digit 0 and 2 because both are even digits and store the digit 1 because it is an odd digit
Start the loop from 3 till square root of a number
Traverse till number % i is returning 0 and keep dividing the number with the value of i
In the loop keep setting the value of temporary variable to temp = temp * i
Set the total to total + temp
Return the value of final res variable and print the result
START
Step 1-> Declare function to calculate sum of odd factors
   int sum(int num)
   declare int res = 1
   Loop While(num % 2 == 0)
      set num = num / 2
   End
   Loop For int i = 3 and i <= sqrt(num) and i++
      declare int count = 0 and total = 1
      declare int temp = 1
      Loop while (num % i == 0)
         count++
         set num = num / i
         set temp *= i
         set total += temp
      End
      set res = res*total
   End
   IF (num >= 2)
      set res *= (1 + num)
   End
   return res
Step 2-> In main()
   Declare int num = 20
   call sum(num)
STOP
#include <bits/stdc++.h>
using namespace std;
//calculate sum of odd factors
int sum(int num) {
   int res = 1;
   while (num % 2 == 0)
   num = num / 2;
   for (int i = 3; i <= sqrt(num); i++) {
      int count = 0, total = 1 ;
      int temp = 1;
      while (num % i == 0) {
         count++;
         num = num / i;
         temp *= i;
         total += temp;
      }
      res = res*total;
   }
   if (num >= 2)
   res *= (1 + num);
   return res;
}
int main() {
   int num = 20;
   cout<<"sum of odd factors is : ";
   cout <<sum(num);
   return 0;
}
sum of odd factors is : 6
Constructor Overloading in C++

As we know function overloading is one of the core feature of the object oriented languages. We can use the same name of the functions; whose parameter sets are different. Here we will see how to overload the constructors of C++ classes. The constructor overloading has few important concepts.
Overloaded constructors must have the same name and different number of arguments
The constructor is called based on the number and types of the arguments are passed.
We have to pass the argument while creating objects, otherwise the constructor cannot understand which constructor will be called.
 Live Demo
#include <iostream>
using namespace std;

class Rect{
   private:
   int area;
   public:
   Rect(){
      area = 0;
   }
   Rect(int a, int b){
      area = a * b;
   }
   void display(){
      cout << "The area is: " << area << endl;
   }
};

main(){
   Rect r1;
   Rect r2(2, 6);
   r1.display();
   r2.display();
}
The area is: 0
The area is: 12
Relational and Logical Operators in C

Relational operators are used to compare two values in C language. It checks the relationship between two values. If relation is true, it returns 1. However, if the relation is false, it returns 0.
Here is the table of relational operators in C language
Here is an example of relational operator in C language
 Live Demo
#include <stdio.h>
int main() {
   int x = 10;
   int y = 28;
   if(x==y)
   printf("Both variables are equal\n");
   if(x>y)
   printf("x is greater than y \n");
   if(x<y)
   printf("x is less than y \n");
   if(x!=y)
   printf("x is not equal to y \n");
   if(x<=y)
   printf("x is lesser or equal to y\n");
   if(x>=y)
   printf("x is greater or equal to y \n");
   return 0;
}
x is less than y
x is not equal to y
x is lesser or equal to y
Logical operators are used to perform logical operations. It returns 0 or 1 based on the result of condition, whether its true or false. These operators are used for decision making in C language.
Here is the table of logical operators in C language,
Here is an example of logical operators in C language,
 Live Demo
#include <stdio.h>
int main() {
   int x = 10;
   int y = 28;
   int a = 15;
   int b = 20;
   if(x<y && a==b)
   printf("x is less than y AND a is equal to b\n");
   if(x<y || a==b)
   printf("x is less than y OR a is equal to b\n");
   if(!x)
   printf("x is zero\n");
   return 0;
}
x is less than y OR a is equal to b
endl vs \n in C++

09 Jun, 2022
endl and \n both seem to do the same thing but there is a subtle difference between them. 
cout << endl inserts a new line and flushes the stream(output buffer), whereas cout << “\n” just inserts a new line.
Therefore, cout << endl; can be said equivalent to cout << ‘\n’ << flush; 
Some other differences between endl and \n are:  
endl
 \n 
Note: cout << “\n” looks performance wise better but in real cout << endl is much better in C++; As it doesn’t occupies any memory and also if flushing of stream is required.
Example 1: 
We can use endl in C++ but not in C. So endl runs well in C++ but if we use C, it runs error.
C++
C
#include <iostream>using namespace std; int main() {     cout << "GFG!"<<endl;  //We can use endl in C++ and it doesn't occupy any memory      cout << "GFG!";    return 0;} //Code submitted by Susobhan AKhuli
#include <stdio.h> int main() {     // code      //We cann't use endl in C      printf("GFG!",endl);  //So it runs error      printf("GFG!");    return 0;} //Code submitted by Susobhan AKhuli
Output:
GFG!
GFG!
Example 2:
We can use “\n” in both C and C++ but it occupies 1 byte memory.
C++
C
#include <iostream>using namespace std; int main() {     cout << "GFG!"<<"\n";      cout << "GFG!";    return 0;}//Code submitted by Susobhan AKhuli
#include <stdio.h> int main() {     // code      printf("GFG!\n");      printf("GFG!");    return 0;} //Code submitted by Susobhan AKhuli
Output:
GFG!
GFG!
This article is contributed by Akshat Saxena. 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.
Ibms
Akanksha_Rai
SharatPaul
ankit10409
anshikajain26
joydeephalder
susobhanakhuli
CBSE - Class 11
cpp-input-output
school-programming
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
QlikView - Set Analysis

QlikView's Set Analysis feature is used to segregate the data in different sheet objects into
many sets and keeps the values unchanged in some of them. In simpler terms, it creates an option to not associate some sheet objects with others while the default behavior is all sheet objects get associated with each other. This helps in filtering the data in one sheet object and seeing the corresponding result in others, while the sheet object chosen as a different set displays values as per its own filters.
Let us consider the following input data, which represents the sales figure of different product lines and product categories.
Product_Line,Product_category,Month,Value
Arts & Entertainment,Hobbies & Creative Arts,Jan,5201
Arts & Entertainment,Paintings,Feb,8451
Arts & Entertainment,Musical Instruments,Jan,1245
Baby & Toddler,Diapering,Mar,1247
Baby & Toddler,Toys,Dec,257
Apparel & Accessories,Clothing,Feb,574
Apparel & Accessories,Costumes & Accessories,Apr,1204
Arts & Entertainment,Musical Instruments,Apr,3625
Baby & Toddler,Diapering,Apr,1281
Apparel & Accessories,Clothing,Jul,2594
Arts & Entertainment,Paintings,Sep,6531
Baby & Toddler,Toys,May,7421
Apparel & Accessories,Clothing,Aug,2541
Arts & Entertainment,Paintings,Oct,2658
Arts & Entertainment,Musical Instruments,Mar,1185
Baby & Toddler,Diapering,Jun,1209

The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the "Table Files" option from the "Data from Files" tab and browse for the file containing the above data. A screen appears as shown below.
Choose all the fields available to create a table box using the menu option Layout → New
Sheet Objects → Table Box and a list box containing the month’s field using the menu option Layout → New Sheet Objects → List Box. Also, create a straight table chart showing the total sales under each product category.
Now we can observe the association between these three sheet objects by selecting some values in one of them. Let us select the month Apr and Jan from the Month list Box. We can see the change in values in the Table Box and chart showing the related values.
Next, we clone the sales sum chart to produce a new set of data not associated with other sheet objects. Right click on the chart Sales Sum and click on the option Clone as shown below. Another copy of the same chart appears in the QlikView document.
Next, we choose the second copy of the chart Sales Sum and right click it to get the chart properties. We create an expression called Sales values writing the formula under the Definition tab as shown below.
On completing the above given steps, we find that when we select the month June we get the associated values in the Table Box and Sales Sum chart. However, the April sales does not change as it is based on the data from the set expression.
Matplotlib.figure.Figure.tight_layout() in Python

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The tight_layout() method figure module of matplotlib library is used to automatically adjust subplot parameters to give specified padding.
Syntax: tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None)
Parameters: This method accept the following parameters that are discussed below:
renderer : This parameter is the subclass of RendererBase.
pad: This parameter is used for padding between the figure edge and the edges of subplots, as a fraction of the font size.
h_pad, w_pad: These parameter are used for padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
rect: This parameter is rectangle in the normalized figure coordinate that the whole subplots area will fit into.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.tight_layout() function in matplotlib.figure:
Example 1:
import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import EngFormatter     prng = np.random.RandomState(19680801)   xs = np.logspace(1, 9, 100)ys = (0.8 + 0.4 * prng.uniform(size = 100)) * np.log10(xs)**2   plt.xscale('log')fig = plt.figure()  ax = fig.subplots()   formatter0 = EngFormatter(unit ='Hz')ax.plot(xs, ys)ax.set_xlabel('Frequency')  fig.tight_layout()  fig.suptitle("""matplotlib.figure.Figure.tight_layout()function Example\n\n""", fontweight ="bold")  fig.show()
Output:
Example 2:
import numpy as npimport matplotlib.pyplot as plt     fig, axs = plt.subplots(1, 2)   x = np.arange(0.0, 2.0, 0.02)  y1 = np.sin(2 * np.pi * x)y2 = np.exp(-x)  l1, = axs[0].plot(x, y1)l2, = axs[0].plot(x, y2, marker ='o')   y3 = np.sin(4 * np.pi * x)y4 = np.exp(-2 * x)  l3, = axs[1].plot(x, y3, color ='tab:green')l4, = axs[1].plot(x, y4, color ='tab:red', marker ='o')   fig.legend((l1, l2), ('Line 1', 'Line 2'), 'upper left')fig.legend((l3, l4), ('Line 3', 'Line 4'), 'upper right')  fig.tight_layout()  fig.suptitle("""matplotlib.figure.Figure.tight_layout()function Example\n\n""", fontweight ="bold")fig.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Need of long data type in C

In C or C++, there are four different datatypes, that are used for integer type data. These four datatypes are short, int, long and long long. Each of these datatypes takes different memory spaces. The size varies in different architecture and different operating systems. Sometimes int takes 4-bytes or sometimes it takes 2-bytes. This also happen for the compilers. So we can use cross compilers.
The cross compilers are basically a compiler, which is capable of compiling for a platform other than current platform.
So if we want to compile the following code in 32bit system, and 64-bit system, it will generate different outputs.
#include<stdio.h>
int main() {
   printf("Size of int : %ld Bytes\n", sizeof(int));
   printf("Size of long : %ld Bytes\n", sizeof(long));
   printf("Size of long long : %ld Bytes", sizeof(long long));
}
Size of int : 4 Bytes
Size of long : 4 Bytes
Size of long long : 8 Bytes
So from this example we can easily understand that the long datatype varies from compiler. So what is the reason behind it?
The CPU calls data from primary memory (RAM) by providing the address of Memory Address Register (MAR). When the location is found, it is transferred to Memory Buffer Register (MBR). The data is stored into the CPU register for further usage. So the size of data bus determines the size of CPU register. For 32-bit system, it can call only 4-byte data at a time. If data is larger than 32bit, then it will take two cycles. So for smaller data it does not make any difference.
Vector of Maps in C++ with Examples

13 Jun, 2022
Map in STL: Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.
Vector in STL: Vector is the same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.
Vector of Maps in STL: Vector of maps can be used to design complex and efficient data structures.
Syntax:
Vector of Ordered Map:vector<map<datatype, datatype> > VM;
Vector of Unordered map:vector<unordered_map<datatype, datatype> > VUM;
Examples:Given a string. The task is to find the frequency of characters up to each index.
C++14
// C++ program to demonstrate the use// of vector of maps#include <bits/stdc++.h>using namespace std; // Function to count frequency// up to each indexvoid findOccurrences(string s){    // Vector of map    vector<map<char, int> > mp(s.length());     // Traverse the string s    for (int i = 0; i < s.length(); i++) {         // Update the frequency        for (int j = 0; j <= i; j++) {            mp[i][s[j]]++;        }    }     // Print the vector of map    for (int i = 0; i < s.length(); i++) {         cout << "Frequency upto "             << "position " << i + 1             << endl;         // Traverse the map        for (auto x : mp[i])            cout << x.first << "-"                 << x.second << endl;    }} // Driver Codeint main(){    // Input string S    string S = "geeks";     // Function Call    findOccurences(S);     return 0;}
Frequency upto position 1
g-1
Frequency upto position 2
e-1
g-1
Frequency upto position 3
e-2
g-1
Frequency upto position 4
e-2
g-1
k-1
Frequency upto position 5
e-2
g-1
k-1
s-1
 
surinderdawra388
simmytarika5
cpp-map
cpp-vector
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Operators in C/C++
vector erase() and clear() in C++
Inheritance in C++
Substring in C++
The C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining
Python SQLite – Connecting to Database

16 May, 2021
In this article, we’ll discuss how to connect to an SQLite Database using the sqlite3 module in Python.
Connecting to the SQLite Database can be established using the connect() method, passing the name of the database to be accessed as a parameter. If that database does not exist, then it’ll be created. 
sqliteConnection = sqlite3.connect('sql.db')
But what if you want to execute some queries after the connection is being made. For that, a cursor has to be created using the cursor() method on the connection instance, which will execute our SQL queries.
cursor = sqliteConnection.cursor()
print('DB Init')
The SQL query to be executed can be written in form of a string, and then executed by calling the execute() method on the cursor object. Then, the result can be fetched from the server by using the fetchall() method, which in this case, is the SQLite Version Number.
query = 'SQL query;'
cursor.execute(query)
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))
Consider the below example where we will connect to an SQLite database and will run a simple query select sqlite_version(); to find the version of the SQLite we are using.
Example:
Python
import sqlite3  try:        # Connect to DB and create a cursor    sqliteConnection = sqlite3.connect('sql.db')    cursor = sqliteConnection.cursor()    print('DB Init')      # Write a query and execute it with cursor    query = 'select sqlite_version();'    cursor.execute(query)      # Fetch and output result    result = cursor.fetchall()    print('SQLite Version is {}'.format(result))      # Close the cursor    cursor.close()  # Handle errorsexcept sqlite3.Error as error:    print('Error occured - ', error)  # Close DB Connection irrespective of success# or failurefinally:        if sqliteConnection:        sqliteConnection.close()        print('SQLite Connection closed')
Output:
Picked
Python-SQLite
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dart – Sort a List

29 Aug, 2021
In Dart programming, the List data type is similar to arrays in other programming languages. A list is used to represent a collection of objects. It is an ordered group of objects. The core libraries in Dart are responsible for the existence of List class, its creation, and manipulation. Sorting of the list depends on the type of list we are sorting i.e. if we are sorting integer list then we can use simple sort function whereas if it is a string list then we use compareTo to sort the list.
An integer list can be sort by the simple sort function.
Example: Sorting an integer list.
Dart
// Main functionmain() {     // Creating List  List<int> geeksforgeeks = [13, 2, -11, 142, -389, 32, 3032, 0];     // Sorting List  geeksforgeeks.sort();     // Printing Sorted List  print(geeksforgeeks);}
Output:
[-389, -11, 0, 2, 13, 32, 142, 3032]
The string is sorted by comparing the length in the sort function.
Example: Sorting a string list.
Dart
// Main functionmain() {     // Creating list of string  List<String> geeksforgeeks = ['one', 'two', 'three', 'four'];     // Sorting string by comparing the length  geeksforgeeks.sort((a, b) => a.length.compareTo(b.length));     // Printing the list  print(geeksforgeeks);}
Output:
[one, two, four, three]
If we use sort without comparing the length then:
Example: Sorting a string list without comparing the length.
Dart
// Main functionmain() {     // Creating list of string  List<String> geeksforgeeks = ['one', 'two', 'three', 'four'];     // Sorting string without  // comparing the length  geeksforgeeks.sort();     // Printing the list  print(geeksforgeeks);}
Output:
[four, one, three, two]
Example: Using the cascades method while sorting the list.
Dart
// Main functionmain() {     // Creating list of string  List<int> geeksforgeeks = [13, 2, -11, 142, -389, 0];     // Sorting string and Printing the list  print(geeksforgeeks..sort());}
Output:
[-389, -11, 0, 2, 13, 142]
surindertarika1234
Dart-List
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Row and Column Widgets
ListView Class in Flutter
Dart Tutorial
Flutter - Stack Widget
Flutter - Search Bar
Container class in Flutter
Operators in Dart
How to improve MongoDB queries with multikey index in array?

For this, use $elemMatch, which is used to query nested objects. Let us create a collection with documents −
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:1,
...          Name:"Chris"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea87bbc41e36cc3caebf")
}
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:2,
...          Name:"David"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea87bbc41e36cc3caec0")
}
> db.demo444.insertOne(
...    {
...       "Information": [{
...          id:3,
...          Name:"Bob"
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78ea88bbc41e36cc3caec1")
}
Display all documents from a collection with the help of find() method −
> db.demo444.find();
This will produce the following output −
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caebf"), "Information" : [ { "id" : 1, "Name" : "Chris" } ] }
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
{ "_id" : ObjectId("5e78ea88bbc41e36cc3caec1"), "Information" : [ { "id" : 3, "Name" : "Bob" } ] }
Following is the query to improve queries with multikey index in array −
> db.demo444.find({
...    "Information":{
...       $elemMatch:{
...          id:2,
...          Name:"David"
...       }
...    }
... })
This will produce the following output −
{ "_id" : ObjectId("5e78ea87bbc41e36cc3caec0"), "Information" : [ { "id" : 2, "Name" : "David" } ] }
Get the value associated with a given key in Java HashMap

Use the get() method to get the value associated with a given key.
Here is our HashMap and its elements −
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("Bag", new Integer(1100));
hm.put("Sunglasses", new Integer(2000));
hm.put("Frames", new Integer(800));
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
To get the associated value. the key is set as a parameter like this −
hm.get("Frames")
Above, the key is Frames and we are fetching the value associated with it.
The following is an example to get the value associated with a given key in Java HashMap −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Bag", new Integer(1100));
      hm.put("Sunglasses", new Integer(2000));
      hm.put("Frames", new Integer(800));
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      // Get a set of the entries
      Set set = hm.entrySet();
      System.out.println("Elements in HashMap...");
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("The value for key Frames in the HashMap = "+hm.get("Frames"));
   }
}
Elements in HashMap...
Frames: 800
Belt: 600
Wallet: 700
Bag: 1100
Sunglasses: 2000

The value for key Frames in the HashMap = 800
PHP - var_dump() Function

The function var_dump() displays structured information (type and value) about one or more expressions/variables.
Arrays and objects are explored recursively with values indented to show structure.
All public, private and protected properties of objects will be returned in the output.
void var_dump ( mixed $value , mixed $values )

value
The expression to dump.
values
Further expressions to dump.
This function returns no value. This function outputs results directly to the browser. The output can be captured using output-control functions and stored to a string.
PHP 4 and above 
Following example demonstrates use of var_dump() −
<?php
   $a = "Welcome TutorialsPoint!";
   var_dump($a);
   echo "<br>";
   $b = array(2,'hello',22.99, array('a','b',2));
   var_dump($b);
?>
This will produce following result −
string(23) "Welcome TutorialsPoint!"
array(4) { 
   [0]=> int(2) 
   [1]=> string(5) "hello" 
   [2]=> float(22.99) 
   [3]=> array(3) { 
      [0]=> string(1) "a" 
      [1]=> string(1) "b" 
      [2]=> int(2) 
   } 
}

Following example demonstrates storing the output of var_dump() to a variable, which can later be manipulated. To execute the example we have used two php functions (output-control functions) ob_start() and ob_get_clean(). ob_start() function turns output buffering on where as ob_get_clean() function gets current buffer contents and delete current output buffer.
<?php
   ob_start();
   var_dump("output var_dump data to a string");
   $out = ob_get_clean();
   echo $out;
   echo("<br>");
   echo substr($out,0,30);
?>
This will produce following result −
string(32) "output var_dump data to a string"
string(32) "output var_dump da


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Python Number asin() Method

Python number  method asin() returns the arc sine of x, in radians.
Following is the syntax for asin() method −
asin(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error.
x − This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will generate an error.
This method returns arc sine of x, in radians.
The following example shows the usage of asin() method.
#!/usr/bin/python
import math

print "asin(0.64) : ",  math.asin(0.64)
print "asin(0) : ",  math.asin(0)
print "asin(-1) : ",  math.asin(-1)
print "asin(1) : ",  math.asin(1)
When we run above program, it produces following result −
asin(0.64) :  0.694498265627
asin(0) :  0.0
asin(-1) :  -1.57079632679
asin(1) :  1.57079632679


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Chef - Environment Variable

Environment variable is a key way to make Chef recipe run on any particular node successfully. There are multiple ways of doing it, either manually setting them up or by using a Shell script. Setting them via recipe is what we need to perform here.
To do this, we need to have a cookbook here we would use test_cookbook and a run list which contains test_cookbook.
Step 1 − Update the default recipe of cookbook with an environment variable.
vipin@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb  
ENV['MESSAGE'] = 'Testing environment variable update with chef !'  
execute 'print value of environment variable $MESSAGE' do 
   command 'echo $MESSAGE > /tmp/message' 
end
Step 2 − Upload the updated cookbook to the server.
vipin@laptop:~/chef-repo $ knife cookbook upload test_cookbook 
Uploading my_cookbook [0.1.0] 

Step 3 − Running the Chef client to create a temp file.
user@server:~$ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-01-25T15:01:57+00:00] INFO: Processing execute[print 
value of environment variable $MESSAGE] action run 
(my_cookbook::default line 11) 
[2013-01-25T15:01:57+00:00] INFO: execute[print value of 
environment variable $MESSAGE] ran successfully 
...TRUNCATED OUTPUT... 

user@server:~$ cat /tmp/message 
Hello from Chef

Ruby exposes the current environment variable via ENV –a hash to read and modify the environment variable.
We can use execute resource to do the same inside the Chef default recipe of cookbook.
mma@laptop:~/chef-repo $ subl cookbooks/test_cookbook/recipes/default.rb  
execute 'print value of environment variable $MESSAGE' do 
   command 'echo $MESSAGE > /tmp/message' 
   environment 'MESSAGE' => 'Hello from the execute resource' 
end 
Note − Setting an environment variable using ENV will make that variable available during the whole Chef run. In contrast, passing it to the execute resource will only make it available for that one command executed by the resource.
 Print
 Add Notes
 Bookmark this page
Returning two values from a function in PHP

Two variables can’t be explicitly returned, they can be put in a list/array data structure and returned.
 Live Demo
function factors( $n ) {
   // An empty array is declared
   $fact = array();
   // Loop through it
   for ( $i = 1; $i < $n; $i++) {
      // Check if i is the factor of
      // n, push into array
      if( $n % $i == 0 )
      array_push( $fact, $i );
   }
   // Return array
   return $fact;
}
// Declare a variable and initialize it
$num = 12;
// Function call
$nFactors = factors($num);
// Display the result
echo 'Factors of ' . $num . ' are: <br>';
foreach( $nFactors as $x ) {
   echo $x . "<br>";
}
This will produce the following output −
Factors of 12 are:
1
2
3
4
6
How to add options to a drop-down list using jQuery?

22 Jan, 2021
Given an HTML document with a drop-down list menu and our task is to add more options to the drop-down list using jQuery.
Approach : To add more option to the existing drop-down list using the append() method :
 var options = {
                val1: 'C#',
                val2: 'PHP'
            };
            var selectOption = $('#programmingLanguage');
            $.each(options, function (val, text) {
                selectOption.append(
                    $('<option></option>').val(val).html(text)
                );
            });
This is a small code snippet that can be used to add an option to an existing list and this code snippet is taken from a demonstration below where val1 and val2 have the option names, programmingLanguage is the id used for the select option, then by using the append() method the new options are merged with the existing list of options.
A detailed explanation of the append() method in JQuery can be found here .
Below is the code for the demonstration of the above approach.
HTML
<!DOCTYPE html><html>  <head>    <script src="https://code.jquery.com/jquery-3.3.1.min.js">    </script>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width">    <title>Add an option to the dropdown list using jquery.</title></head>  <body>    <h1 style="color: green;">GeeksForGeeks</h1>      <p>Programming Languages :</p>      <select id='programmingLanguage'>        <option value="Java" style="color: green;                 font-weight: 700;">Java</option>        <option value="Python" style="color: green;                 font-weight: 700;">Python</option>        <option value="CPP" style="color: green;                 font-weight: 700;">CPP</option>        <option value="C" style="color: green;                 font-weight: 700;">C</option>    </select>      <p> Click to add C# and PHP programming languages</p>      <button onclick="addOption()">Add option</button>    <!--Code to add an option to an existing set of option using jquery-->    <script>        function addOption() {            var options = {                val1: 'C#',                val2: 'PHP'            };            var selectOption = $('#programmingLanguage');            $.each(options, function (val, text) {                selectOption.append(                    $('<option></option>').val(val).html(text)                );            });        }    </script></body>  </html>
Output:
jQuery-Basics
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the value in an input text box using jQuery ?
jQuery | ajax() Method
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | removeAttr() with Examples
jQuery | parent() & parents() with Examples
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 ?