code-rag-bench/online-tutorials huggingface dataset:
Angular forms formatCurrency Directive - GeeksforGeeks

02 Jun, 2021
In this article, we are going to see what is formatCurrency in Angular 10 and how to use it. The formatCurrency is used to format a number as currency using locale rules.
Syntax:
formatCurrency(value, locale, currency, currencyCode, digitsInfo)
Parameters:
value: The number to format.
locale: A locale code for the locale format.
currency: A string containing the currency symbol or its name.
currencyCode: the currency code.
digitsInfo: Decimal representation options.
 
Return Value:
string: the formatted currency code.
NgModule: Module used by formatCurrency is:
CommonModule
Approach: 
Create the Angular app to be used.
In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatCurrency.import { LOCALE_ID, NgModule } from '@angular/core';
import { LOCALE_ID, NgModule } from '@angular/core';
In app.component.ts import formatCurrency and LOCALE_ID
inject LOCALE_ID as a public variable.
In app.component.html show the local variable using string interpolation
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import {  formatCurrency }  from '@angular/common';  import {Component,  Inject,  LOCALE_ID }  from '@angular/core';  @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatCurrency(10,this.locale,          'USD');constructor(  @Inject(LOCALE_ID) public locale: string,){}}
app.component.html
<h1>  GeeksforGeeks</h1>  <p>Locale Currency is : {{curr}}</p>
Output:
Example 2:
app.component.ts
import {  formatCurrency }  from '@angular/common';  import {Component,  Inject,  LOCALE_ID }  from '@angular/core';  @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatCurrency(10,this.locale,          'INR');constructor(  @Inject(LOCALE_ID) public locale: string,){}}
app.component.html
<h1>  GeeksforGeeks</h1>  <p>Locale Currency is : {{curr}}</p>
Output:
Reference: https://angular.io/api/common/formatCurrency
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
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?
Class getFields() method in Java with Examples - GeeksforGeeks

25 Jan, 2022
The getFields() method of java.lang.Class class is used to get the fields of this class, which are the fields that are public and its members. The method returns the fields of this class in the form of array of Field objects. Syntax:  
public Field[] getFields()
Parameter: This method does not accept any parameter.Return Value: This method returns the fields of this class in the form of an array of Field objects. Exception This method throws SecurityException if a security manager is present and the security conditions are not met.Below programs demonstrate the getFields() method.Example 1: 
Java
// Java program to demonstrate getFields() method import java.util.*; public class Test {     public Object obj;     public static void main(String[] args)        throws ClassNotFoundException    {         // returns the Class object for this class        Class myClass = Class.forName("Test");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the fields of myClass        // using getFields() method        System.out.println("Fields of myClass: "                           + Arrays.toString(                                 myClass.getFields()));    }}
Class represented by myClass: class Test
Fields of myClass: [public java.lang.Object Test.obj]
 
Example 2: 
Java
// Java program to demonstrate getFields() method import java.util.*; class Main {     private Object obj;     Main()    {         class Arr {        };         obj = new Arr();    }     public static void main(String[] args)        throws ClassNotFoundException    {        Main t = new Main();         // returns the Class object        Class myClass = t.obj.getClass();         // Get the fields of myClass        // using getFields() method        System.out.println("Fields of myClass: "                           + Arrays.toString(                                 myClass.getFields()));    }}
Fields of myClass: []
 
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getFields– 
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Java Program for Binary Insertion Sort - GeeksforGeeks

28 Jun, 2021
We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration.In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search.
// Java Program implementing// binary insertion sort  import java.util.Arrays;class GFG{    public static void main(String[] args)    {        final int[] arr = {37, 23, 0, 17, 12, 72, 31,                             46, 100, 88, 54 };          new GFG().sort(arr);          for(int i=0; i<arr.length; i++)            System.out.print(arr[i]+" ");    }      public void sort(int array[])    {        for (int i = 1; i < array.length; i++)        {            int x = array[i];              // Find location to insert using binary search            int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1);              //Shifting array to one location right            System.arraycopy(array, j, array, j+1, i-j);              //Placing element at its correct location            array[j] = x;        }    }}  // Code contributed by Mohit Gupta_OMG 
Please refer complete article on Binary Insertion Sort for more details!
Insertion Sort
Java Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
Java Servlet and JDBC Example | Insert data in MySQL
What is the difference between re.findall() and re.finditer() methods available in Python?

