code-rag-bench/online-tutorials huggingface dataset:
C++ Stack Library - size() Function

The C++ function std::stack::size() returns the total number of element present in the stack.
Following is the declaration for std::stack::size() function form std::stack header.
size_type size() const;

None
Returns the number of element present in the stack.
Depends upon underlying container.
Constant i.e. O(1)
The following example shows the usage of std::stack::size() function.
#include <iostream>
#include <stack>

using namespace std;

int main(void) {
   stack<int> s;

   cout << "Initial size of stack = " << s.size() << endl;

   for (int i = 0; i < 5; ++i)
      s.push(i + 1);

   cout << "Stack size after push operation = " << s.size() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Initial size of stack = 0
Stack size after push operation = 5

 Print
 Add Notes
 Bookmark this page
C++ Library - <array>

Arrays are sequence container of fixed size. Container is a objects that holds data of same type. Sequence containers store elements strictly in linear sequence.
The container class uses implicit constructor to allocate required memory statically. Memory is allocated at the compile time, hence array size cannot shrink or expand at runtime. All elements inside array are located at contiguous memory locations.
Below is definition of std::array from <array> header file.
template < class T, size_t N >
class array;

T − Type of the element contained.
T may be substituted by any other data type including user-defined type.
T − Type of the element contained.
T may be substituted by any other data type including user-defined type.
N − Size of the array.
Zero sized arrays are also valid. In that case array.begin() and array.end() points to same location. But behavior of calling front() or back() is undefined.
N − Size of the array.
Zero sized arrays are also valid. In that case array.begin() and array.end() points to same location. But behavior of calling front() or back() is undefined.
Following member types can be used as parameters or return type by member functions.
Below is list of all methods from <array> header.
Returns a reference to the element present at location N in given array container.
Returns a reference to the last element of the array container.
Returns an iterator which points to the start of the array.
Returns a constant iterator which points to the start of the array.
Returns a constant iterator which points to the past-end element of array.
Returns a constant reverse iterator pointing to the last element of the array.
Returns a constant reverse iterator which points to the past-end.
Return a pointer pointing to the first element of the array container.
Tests whether size of array is zero or not.
Returns an iterator which points to the past-end element of array.
Sets given value to all elements of array.
Returns a reference to the first element of the array container.
Returns the maximum number of elements that can be held by array container.
Returns a reference to the element present at location N in a given array container.
Returns a reverse iterator pointing to the last element of the array.
Returns a reverse iterator which points to the theoretical element preceding to first element of the array.
Returns the number of elements present in the array.
Swap the contents of the two array.
Returns reference to the Ith element of the array container.
Tests whether two containers are identical or not
Tests whether two containers are identical or not
Tests whether first array container is less than second or not.
Tests whether first array container is less than or equal to second or not.
Tests whether first array container is greater than second or not.
Tests whether first array container is greater than or equal to second or not.
Provides compile-type indexed access to the type of the elements of the array using tuple-like interface.
Returns the total number of elements present in the container.
 Print
 Add Notes
 Bookmark this page
Password validation in Python

It is a general requirement to have a reasonably complex password. In this article we will see how to validate if a given password meats certain level of complexity. For that will use the regular expression module known as re.
First we create a regular expression which can satisfy the conditions required to call it a valid password. Then we e match the given password with the required condition using the search function of re. In the below example the complexity requirement is we need at least one capital letter, one number and one special character. We also need the length of the password to be between 8 and 18.
 Live Demo
import re

pswd = 'XdsE83&!'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!#%*?&]{8,18}$"

# compiling regex
match_re = re.compile(reg)

# searching regex
res = re.search(match_re, pswd)

# validating conditions
if res:
   print("Valid Password")
else:
   print("Invalid Password")
Running the above code gives us the following result −
Valid Password
In this example we e use a password which does not meet all the required conditions. For example, no numbers in the password. In that case the program indicates it it as invalid password.
 Live Demo
import re

pswd = 'XdsEfg&!'
reg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?& ])[A-Za-z\d@$!#%*?&]{8,18}$"

# compiling regex
match_re = re.compile(reg)

# searching regex
res = re.search(match_re, pswd)

# validating conditions
if res:
   print("Valid Password")
else:
   print("Invalid Password")
Running the above code gives us the following result −
Invalid Password
CSS scroll-margin-left property - GeeksforGeeks

07 Sep, 2020
The scroll-margin-left property is used to set all the scroll margins to the left of an element at once. The value specified for the scroll-margin-left determines how much of the page that is primarily outside the support should remain visible.
Hence, the scroll-margin-left values represent outsets that define the scroll snap area that is used for snapping this box to the support. 
Syntax:
scroll-margin-left: length
/* Or */
scroll-margin-left: Global_Values

Property values: This property accepts two-properties mentioned above and described below:
length: This property refers to the values defined with length units: px, em, rem, vh, etc.
Global_Values: This property refers to the global values like inherit, unset, initial, etc.
Note: scroll-margin-left doesn’t accept percentage value as the length.
Example: In this example, you can see the effect of scroll-margin-left by scrolling to a point partway between two of the “interfaces” of the example’s content.
<!DOCTYPE html><html>    <head>        <style>            .img {                width: 296px;                height: 275px;                scroll-snap-align: none end;            }            .photo {                width: 300px;                height: 300px;                overflow-x: auto;                overflow-y: hidden;                white-space: nowrap;                scroll-snap-type: x mandatory;            }        </style>    </head>    <body>        <div class="photo">            <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131452/img8.jpeg"                  class="img"                  style="scroll-margin-left: 1rem;" />              <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131450/img6-300x82.png"                  class="img"                  style="scroll-margin-left: 2rem;" />              <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131445/img1-300x214.jpg"                  class="img"                  style="scroll-margin-left: 3rem;" />              <img src="https://media.geeksforgeeks.org/wp-content/uploads/20200723131447/img9.jpeg"                  class="img"                 style="scroll-margin-left: 4rem;" />        </div>    </body></html>
Output:
Supported Browsers:
Chrome
Firefox
Edge
Opera
Safari(partially supported)
Internet Explorer (Not Supported)
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to set space between the flexbox ?
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Can we get total number of rows in a MySQL database?

To get the total number of rows in a MySQL database, you can use aggregate function SUM() along with inbuilt column TABLE_ROWS from INFORMATION_SCHEMA.TABLES.
The syntax is as follows−
SELECT SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = database();
Let’s say we are using the database with the name ‘sample’.
Now we will get the total number of rows in a MySQL database−
mysql> SELECT SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = database();
This will produce the following output−
+-----------------+
| SUM(TABLE_ROWS) |
+-----------------+
| 2043            |
+-----------------+
1 row in set (22.11 sec)
GATE | GATE CS 1996 | Question 12 - GeeksforGeeks

28 May, 2020
Consider the following statements:
i.   First-in-first out types of computations are efficiently supported by STACKS.
ii.  Implementing LISTS on linked lists is more efficient than implementing LISTS on
     an array for almost all the basic LIST operations.
iii. Implementing QUEUES on a circular array is more efficient than implementing QUEUES
     on a linear array with two indices.
iv.  Last-in-first-out type of computations are efficiently supported by QUEUES.

Which of the following is correct?
(A) (ii) and (iii) are true(B) (i) and (ii) are true(C) (iii) and (iv) are true(D) (ii) and (iv) are trueAnswer: (A)Explanation: i -STACK is the data structure that follows Last In First Out (LIFO) or First In Last Out (FILO) order, in which the element which is inserted at last is removed out first.
ii – Implementing LISTS on linked lists is more efficient than implementing it on an array for almost all the basic LIST operations because the insertion and deletion of elements can be done in O(1) in Linked List but it takes O(N) time in Arrays.
iii- Implementing QUEUES on a circular array is more efficient than implementing it on a linear array with two indices because using circular arrays, it takes less space and can reuse it again.
iv – QUEUE is the data structure that follows First In First Out (FIFO) or Last In Last Out (LILO) order, in which the element which is inserted first is removed first.
only (ii) and (iii) are TRUE.Option (A) is correct.Quiz of this Question
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
How to add a property to a JavaScript object using a variable as the name? - GeeksforGeeks

10 Jan, 2022
We can create a JavaScript object with an object literal:
Example :
 var obj = { firstname : "Romy", lastname : "kumari", age : 20}
The name: values pairs in JavaScript objects are called properties. We can add the property to JavaScript object using a variable as the name by using dot notation or bracket notation.
Below example illustrate explain two different approaches:
Example 1: In this example, we will be using dot notation.
HTML
<!DOCTYPE html><html>    <body>        <p style="font-size: 30px; color: green;" ;>          GeeksforGeeks        </p>           <p id="add"></p>           <script>            // Variable a and b            var a = "string1";            var b = "string2";            var object1 = { firstname: "Romy",                            lastname: "Kumari" };             // Property using variable name            object1.a = "first property";            object1.b = "Second Property";             document.getElementById("add").innerHTML =              "Added property are : " + object1.a +              " and " + object1.b;        </script>    </body></html>
Output:
Example 2: We can use the bracket operator if we want to add the property with the value stored in the variable. The obj.a is not same as obj[a]
HTML
<!DOCTYPE html><html>    <body>        <p style="font-size: 30px; color: green;";>          GeeksforGeeks        </p>           <p id="add"></p>           <script>            var myObj = new Object();             var a = "string1";            var b = "string2";            // This can be accesses with            // the value stored in b.            myObj.b = "somewhere";            // This can be accessed with the            // value stored in a that is string1            myObj[a] = "whatever";             document.getElementById("add").innerHTML =              "Added property are : " + myObj.string1 +              " and " + myObj.b;        </script>    </body></html>
Output:
varshagumber28
javascript-object
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Throwable getLocalizedMessage() method in Java with Examples - GeeksforGeeks

06 Feb, 2019
The getLocalizedMessage() method of Throwable class is used to get a locale-specific description of the Throwable object when an Exception Occurred. It helps us to modify the description of the Throwable object according to the local Specific message. For the subclasses which do not override this method, the default implementation of this method returns the same result as getMessage().
Syntax:
public String getLocalizedMessage()
Return Value: This method returns a locale-specific description of the Throwable object when an Exception Occurred.
Below programs demonstrate the getLocalizedMessage() method of Throwable Class:
Example 1:
// Java program to demonstrate// the getLocalizedMessage() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {            // add the numbers            addPositiveNumbers(2, -1);        }        catch (Exception e) {            System.out.println("LocalizedMessage = "                               + e.getLocalizedMessage());        }    }      // method which adds two positive number    public static void addPositiveNumbers(int a, int b)        throws Exception    {          if (a < 0 || b < 0) {              throw new Exception("Numbers are not Positive");        }        else {              System.out.println(a + b);        }    }}
LocalizedMessage = Numbers are not Positive

Example 2:
// Java program to demonstrate// the ensureCapacity() Method.  import java.io.*;  class GFG {      // Main Method    public static void main(String[] args)        throws Exception    {          try {            testException();        }          catch (Throwable e) {            System.out.println("LocalizedMessage of Exception : "                               + e.getLocalizedMessage());        }    }      // method which throws IndexOutOfBoundsException    public static void testException()        throws IndexOutOfBoundsException    {          throw new IndexOutOfBoundsException(            "Forcefully Generated Exception");    }}
LocalizedMessage of Exception : Forcefully Generated Exception

References:https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getLocalizedMessage()
Java-Exception Handling
Java-Exceptions
Java-Functions
Java-lang package
java-Throwable
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
JavaScript | Atomics.wait() Method - GeeksforGeeks

02 Aug, 2021
Among the Atomic Operations, there is an inbuilt operation Atomics.wait() in JavaScript is used to verify whether a given position in an Int32Array still contains a given value and if so sleeps, awaiting a wakeup or a timeout. The Atomics.wait() operation returns a string which is either “ok”, “not-equal”, or “timed-out”. The integer typedarray, index, and the value are passed as an argument to the function and timeout is also an argument but it is optional.Syntax:  
Atomics.wait(typedArray, index, value, timeout)
Parameters: This method accept four parameters as mentioned above and described below:  
typedarray: This parameter specifies a shared integer typed array Int16Array.
index: This parameter specifies the position in the array, typedArray to wait on.
value: This parameter specifies the expected value to test.
timeout: This parameter is an optional parameter. It is time to wait in milliseconds.
Return value: The Atomics.wait() method returns the String which is either “ok”, “not-equal”, or “timed-out”.Examples: 
Input: arr[0] = 5
        Atomics.wait(arr, 0, 0, 1)
Output: not-equal

Input: arr[0] = 4
        Atomics.wait(arr, 1, 0, 1)
Output: time-out
Below programs illustrate the Atomics.wait() method in JavaScript:Program 1:  
javascript
var buf = new SharedArrayBuffer(1024);var arr = new Int32Array(buf); arr[0] = 5;console.log(Atomics.load(arr, 0));console.log(Atomics.and(arr, 0, 9));console.log(Atomics.wait(arr, 0, 0, 1));console.log(Atomics.load(arr, 0));
Output:  
5
5
not-equal
1
Program 2:  
javascript
var buf = new SharedArrayBuffer(1024);var arr = new Int32Array(buf); arr[0] = 5;console.log(Atomics.load(arr, 0));console.log(Atomics.and(arr, 0, 9));console.log(Atomics.wait(arr, 1, 0, 1));console.log(Atomics.load(arr, 0));
Output:  
5
5
time-out
1
Exceptions:  
If the typedArray is not a shared Int32Array then the Atomics.wait() operation throws a TypeError.
If the index used as an argument to the Atomics.wait() operation is out of the bound in the typedArray then the Atomics.store( ) operation throws a RangeError.
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
ysachin2314
JavaScript-atomics
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
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?
How to create a ListDictionary in C# - GeeksforGeeks

27 Feb, 2019
ListDictionary() constructor is used to initialize a new empty instance of the ListDictionary class using the default comparer. ListDictionary is a specialized collection. It comes under the System.Collections.Specialized namespace. This type represents a non-generic dictionary type. It is implemented with a linked list. This class is a simple implementation of a dictionary collection (System.Collections.IDictionary) for small lists.
Syntax:
public ListDictionary ();
Example 1:
// C# Program to illustrate how// to create a ListDictionaryusing System;using System.Collections;using System.Collections.Specialized;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // ld is the ListDictionary object        // ListDictionary() is the constructor        // used to initializes a new        // instance of the ListDictionary class        ListDictionary ld = new ListDictionary();          // Count property is used to get the        // number of elements in ListDictionary        // It will give 0 as no elements        // are present currently        Console.WriteLine("The number of elements: "+                                            ld.Count);    }}
The number of elements: 0

Example 2:
// C# Program to illustrate how// to create a ListDictionaryusing System;using System.Collections;using System.Collections.Specialized;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // ld is the ListDictionary object        // ListDictionary() is the constructor        // used to initializes a new        // instance of the ListDictionary class        ListDictionary ld = new ListDictionary();          Console.Write("Before Add Method: ");          // Count property is used to get the        // number of elements in ListDictionary        // It will give 0 as no elements        // are present currently        Console.WriteLine(ld.Count);          // Adding key/value pairs in ld        ld.Add("Australia", "Canberra");        ld.Add("Belgium", "Brussels");        ld.Add("Netherlands", "Amsterdam");        ld.Add("China", "Beijing");        ld.Add("Russia", "Moscow");        ld.Add("India", "New Delhi");          Console.Write("After Add Method: ");          // Count property is used to get the        // number of elements in ld        Console.WriteLine(ld.Count);    }}
Before Add Method: 0
After Add Method: 6

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.-ctor?view=netframework-4.7.2#System_Collections_Specialized_ListDictionary__ctor
CSharp-Specialized-ListDictionary
CSharp-Specialized-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Class and Object
C# | Constructors
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Arrays
Python | Pandas Series.dt.days_in_month - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.days_in_month attribute return the number of days in the month for the given series object.
Syntax: Series.dt.days_in_month
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.days_in_month attribute to find the number of days in the month of the given date in series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-12-31', '2019-1-1 12:30', '2008-02-2 10:30',               '2010-1-1 09:25', '2019-12-31 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.days_in_month attribute to find the number of days in the month for the given date.
# find the number of # days in the monthresult = sr.dt.days_in_month  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.days_in_month attribute has successfully accessed and returned the number of days in the month for the given date.
Example #2 : Use Series.dt.days_in_month attribute to find the number of days in the month of the given date in series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.days_in_month attribute to find the number of days in the month for the given date.
# find the number of # days in the monthresult = sr.dt.days_in_month  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.days_in_month attribute has successfully accessed and returned the number of days in the month for the given date.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
struct module in Python

In this tutorial, we are going to learn about the struct module. Let's dive into the tutorial.
The module struct is used to convert the native data types of Python into string of bytes and vice versa. We don't have to install it. It's a built-in module available in Python3.
The struct module is related to the C languages. We have to know the notations used in C to represent various data type to work with struct module. Let's see some of them.
Let's see how to convert the Python data types into bytes.
The method struct.pack() is used to convert the data types into bytes. It takes multiple arguments based on the first string.
We have to pass the first string with format characters as mention in the above table. We can
pass any arguments as we want. Let's see some examples.
struct.pack('14s i', b'Tutorialspoint', 2020)
struct.pack('i i f 3s', 1, 2, 3.5, b'abc')
Let's convert the above examples into bytes.
 Live Demo
# importing the struct module
import struct
# converting into bytes
print(struct.pack('14s i', b'Tutorialspoint', 2020))
print(struct.pack('i i f 3s', 1, 2, 3.5, b'abc'))
If you run the above code, then you will get the following result.
b'Tutorialspoint\x00\x00\xe4\x07\x00\x00'
b'\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00`@abc'
We have another method struct.unpack() that converts bytes to native Python data types. It takes two arguments, the first one is similar to the pack() method and the second one is the result of struct.pack() method.
The method struct.unpack() always returns a tutple.
 Live Demo
# importing the struct module
import struct
# converting into bytes
converted_bytes = struct.pack('14s i', b'Tutorialspoint', 2020)
# converting into Python data types
print(struct.unpack('14s i', converted_bytes))
If you run the above code, then you will get the following result.
(b'Tutorialspoint', 2020)
If you have any doubts in the tutorial, mention them in the comment section.
Difference between for and while loop in C, C++, Java

13 Jun, 2022
for loop:
for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. Syntax:
for (initialization condition; testing condition; 
                              increment/decrement)
{
    statement(s)
}
Flowchart:  Example: 
C
C++
Java
#include <stdio.h> int main(){     int i = 0;     for (i = 5; i < 10; i++) {        printf("GFG\n");    }     return 0;}
#include <iostream>using namespace std; int main(){     int i = 0;     for (i = 5; i < 10; i++) {        cout << "GFG\n";    }     return 0;}
import java.io.*; class GFG {    public static void main(String[] args)    {         int i = 0;         for (i = 5; i < 10; i++) {            System.out.println("GfG");        }    }}
GFG
GFG
GFG
GFG
GFG
Looping Infinite times:
C++
C
#include <iostream>using namespace std; int main(){       for ( ; ; )        cout << "GFG\n";    return 0;}
#include <stdio.h> int main() {     for ( ; ; )        printf("GFG\n");    return 0;}
Output:
Network Error
while loop:
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax :
while (boolean condition)
{
   loop statements...
}
Flowchart:  Example: 
C
C++
Java
#include <stdio.h> int main(){     int i = 5;     while (i < 10) {        printf("GFG\n");        i++;    }     return 0;}
#include <iostream>using namespace std; int main(){     int i = 5;     while (i < 10) {        i++;        cout << "GFG\n";    }     return 0;}
import java.io.*; class GFG {    public static void main(String[] args)    {         int i = 5;         while (i < 10) {            i++;            System.out.println("GfG");        }    }}
GFG
GFG
GFG
GFG
GFG
Looping Infinite times:
C++
C
#include <iostream>using namespace std; int main(){     while (1)        cout << "GFG\n";    return 0;}
#include <stdio.h> int main() {     while (1)        printf("GFG\n");    return 0;}
Output:
Network Error
Here are few differences:
susobhanakhuli
harshitdevda97
loop
Loops & Control Structure
Difference Between
Programming Language
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Set Methods

12 Nov, 2021
A Set in Python is a collection of unique elements which are unordered and mutable. Python provides various functions to work with Set. In this article, we will see a list of all the functions provided by Python to deal with Sets.
We can add and remove elements form the set with the help of the below functions – 
add(): Adds a given element to a set
clear(): Removes all elements from the set
discard(): Removes the element from the set
pop(): Returns and removes a random element from the set
remove(): Removes the element from the set
Example: Adding and removing elements from the Set.
Python3
# set of letterss = {'g', 'e', 'k', 's'} # adding 's's.add('f')print('Set after updating:', s) # Discarding element from the sets.discard('g')print('\nSet after updating:', s) # Removing element from the sets.remove('e')print('\nSet after updating:', s) # Popping elements from the setprint('\nPopped element', s.pop())print('Set after updating:', s) s.clear()print('\nSet after updating:', s)
Set after updating: {'g', 'k', 's', 'e', 'f'}

Set after updating: {'k', 's', 'e', 'f'}

Set after updating: {'k', 's', 'f'}

Popped element k
Set after updating: {'s', 'f'}

Set after updating: set()
  
 
Note: For more information about Python Sets, refer to Python Set Tutorial.
 
prachisoda1234
surindertarika1234
python-set
Python-set-functions
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
ReactJS - Higher Order Components

Higher order components are JavaScript functions used for adding additional functionalities to the existing component. These functions are pure, which means they are receiving data and returning values according to that data. If the data changes, higher order functions are re-run with different data input. If we want to update our returning component, we don't have to change the HOC. All we need to do is change the data that our function is using.
Higher Order Component (HOC) is wrapping around "normal" component and provide additional data input. It is actually a function that takes one component and returns another component that wraps the original one.
Let us take a look at a simple example to easily understand how this concept works. The MyHOC is a higher order function that is used only to pass data to MyComponent. This function takes MyComponent, enhances it with newData and returns the enhanced component that will be rendered on the screen.
import React from 'react';

var newData = {
   data: 'Data from HOC...',
}

var MyHOC = ComposedComponent => class extends React.Component {
   componentDidMount() {
      this.setState({
         data: newData.data
      });
   }
   render() {
      return <ComposedComponent {...this.props} {...this.state} />;
   }
};
class MyComponent extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.data}</h1>
         </div>
      )
   }
}