The re.findall() helps to get a list of all matching patterns. It searches from start or end of the given string. If we use method findall to search for a pattern in a given string it will return all occurrences of the pattern. While searching a pattern, it is recommended to use re.findall() always, it works like re.search() and re.match() both.
import re result = re.search(r'TP', 'TP Tutorials Point TP')

print result.group()
TP
re.finditer(pattern, string, flags=0)
 Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. 
The following code shows the use of re.finditer() method in Python regex
import re s1 = 'Blue Berries'
pattern = 'Blue Berries'
for match in re.finditer(pattern, s1):
    s = match.start()
    e = match.end()
    print 'String match "%s" at %d:%d' % (s1[s:e], s, e)
Strings match "Blue Berries" at 0:12
F# - Discriminated Unions

Unions, or discriminated unions allows you to build up complex data structures representing well-defined set of choices. For example, you need to build an implementation of a choice variable, which has two values yes and no. Using the Unions tool, you can design this.
Discriminated unions are defined using the following syntax −
type type-name =
   | case-identifier1 [of [ fieldname1 : ] type1 [ * [ fieldname2 : ] 
type2 ...]
   | case-identifier2 [of [fieldname3 : ]type3 [ * [ fieldname4 : ]type4 ...]
...

Our simple implementation of ,choice, will look like the following −
type choice =
   | Yes
   | No

The following example uses the type choice −
type choice =
   | Yes
   | No

let x = Yes (* creates an instance of choice *)
let y = No (* creates another instance of choice *)
let main() =
   printfn "x: %A" x
   printfn "y: %A" y
main()
When you compile and execute the program, it yields the following output −
x: Yes
y: No

The following example shows the implementation of the voltage states that sets a bit on high or low −
type VoltageState =
   | High
   | Low

let toggleSwitch = function (* pattern matching input *)
   | High -> Low
   | Low -> High

let main() =
   let on = High
   let off = Low
   let change = toggleSwitch off

   printfn "Switch on state: %A" on
   printfn "Switch off state: %A" off
   printfn "Toggle off: %A" change
   printfn "Toggle the Changed state: %A" (toggleSwitch change)

main()
When you compile and execute the program, it yields the following output −
Switch on state: High
Switch off state: Low
Toggle off: High
Toggle the Changed state: Low

type Shape =
   // here we store the radius of a circle
   | Circle of float

   // here we store the side length.
   | Square of float

   // here we store the height and width.
   | Rectangle of float * float

let pi = 3.141592654

let area myShape =
   match myShape with
   | Circle radius -> pi * radius * radius
   | Square s -> s * s
   | Rectangle (h, w) -> h * w

let radius = 12.0
let myCircle = Circle(radius)
printfn "Area of circle with radius %g: %g" radius (area myCircle)

let side = 15.0
let mySquare = Square(side)
printfn "Area of square that has side %g: %g" side (area mySquare)

let height, width = 5.0, 8.0
let myRectangle = Rectangle(height, width)
printfn "Area of rectangle with height %g and width %g is %g" height width (area myRectangle)
When you compile and execute the program, it yields the following output −
Area of circle with radius 12: 452.389
Area of square that has side 15: 225
Area of rectangle with height 5 and width 8 is 40

 Print
 Add Notes
 Bookmark this page
Merge Overlapping Intervals using C++.

Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals
Given set of interval is {{12, 14}, {11, 13}, {20, 22}, {21, 23}} then
Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14}
Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14}
Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23}
Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23}
1. Sort the intervals based on increasing order of starting time
2. Push the first interval on to a stack
3. For each interval perform below steps:
   3.1. If the current interval does not overlap with the top of the stack, push it.
   3.2. If the current interval overlaps with top of the stack and ending time of current interval is more than that of top of stack, update stack top with the ending time of current interval.
4. Finally, stack contains the merged intervals.
#include <iostream>
#include <algorithm>
#include <stack>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct interval{
   int start;
   int end;
};
bool compareInterval(interval i1, interval i2){
   return (i1.start < i2.start);
}
void mergeOverlappingIntervals(interval *arr, int n){
   if (n <= 0) {
      return;
   }
   stack<interval> s;
   sort(arr, arr + n, compareInterval);
   s.push(arr[0]);
   for (int i = 1; i < n; ++i) {
      interval top = s.top();
      if (top.end < arr[i].start) {
         s.push(arr[i]);
      } else if(top.end < arr[i].end) {
         top.end = arr[i].end;
         s.pop();
         s.push(top);
      }
   }
   cout << "Merged intervals: " << endl;
   while (!s.empty()) {
      interval i = s.top();
      cout << "{" << i.start << ", " << i.end << "}" << " ";
      s.pop();
   }
   cout << endl;
}
int main(){
   interval arr[] = {{12, 14}, {11, 13}, {20, 22}, {21, 23}};
   mergeOverlappingIntervals(arr, SIZE(arr));
   return 0;
}
When you compile and execute the above program. It generates the following output −
Merged intervals:
{20, 23} {11, 14}
How do nested functions work in Python?

To learn about nested function, refer the following code. In the code, you can see Inner functions can access variables from the enclosing scope, which is the local variable.
def mulFunc(num1):
   def mul(num2):
      return num1 * num2
   return mul
res = mulFunc(15)
// The following prints 300 i.e. 20*15
print(res(20))
The above prints the multiplication of num1 and num 2 i.e. 300
How to insert blank row into dataframe in R ? - GeeksforGeeks

17 Dec, 2021
In this article, we will discuss how to insert blank rows in dataframe in R Programming Language.
The nrow() method in R is used to return the number of rows in a dataframe. A new row can be inserted at the end of the dataframe using the indexing technique. The new row is assigned a vector NA, in order to insert blank entries. The changes are made to the original dataframe. 
Syntax:
df [ nrow(df) + 1 , ] <- NA
Example:
R
# declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4),                         col2 = letters[1:4],                         col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # calculating total rowsrows <- nrow(data_frame) # inserting row at enddata_frame[rows+1,] <- NA print ("Modified Dataframe")print (data_frame)
Output
[1] "Original Dataframe"
 col1 col2 col3
1    1    a    8
2    2    b    9
3    3    c   10
4    4    d   11
[1] "Modified Dataframe"
 col1 col2 col3
1    1    a    8
2    2    b    9
3    3    c   10
4    4    d   11
5   NA <NA>   NA
A package in R programming language “berryFunctions” can be invoked in order to work with converting the lists to data.frames and arrays, fit multiple functions. 
Syntax:
install.packages(“berryFunctions”)
The method insertRows() in R language can be used to append rows at the dataframe at any specified position. This method can also insert multiple rows into the dataframe. The new row is declared in the form of a vector. In the case of a blank row insertion, the new row is equivalent to NA. The changes have to be saved to the original dataframe. 
Syntax:
insertRows(df, r, new = NA)
Parameter : 
df – A dataframe to append row to
r – The position at which to insert the row
new – The new row vector to insert
Example:
R
library ("berryFunctions") # declaring a dataframe in Rdata_frame <- data.frame(col1 = c(1:4),                         col2 = letters[1:4],                         col3 = c(8:11)) print ("Original Dataframe")print (data_frame) # inserting row at enddata_frame <- insertRows(data_frame, 2 , new = NA) print ("Modified DataFrame")print (data_frame)
Output
[1] "Original Dataframe" 
col1 col2 col3 
1    1    a    8 
2    2    b    9 
3    3    c   10 
4    4    d   11 
[1] "Modified DataFrame" 
col1 col2 col3 
1    1    a    8 
2   NA <NA>   NA 
3    2    b    9 
4    3    c   10 
5    4    d   11
simmytarika5
singghakshay
sweetyty
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Data Visualization in R
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Control Statements in R Programming
Logistic Regression in R Programming
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
enable and disable command in Linux

05 Nov, 2019
Enables and disables are the built-in shell commands. enable command is used to start the printers or classes whereas the disable command is used to stop the printers or classes.
Syntax For enable Command:
enable [-a] [-dnps] [-f filename][name ...]