export default MyHOC(MyComponent);
If we run the app, we will see that data is passed to MyComponent.
Note − Higher order components can be used for different functionalities. These pure functions are the essence of functional programming. Once you are used to it, you will notice how your app is becoming easier to maintain or to upgrade.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    60 Lectures 
     4.5 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    17 Lectures 
     2 hours 

 Mohd Raqif Warsi
 Print
 Add Notes
 Bookmark this page
DocumentDB - Sorting Records

Microsoft Azure DocumentDB supports querying documents using SQL over JSON documents. You can sort documents in the collection on numbers and strings using an ORDER BY clause in your query. The clause can include an optional ASC/DESC argument to specify the order in which results must be retrieved.
Let’s take a look at the following example in which we have a JSON document.
{ 
   "id": "Food Menu",
   "description": "Grapes, red or green (European type, such as Thompson seedless), raw",
	
   "tags": [
      {
         "name": "grapes"
      },
		
      {
         "name": "red or green (european type"
      },
		
      {
         "name": "such as thompson seedless)"
      },
		
      {
         "name": "raw"
      }
   ],
	
   "foodGroup": "Fruits and Fruit Juices",
	
   "servings": [
      {
         "amount": 1,
         "description": "cup",
         "weightInGrams": 151
      },
		
      {
         "amount": 10,
         "description": "grapes",
         "weightInGrams": 49
      },
		
      {
         "amount": 1,
         "description": "NLEA serving",
         "weightInGrams": 126
      }
   ]
	
}
Following is the SQL query to sort the result in a descending order.
SELECT f.description, f.foodGroup,  
   f.servings[2].description AS servingDescription,  
   f.servings[2].weightInGrams AS servingWeight  
	
FROM f  
ORDER BY f.servings[2].weightInGrams DESC 
When the above query is executed, you will receive the following output.
[
   {
      "description": "Grapes, red or green (European type, such as Thompson
         seedless), raw",
      "foodGroup": "Fruits and Fruit Juices",
      "servingDescription": "NLEA serving",
      "servingWeight": 126
   }
]

 Print
 Add Notes
 Bookmark this page
Popovers in Bootstrap with examples

A popover is a simple tooltip plugin. A popover is a box of content that pops up when the user clicks on a specific element. This plugin relies on popover.js.
The attribute data-toggle = "popover" is used to create a popover in HTML. Adding this attribute to an element converts it to a popover.
<a href=”” data-toggle = "popover" title="popover title" data-content="popover content" >popover display</a>
 Live Demo
<!DOCTYPE html>
<html lang="en" >
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h3>Popover In BootStap</h3><br><br>
<a href="#" data-toggle="popover" title="Welcome Text" data-content="Learning Bootstrap from TutorialsPoint!">Learn BootStrap</a>
</div>
<script>
$(document).ready(function(){
   $('[data-toggle="popover"]').popover();
});
</script>
</body>
</html>
You can position popovers using the data-placement attribute. By default, a popover appears on the right of the element.
Let’s see the positioning of popovers in different directions −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title<Bootstrap Example</title<
<meta charset="utf-8"<
<meta name="viewport" content="width=device-width, initial-scale=1"<
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"<
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"<</script<
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"<</script<
</head>
<body>
<div class="container">
<h3>Popover Example</h3>
<a href="#" data-toggle="popover" title="Popover Header" data-placement="right" data-content="Some content inside the popover">Toggle popover right</a><br><br><br><hr>
<a href="#" data-toggle="popover" title="Popover Header" data-placement="top" data-content="Some content inside the popover">Toggle popover Top</a><br><br><br><hr>
<a href="#" data-toggle="popover" title="Popover Header" data-placement="left" data-content="Some content inside the popover">Toggle popover left</a><br><br><br><hr>
<a href="#" data-toggle="popover" title="Popover Header" data-placement="bottom" data-content="Some content inside the popover">Toggle popover bottom</a><br><br><br><hr>
</div>
<script>
$(document).ready(function(){
   $('[data-toggle="popover"]').popover();
});
</script>
</body>
</html>
How to convert array into array of objects using map() and reduce() in JavaScript