Syntax For disable Command:
disable [-c] [-W] [ -r [ reason ] ] printer
Options:
-a : List all builtins with the message of whether it is enabled or not.
-c : It will cancel the requests which are currently printing.
-d : Delete a builtin loaded with `-f’.
-W : Wait until the request currently being printed is finished before disabling printer. This option cannot be used with the -c option. If the printer is remote then the -W option will be silently ignored.
-r reason : It assigns a reason for the disabling of the printer(s).
printer : The name of the printer to be enabled or disabled.
-n: Disable the names listed, otherwise names are enabled.
Akanksha_Rai
linux-command
Linux-Shell-Commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to detect HTTP or HTTPS then force redirect to HTTPS in JavaScript ?

12 Dec, 2021
HTTPS stands for Hypertext Transfer Protocol Secure. As its name implies, it creates a secure, encrypted connection between the user’s browser and the server they are trying to access. Since it is an encrypted connection, it prevents malicious hackers from stealing data that is transmitted from the user’s browser to the server. Having a site in HTTPS also tells users that they can trust your site. If you have a site in HTTP as well as the same version in HTTPS, you can automatically redirect the user to the HTTPS site.To implement this redirect, we will use JavaScript code. Specifically, we will use the window.location.protocol property to identify the protocol and then use window.location.href property to redirect the browser. The window.location is a property of the Window object. It is often used for redirects. The window.location returns a Location object, which contains a number of useful properties:  
protocol: This is the protocol (http: or https:) of the current URL of the browser window.
href: This is the full URL of the current browser window. It is writable.
Note: Since window.location.href is writable, we will set a new URL to it and therefore reload the browser with the new URL. 
Example:  
javascript
if (window.location.protocol == 'http:') {         console.log("you are accessing us via "        +  "an insecure protocol (HTTP). "        + "Redirecting you to HTTPS.");             window.location.href =        window.location.href.replace(                   'http:', 'https:');}else    (window.location.protocol == "https:") {        console.log("you are accessing us via"            + " our secure HTTPS protocol.");    }
Output:  
// On HTTP sites, you will be redirected to the HTTPS version.
Disadvantages: There are some downsides with setting an HTTPS redirect from the browser side. These downsides include:  
If there is a malicious hacker in the middle of your connection (Man in the Middle Attack), they can prevent the redirect from occurring.
During the initial load of HTTP, there may be cookies that have been previously set that can now be read by the hacker.
Therefore, we recommend redirecting users via HTTPS on the server-side instead of in JavaScript. We have added an example below on how to do this redirect using NodeJS, which is a server written in Javascript. Using NodeJS on the server, the code is similar but not exactly the same. We will use req.protocol instead.  
Example (app.js): 
javascript
app.get('/', function(req, res, next) {    if (req.protocol == 'http') {        res.redirect('https://' +        req.get('host') + req.originalUrl);    }});
Output:  
// On HTTP sites, you will be redirected to the HTTPS version.
Note: The req.protocol does not include the colon (eg: http or https) whereas window.location.protocol does (eg: http: and https:). 
sagar0719kumar
JavaScript-Misc
Picked
JavaScript
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Why we should use set.seed in R?

The use of set.seed is to make sure that we get the same results for randomization. If we
randomly select some observations for any task in R or in any statistical software it
results in different values all the time and this happens because of randomization. If we
want to keep the values that are produced at first random selection then we can do this by
storing them in an object after randomization or we can fix the randomization procedure
so that we get the same results all the time.
Randomization without set.seed
> sample(1:10)
[1] 4 10 5 3 1 6 9 2 8 7
> sample(1:10)
[1] 1 4 2 5 8 3 7 9 6 10
> sample(1:10)
[1] 6 3 9 5 10 2 7 1 8 4
Here we created a sample of size 10 three times and in all these samples the values are
different.
Randomization with set.seed
> set.seed(99)
> sample(1:10)
[1] 6 2 10 7 4 5 3 1 8 9
> set.seed(99)
> sample(1:10)
[1] 6 2 10 7 4 5 3 1 8 9
> set.seed(99)
> sample(1:10)
[1] 6 2 10 7 4 5 3 1 8 9
Since we used the same set.seed in all the three samples hence we obtained the same
sample values.
How to order an alphanumeric column in MySQL?

To order an alphanumeric column with values like “100X, “2Z”, etc. use the ORDER BY. Let us first create a table −
mysql> create table DemoTable
-> (
-> StudentId varchar(100)
-> );
Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('2X');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values('100Y');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('100X');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values('2Z');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('2Y');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable values('100Z');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| 2X        |
| 100Y      |
| 100X      |
| 2Z        |
| 2Y        |
| 100Z      |
+-----------+
6 rows in set (0.00 sec)
Here is the query to order by an alphanumeric column in MySQL −
mysql>select *from DemoTable order by (StudentId+0), right(StudentId, 1);
This will produce the following output −
+-----------+
| StudentId |
+-----------+
| 2X        |
| 2Y        |
| 2Z        |
| 100X      |
| 100Y      |
| 100Z      |
+-----------+
6 rows in set, 6 warnings (0.00 sec)
Bootstrap Collapsible button

The collapsible button is used in Bootstrap to create a collapsible that can be shown or hidden on click.
You can try to run the following code to create a collapsible button:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h2>Contact Us</h2>
         <p>Click for more info...</p>
         <button type = "button" class = "btn btn-info" data-toggle = "collapse" data-target = "#demo">More</button>
         <div id="demo" class="collapse">
            You can also contact us on 9199****** for more information on our products.
         </div>
      </div>
   </body>
</html>
Convert a list into tuple of lists in Python

Converting one data container into another in python is a frequent requirement. In this article we will take a list and convert into a tuple where each element of the tuple is also a list.
We can apply the tuple function straight to the list. But we have to also put a for loop in place so that each element is enclosed in a [].
 Live Demo
listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = tuple([i] for i in listA)
# Result
print("The tuple is : ",res)
Running the above code gives us the following result −
Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : (['Mon'], [2], ['Tue'], [3])
We can also use zip and map in a similar approach as in the above. The map function will apply the list function to each element in the list. Finally the tuple function converts the result into a tuple whose each element is a list.
 Live Demo
listA = ["Mon",2,"Tue",3]
# Given list
print("Given list A: ", listA)
# Use zip
res = tuple(map(list, zip(listA)))
# Result
print("The tuple is : ",res)
Running the above code gives us the following result −
Given list A: ['Mon', 2, 'Tue', 3]
The tuple is : (['Mon'], [2], ['Tue'], [3])
Heap Data Structure - GeeksQuiz

07 Nov, 2019
BUILD-HEAP(A) 
    heapsize := size(A); 
    for i := floor(heapsize/2) downto 1 
        do HEAPIFY(A, i); 
    end for 
END
                                      9
                                   /  |   \
                                /     |     \
                              5       6      8
                           /  |
                         /    |
                       3      1

                                          9
                                      /   |   \
                                    /     |     \
                                  7       6       8
                               / | \
                             /   |  \
                            3    1    5    

                                           9
                                      /    |   \
                                    /      |     \
                                  7        6       8
                               / | \       /
                             /   |  \     /
                            3    1    5  2

                                 10
                             /    |   \
                           /      |     \
                        7         9       8
                    / | \       / |
                  /   |  \     /  |
                3    1    5  2    6

                                 10
                             /   |   \
                           /     |     \
                         7        9       8
                      / | \      / | \
                    /   |  \    /  |   \
                  3    1    5  2   6    4

           25
        /      \
      /          \
    14            16
   /  \           /  \
 /      \       /     \
13     10      8       12
          12
        /    \
      /       \
    14        16
   / \         /
 /     \      /
13     10    8
           16
        /     \
      /        \
    14         12
   / \         /
  /   \       /
13     10    8
           8
        /    \
       /      \
    14         12
   / \
  /   \
 13     10
           14
         /    \
       /       \
     8         12
    / \
   /   \
 13     10
            14
         /     \
        /       \
     13         12
    / \
   /   \
  8    10
         12
        /  \
      /      \
    8         7
   / \        / \
 /     \    /     \
2      3   4       5
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
SQL Query to Convert VARCHAR to INT
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
Insert Image in a Jupyter Notebook
How to Replace Values in a List in Python?
Python | Pandas Timestamp.toordinal - GeeksforGeeks

27 Jan, 2019
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 Timestamp.toordinal() function return proleptic Gregorian ordinal. January 1 of year 1 is day 1. Function return the ordinal value for the given Timestamp object.
Syntax :Timestamp.toordinal()
Parameters : None
Return : ordinal
Example #1: Use Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                   hour = 10, second = 49, tz = 'US/Central')   # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object.
# return ordinalts.toordinal()
Output :
As we can see in the output, the Timestamp.toordinal() function has returned the Gregorian ordinal for the given Timestamp.
Example #2: Use Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                   hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.toordinal() function to return the Gregorian ordinal for the given Timestamp object.
# return ordinalts.toordinal()
Output :
As we can see in the output, the Timestamp.toordinal() function has returned the Gregorian ordinal for the given Timestamp.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
sum() function in Python
How to record a video in Selenium webdriver?

We can record a video with Selenium. There is no default technique in Selenium to record videos. The videos can be captured in the below processes−
ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar files need to be downloaded and saved within the project folder.
ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar files need to be downloaded and saved within the project folder.
Next, add the above two jars to the project Build path. Right-click on project−> Click on Properties−> Choose Java Build Path−> Click on the Libraries tab−> Click on Add External Jars−> Browser and select the ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar−> Click on Apply−> Click OK.
Next, add the above two jars to the project Build path. Right-click on project−> Click on Properties−> Choose Java Build Path−> Click on the Libraries tab−> Click on Add External Jars−> Browser and select the ATUTestRecorder.jar and ATUReporter_Selenium_testNG.jar−> Click on Apply−> Click OK.
Have a folder to hold the videos within the project.
Have a folder to hold the videos within the project.
@BeforeMethod
public void bmethod(Method m){
   // format of the date and time defined
   DateFormat d = new SimpleDateFormat("yy−mm−dd HH−mm−ss");
   // get the current date
   Date dt = new Date();
   try {
      // video capture file name
      recorder = new ATUTestRecorder(System.getProperty("userdir") + "\\TestVideos\\" , m.getName() +       "_" + d.format(dt), false);
   }
   catch (Exception e){
      Log.error("Error capturing videos");
   }
   //begin recording
   try {
      recorder.start();
   }
   catch (Exception e){
      Log.error("Error in beginning videos");
   }
}
@AfterMethod
public void amethod(iTestResult result) {
   try {
      recorder.stop();
   }
   catch (Exception e){
      Log.error("Error in stopping videos");
   }
}
For a Maven project, the pom.xml should have the setting −
Finding LCM of more than two (or array) numbers without using GCD in C++

We have an array A, we have to find the LCM of all elements without using the GCD operation. If the array is like {4, 6, 12, 24, 30}, then the LCM will be 120.
The LCM can be calculated easily for two numbers. We have to follow this algorithm to get the LCM.
getLCM(a, b) −
begin
   if a > b, then m := a, otherwise m := b
      while true do
         if m is divisible by both a and b, then return m
            m := m + 1
   done
end
Use this function to get LCM of first two numbers of array, then result of LCM will be used to find LCM of next element, thus we can get the result
 Live Demo
#include <iostream>
using namespace std;
int getLCM(int a, int b){
   int m;
   m = (a > b) ? a : b;
   while(true){
      if(m % a == 0 && m % b == 0)
      return m;
      m++;
   }
}
int getLCMArray(int arr[], int n){
   int lcm = getLCM(arr[0], arr[1]);
   for(int i = 2; i < n; i++){
      lcm = getLCM(lcm, arr[i]);
   }
   return lcm;
}
int main() {
   int arr[] = {4, 6, 12, 24, 30};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "LCM of array elements: " << getLCMArray(arr, n);
}
LCM of array elements: 120
Python | Pandas Dataframe.pop()

30 Dec, 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 Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop doesn’t require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly. 
Syntax: DataFrame.pop(item)Parameters: item: Column name to be popped in stringReturn type: Popped column in form of Pandas Series
To download the CSV used in code, click here.Example #1: In this example, a column have been popped and returned by the function. The new data frame is then compared with the old one. 
Python3
import pandas as pd# importing pandas package data = pd.read_csv("nba.csv")# making data frame from csv file popped_col = data.pop("Team")# storing data in new var data# display
Output: In the output images, the data frames are compared before and after using .pop(). As shown in second image, Team column has been popped out.Dataframe before using .pop()  
Dataframe after using .pop()  
  Example #2: Popping and pushing in other data frame In this example, a copy of data frame is made and the popped column is inserted at the end of the other data frame. 
Python3
import pandas as pd# importing pandas package data = pd.read_csv("nba.csv")# making data frame from csv file new = data.copy()# creating independent copy of data frame popped_col = data.pop("Name")# storing data in new var new["New Col"]= popped_col# creating new col and passing popped col new# display
Output: As shown in the output image, the new data frame is having the New col at the end which is nothing but the Name column which was popped out earlier.  
 
sumitgumber28
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Taking multiple inputs from user in Python

08 Jul, 2022
The developer often wants a user to enter multiple values or inputs in one line. In C++/C user can take multiple inputs in one line using scanf but in Python user can take multiple values or inputs in one line by two methods. 
Using split() method
Using List comprehension
Using split() method : This function helps in getting multiple inputs from users. It breaks the given input by the specified separator. If a separator is not provided then any white space is a separator. Generally, users use a split() method to split a Python string but one can use it in taking multiple inputs.
Syntax : 
input().split(separator, maxsplit)
Example : 
Python3
# Python program showing how to# multiple input using split  # taking two inputs at a timex, y = input("Enter two values: ").split()print("Number of boys: ", x)print("Number of girls: ", y)print()  # taking three inputs at a timex, y, z = input("Enter three values: ").split()print("Total number of students: ", x)print("Number of boys is : ", y)print("Number of girls is : ", z)print()  # taking two inputs at a timea, b = input("Enter two values: ").split()print("First number is {} and second number is {}".format(a, b))print()  # taking multiple inputs at a time # and type casting using list() functionx = list(map(int, input("Enter multiple values: ").split()))print("List of students: ", x)
Output:  
Using List comprehension : List comprehension is an elegant way to define and create list in Python. We can create lists just like mathematical statements in one line only. It is also used in getting multiple inputs from a user. 
Example: 
Python3
# Python program showing# how to take multiple input# using List comprehension  # taking two input at a timex, y = [int(x) for x in input("Enter two values: ").split()]print("First Number is: ", x)print("Second Number is: ", y)print()  # taking three input at a timex, y, z = [int(x) for x in input("Enter three values: ").split()]print("First Number is: ", x)print("Second Number is: ", y)print("Third Number is: ", z)print()  # taking two inputs at a timex, y = [int(x) for x in input("Enter two values: ").split()]print("First number is {} and second number is {}".format(x, y))print()  # taking multiple inputs at a time x = [int(x) for x in input("Enter multiple values: ").split()]print("Number of list is: ", x) 
Output :  
Note: The above examples take input separated by spaces. In case we wish to take input separated by comma (, ), we can use the following: 
Python3
# taking multiple inputs at a time separated by commax = [int(x) for x in input("Enter multiple value: ").split(",")]print("Number of list is: ", x) 
Please see https://ide.geeksforgeeks.org/BHf0Cxr4mx for a sample run. 
rakeshsshankala
eramitkrgupta
punamsingh628700
tyunsworth
python-input-output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Search (bisect) in Python

Here we will see the bisect in Python. The bisect is used for binary search. The binary search technique is used to find elements in sorted list. The bisect is one library function.
We will see three different task using bisect in Python.
The bisect.bisect_left(a, x, lo = 0, hi = len(a)) this function is used to return the left most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist.
from bisect import bisect_left
def BinSearch(a, x):
   i = bisect_left(a, x)
   if i != len(a) and a[i] == x:
      return i
   else:
      return -1
a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]
x = int(4)
pos = BinSearch(a, x)
if pos == -1:
   print(x, "is absent")
else:
   print("First occurrence of", x, "is at position", pos)
First occurrence of 4 is at position 2
Using the bisect_left option, we can get the greater value, which is smaller than the x (key).
from bisect import bisect_left
def BinSearch(a, x):
   i = bisect_left(a, x)
   if i :
      return i-1
   else:
      return -1
a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]
x = int(8)
pos = BinSearch(a, x)
if pos == -1:
   print(x, "is absent")
else:
   print("Larger value, smaller than", x, "is at position", pos)
Larger value, smaller than 8 is at position 4
The bisect.bisect_right(a, x, lo = 0, hi = len(a)) this function is used to return the right most insertion point of x in a sorted list. Last two parameters are optional in this case. These two are used to search in sublist.
from bisect import bisect_right
def BinSearch(a, x):
   i = bisect_right(a, x)
   if i != len(a) + 1 and a[i-1] == x:
      return i-1
   else:
      return -1
a = [2, 3, 4, 4, 5, 8, 12, 36, 36, 36, 85, 89, 96]
x = int(36)
pos = BinSearch(a, x)
if pos == -1:
   print(x, "is absent")
else:
   print("Right most occurrence of", x, "is at position", pos)
Right most occurrence of 36 is at position 9
jQuery - children( [selector]) Method

The children( [selector] ) method gets a set of elements containing all of the unique immediate children of each of the matched set of elements.
Here is the simple syntax to use this method −
selector.children( [selector] )

Here is the description of all the parameters used by this method −
selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected.
selector − This is an optional argument to filter out all the childrens. If not supplied then all the childrens are selected.
Following is a simple example a simple showing the usage of this method −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
		
      <script>
         $(document).ready(function(){
            $("div").children(".selected").addClass("blue");
         });
      </script>
		
      <style>
         .blue { color:blue; }
      </style>
   </head>
	
   <body>
      <div>
         <span>Hello</span>
         <p class = "selected">Hello Again</p>
         <div class = "selected">And Again</div>
         <p class = "biggest">And One Last Time</p>
      </div>
   </body>
</html>
This would apply blue color to all children with a class "selected" of each div, as shown below −
Hello Again
And One Last Time
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
		
      <script>
         $(document).ready(function(){
            $("div").children(".selected").addClass("blue");
         });
      </script>
		
      <style>
         .blue { color:blue; }
      </style>
   </head>
	
   <body>
      <div>
         <span>Hello</span>
         <p class = "blue">Hello Again</p>
         <div class = "blue">And Again</div>
         <p class = "biggest">And One Last Time</p>
      </div>
   </body>
</html>
This will produce following result −
Hello Again
And One Last Time
What is Register Renaming?

Register renaming is a standard approach for eliminating false data dependencies, such as WAR and WAW dependencies, between register data. It was first suggested by Tjaden and Flynn in 1970.
They intended to use register renaming for a definite set of instructions that compare more or less to the class of load instructions, although it does not use the phrase ‘renaming’. Keller (1975) introduced the designation ‘register renaming’ and interpreted it for all suitable instructions.
Register Renaming presumes the three-operand instruction format. To illustrate this precondition, let us consider a two-operand instruction, say
ad r1, r2
with the interpretation
r1←(r1)+(r2)

In the two instruction format, the result is written back in place of one of the source operands, in the example in the place of r1. However, for the renaming of the destination, a register different from that containing a source operand (r1) has to be used, say r11. Thus, after renaming we get
r11←(r1)+(r2)
This means that the renaming of two-operand instruction always ends up as three-operand instruction. As a consequence, two-operand instructions can only be renamed using an internal two to three operand conversion.
Register renaming can be implemented either statistically or dynamically as shown in the figure.
Static Implementation − In a static implementation, register renaming is carried out during compilation. This technique was first introduced in parallel optimizing compilers for pipelined processors, and later in superscalar processors.
Dynamic Implementation − When register renaming is implemented dynamically, renaming takes place during execution. This requires extra circuitry in terms of supplementary register space, additional data path, and logic. The dynamic renaming has been utilized in advanced superscalar processors because the early 1990s.
The renaming was introduced in two stages. In the first stage, the renaming was only partially implemented. Here, renaming is confined to one or a few particular data types. For instance, the Power1, Power2, PowerPC 601 and Nx586 processors employ partial renaming.
In both stages, IBM was the first vendor to introduce renaming, initially in its Power-line with the Power1 (RS/6000) and later in the high-end processors of its ES/9000 family. IBM continued to implement full renaming in the power-based PowerPC-line except for the first model, the PowerPC 601. All vendors of significant superscalar processors have introduced renaming in their most recent models, except DEC in its α-line and Sun in the UltraSparc.
List in C++ Standard Template Library (STL)

06 Jul, 2022
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list. Below is the program to show the working of some functions of List: 
CPP
// CPP program to show the implementation of List#include <iostream>#include <iterator>#include <list>using namespace std;  // function for printing the elements in a listvoid showlist(list<int> g){    list<int>::iterator it;    for (it = g.begin(); it != g.end(); ++it)        cout << '\t' << *it;    cout << '\n';}  // Driver Codeint main(){      list<int> gqlist1, gqlist2;      for (int i = 0; i < 10; ++i) {        gqlist1.push_back(i * 2);        gqlist2.push_front(i * 3);    }    cout << "\nList 1 (gqlist1) is : ";    showlist(gqlist1);      cout << "\nList 2 (gqlist2) is : ";    showlist(gqlist2);      cout << "\ngqlist1.front() : " << gqlist1.front();    cout << "\ngqlist1.back() : " << gqlist1.back();      cout << "\ngqlist1.pop_front() : ";    gqlist1.pop_front();    showlist(gqlist1);      cout << "\ngqlist2.pop_back() : ";    gqlist2.pop_back();    showlist(gqlist2);      cout << "\ngqlist1.reverse() : ";    gqlist1.reverse();    showlist(gqlist1);      cout << "\ngqlist2.sort(): ";    gqlist2.sort();    showlist(gqlist2);      return 0;}
List 1 (gqlist1) is :     0    2    4    6    8    10    12    14    16    18

List 2 (gqlist2) is :     27    24    21    18    15    12    9    6    3    0

gqlist1.front() : 0
gqlist1.back() : 18
gqlist1.pop_front() :     2    4    6    8    10    12    14    16    18

gqlist2.pop_back() :     27    24    21    18    15    12    9    6    3

gqlist1.reverse() :     18    16    14    12    10    8    6    4    2

gqlist2.sort():     3    6    9    12    15    18    21    24    27
Functions
Definition
Recent Articles on C++ list
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anshikajain26
cpp-containers-library
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Sorting a vector in C++
2D Vector In C++ With User Defined Size
Virtual Function in C++