Suppose we have an array of arrays like this −
const arr = [
   [
      ['juice', 'apple'], ['maker', 'motts'], ['price', 12]
   ],
   [
      ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]
   ]
];
We are required to write a JavaScript function that takes in one such array and returns a new
array of objects built based on the input array.
So, for the above array, the output should look like this −
const output = [
   {juice: 'apple', maker: 'motts', price: 12},
   {juice: 'orange', maker: 'sunkist', price: 11}
];
The code for this will be −
const arr = [
   [
      ['juice', 'apple'], ['maker', 'motts'], ['price', 12]
   ],
   [
      ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]
   ]
];
const arrayToObject = arr => {
   let res = [];
   res = arr.map(list => {
      return list.reduce((acc, val) => {
         acc[val[0]] = val[1];
         return acc;
      }, {});
   });
   return res;
};
console.log(arrayToObject(arr));
The output in the console −
[
   { juice: 'apple', maker: 'motts', price: 12 },
   { juice: 'orange', maker: 'sunkist', price: 11 }
][
   { juice: 'apple', maker: 'motts', price: 12 },
   { juice: 'orange', maker: 'sunkist', price: 11 }
]
Flip String to Monotone Increasing in C++

Suppose a string of '0's and '1's is given. That string will be monotonic increasing if it consists of some number of '0's (possibly 0), followed by some number of '1's (also possibly 0.). We have a string S of '0's and '1's, and we may flip any '0' to a '1' or a '1' to a '0'. Find the minimum number of flips to make S monotone increasing. So if the input is like “010110”, then the output will be 2. By flipping we can get “011111” or “000111”.
To solve this, we will follow these steps −
n := size of S, set flipCount := 0, oneCount := 0
n := size of S, set flipCount := 0, oneCount := 0
for i in range 0 to n – 1if S[i] is 0, thenif oneCount = 0, then skip to the next iterationincrease the flipCount by 1otherwise increase oneCount by 1if oneCount < flipCount, then set flipCount := oneCount
for i in range 0 to n – 1
if S[i] is 0, thenif oneCount = 0, then skip to the next iterationincrease the flipCount by 1
if S[i] is 0, then
if oneCount = 0, then skip to the next iteration
if oneCount = 0, then skip to the next iteration
increase the flipCount by 1
increase the flipCount by 1
otherwise increase oneCount by 1
otherwise increase oneCount by 1
if oneCount < flipCount, then set flipCount := oneCount
if oneCount < flipCount, then set flipCount := oneCount
return flipCount
return flipCount
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int minFlipsMonoIncr(string S) {
      int n = S.size();
      int flipCount = 0;
      int oneCount = 0;
      for(int i = 0; i < n; i++){
         if(S[i] == '0'){
            if(oneCount == 0) continue;
            flipCount++;
         } else oneCount++;
            if(oneCount < flipCount) flipCount = oneCount;
      }
      return flipCount;
   }
};
main(){
   Solution ob;
   cout << (ob.minFlipsMonoIncr("010110"));
}
"010110"
2
Python | Pandas Index.union() - GeeksforGeeks

22 Sep, 2021
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 Index.union() function form the union of two Index objects and sorts if possible. The function follows behaves like a standard set union operation. The function can also find the union of categorical data.
Syntax: Index.union(other)Parameters : other : Index or array-likeReturns : union : Index 
Example #1: Use Index.union() function to find the union of two indexes. 
Python3
# importing pandas as pdimport pandas as pd # Creating the first indexidx1 = pd.Index([10, 20, 18, 32]) # Creating the second indexidx2 = pd.Index([21, 10, 30, 40, 50]) # Print the first Indexprint(idx1) # Print the second Indexprint("\n", idx2)
Output :  
Let’s find the union of these two indexes 
Python3
# perform set union of the two indexesidx1.union(idx2)
Output :  
The function has found the union of these two indexes.   Example #2: Use Index.union() function to perform set union operation on the given two indexes. Index labels are of string type.
Python3
# importing pandas as pdimport pandas as pd # Creating the first indexidx1 = pd.Index(['Harry', 'Mike', 'Arther', 'Nick'],                                    name ='Student') # Creating the second indexidx2 = pd.Index(['Alice', 'Bob', 'Rachel', 'Tyler', 'Louis'],                                            name ='Winners') # Print the first Indexprint(idx1) # Print the second Indexprint("\n", idx2)
Output :  
Let’s find the union of these two indexes.
Python3
# find union of two indexesidx1.union(idx2)
Output :  
The function has returned a new index that contains the result of the set union of the idx1 and idx2. 
anikakapoor
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Instruction type SUB R in 8085 Microprocessor

In 8085 Instruction, SUB is a mnemonic that stands for ‘SUBtract contents of R from Accumulator. Here R stands for any of the following registers, or memory location M pointed by HL pair.
R = A, B, C, D, E, H, L, or M

In this instruction content of the register R will get subtracted from the Accumulator and the resultant difference will be stored on the Accumulator replacing the previous content of the Accumulator. Where R can be any of the eight values, so as a result there are eight opcodes for this type of instruction as mentioned in the above table. It occupies only 1-Byte in the memory.
Let us consider SUB E as an example instruction of this category. As It is 1-Byte instruction so it will occupy a single Byte space in the memory. The result of execution of this instruction is shown below with examples.
Let us supposeAccumulator and E register are having initial values as ABH and CDH respectively. So after execution of the instruction SUB E the contents of the registers would be
(A)
(E)
(F)
Here Cy=1 indicates that result is negative. Actually A – E = A + 2’ Complement of E. Here is the calculation.
(A)	ABH (1010 1011) ---------------> 1010 1011
                           2'S Complement
(E)  CDH (1100 1101) --------------->      0011 0011
                                       ---------------
                                       1101 1110 (DEH)

Here is the timing diagram of the instruction SUB E as below
Summary − So this instruction SUB E requires 1-Byte, 1 Machine Cycles (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
Let us suppose Accumulator and E register are having initial values as CDH and ABH respectively. So after execution of the instruction SUB E the contents of the registers would be
(A)
(E)
(F)
Here Cy=0 indicates that result is positive. Actually A – E = A + 2’ Complement of E. Here is the calculation.
(A)	CDH (1100 1101) ---------------> 1100 1101
                         2'S Complement
(E) ABH (1010 1011) --------------->    0101 0101
                                       ----------------
                                       0010 0010 (22H)

Here is the timing diagram of the instruction SUB E as below
Summary − So this instruction SUB E requires 1-Byte, 1 Machine Cycles (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
How will GROUP BY clause perform without an aggregate function?

When we use GROUP BY clause in the SELECT statement without using aggregate functions then it would behave like DISTINCT clause. For example, we have the following table −
mysql> Select * from Student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Chandigarh | Literature |
| 125  | Raman   | Shimla     | Computers  |
| 130  | Ram     | Jhansi     | Computers  |
| 132  | Shyam   | Chandigarh | Economics  |
| 133  | Mohan   | Delhi      | Computers  |
| 150  | Saurabh | NULL       | Literature |
+------+---------+------------+------------+
7 rows in set (0.00 sec)
By using the DISTINCT clause on column ‘Address’, MySQL returns the following result set.
mysql> Select DISTINCT ADDRESS from Student_info;
+------------+
| ADDRESS    |
+------------+
| Amritsar   |
| Chandigarh |
| Shimla     |
| Jhansi     |
| Delhi      |
| NULL       |
+------------+
6 rows in set (0.07 sec)
Now, by using GROUP BY clause as follows, we can get the same result set as we got by using DISTINCT −
mysql> Select ADDRESS from Student_info GROUP BY Address;
+------------+
| ADDRESS    |
+------------+
| NULL       |
| Amritsar   |
| Chandigarh |
| Delhi      |
| Jhansi     |
| Shimla     |
+------------+
6 rows in set (0.00 sec)
We can observe a difference between both the result sets returned by MySQL that the result set returns by MySQL query using GROUP BY clause is sorted and in contrast, the result set return by MySQL query using DISTICT clause is not sorted.