code-rag-bench/online-tutorials huggingface dataset:
Python Pandas – Find unique values from multiple columns

To find unique values from multiple columns, use the unique() method. Let’s say you have Employee Records with “EmpName” and “Zone” in your Pandas DataFrame. The name and zone can get repeated since two employees can have similar names and a zone can have more than one employee. In that case, if you want unique Employee names, then use the unique() for DataFrame.
At first, import the required library. Here, we have set pd as an alias −
import pandas as pd
At first, create a DataFrame. Here, we have two columns −
dataFrame = pd.DataFrame(
   {
      "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],"Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North']
   }
)
Fetch unique Employee Names and Zone from the DataFrame column “EmpName” and “Zone” −
{pd.concat([dataFrame['EmpName'],dataFrame['Zone']]).unique()}
Following is the complete code −
import pandas as pd

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "EmpName": ['John', 'Ted', 'Jacob', 'Scarlett', 'Ami', 'Ted', 'Scarlett'],"Zone": ['North', 'South', 'South', 'East', 'West', 'East', 'North']
   }
)

print("DataFrame ...\n",dataFrame)

# Fetch unique values from multiple columns
print(f"\nFetching unique Values from the two columns and concatenate them:\n \
{pd.concat([dataFrame['EmpName'],dataFrame['Zone']]).unique()}")
This will produce the following output −
DataFrame ...
    EmpName   Zone
0      John  North
1       Ted  South
2     Jacob  South
3  Scarlett   East
4       Ami   West
5       Ted   East
6  Scarlett  North

Fetching unique Values from the two columns and concatenate them:
['John' 'Ted' 'Jacob' 'Scarlett' 'Ami' 'North' 'South' 'East' 'West']
C library function - strtok()

The C library function char *strtok(char *str, const char *delim) breaks string str into a series of tokens using the delimiter delim.
Following is the declaration for strtok() function.
char *strtok(char *str, const char *delim)
str − The contents of this string are modified and broken into smaller strings (tokens).
str − The contents of this string are modified and broken into smaller strings (tokens).
delim − This is the C string containing the delimiters. These may vary from one call to another.
delim − This is the C string containing the delimiters. These may vary from one call to another.
This function returns a pointer to the first token found in the string. A null pointer is returned if there are no tokens left to retrieve.
The following example shows the usage of strtok() function.
#include <string.h>
#include <stdio.h>

int main () {
   char str[80] = "This is - www.tutorialspoint.com - website";
   const char s[2] = "-";
   char *token;
   
   /* get the first token */
   token = strtok(str, s);
   
   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token );
    
      token = strtok(NULL, s);
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
This is 
  www.tutorialspoint.com 
  website


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Go - Range

The range keyword is used in for loop to iterate over items of an array, slice, channel or map. With array and slices, it returns the index of the item as integer. With maps, it returns the key of the next key-value pair. Range either returns one value or two. If only one value is used on the left of a range expression, it is the 1st value in the following table.
The following paragraph shows how to use range −
package main

import "fmt"

func main() {
   /* create a slice */
   numbers := []int{0,1,2,3,4,5,6,7,8} 
   
   /* print the numbers */
   for i:= range numbers {
      fmt.Println("Slice item",i,"is",numbers[i])
   }
   
   /* create a map*/
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
   
   /* print map using keys*/
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* print map using key-value*/
   for country,capital := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",capital)
   }
}
When the above code is compiled and executed, it produces the following result −
Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Split String with Dot (.) in Java

Let’s say the following is our string.
String str = "This is demo text.This is sample text!";
To split a string with dot, use the split() method in Java.
str.split("[.]", 0);
The following is the complete example.
 Live Demo
public class Demo {
    public static void main(String[] args) {
       String str = "This is demo text.This is sample text!";
       String[] res = str.split("[.]", 0);
       for(String myStr: res) {
          System.out.println(myStr);
       }
    }
}
This is demo text
This is sample text!
How to draw an average line for a scatter plot in MatPlotLib?

To draw an average line for a plot in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make x and y data points using numpy.
Make x and y data points using numpy.
Use subplots() method to create a figure and a set of subplots.
Use subplots() method to create a figure and a set of subplots.
Use plot() method for x and y data points.
Use plot() method for x and y data points.
Find the average value of the array, x.
Find the average value of the array, x.
Plot x and y_avg data points using plot() method.
Plot x and y_avg data points using plot() method.
Place a legend on the figure.
Place a legend on the figure.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

x = np.array([3, 4, 5, 6, 7, 8, 9])
y = np.array([6, 5, 4, 3, 2, 1, 6])

fig, ax = plt.subplots()
ax.plot(x, y, 'o-', label='line plot')
y_avg = [np.mean(x)] * len(x)
ax.plot(x, y_avg, color='red', lw=6, ls='--', label="average plot")

plt.legend(loc=0)
plt.show()
VBA - WeekDay

The WeekDay function returns an integer from 1 to 7 that represents the day of the week for the specified date.
Weekday(date[,firstdayofweek])  

Date − A required parameter. The weekday will return a specified date.
Date − A required parameter. The weekday will return a specified date.
Firstdayofweek − An optional parameter. Specifies the first day of the week. It can take the following values.

0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting
1 = vbSunday - Sunday
2 = vbMonday - Monday
3 = vbTuesday - Tuesday
4 = vbWednesday - Wednesday
5 = vbThursday - Thursday
6 = vbFriday - Friday
7 = vbSaturday - Saturday


Firstdayofweek − An optional parameter. Specifies the first day of the week. It can take the following values.
0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting
0 = vbUseSystemDayOfWeek - Use National Language Support (NLS) API setting
1 = vbSunday - Sunday
1 = vbSunday - Sunday
2 = vbMonday - Monday
2 = vbMonday - Monday
3 = vbTuesday - Tuesday
3 = vbTuesday - Tuesday
4 = vbWednesday - Wednesday
4 = vbWednesday - Wednesday
5 = vbThursday - Thursday
5 = vbThursday - Thursday
6 = vbFriday - Friday
6 = vbFriday - Friday
7 = vbSaturday - Saturday
7 = vbSaturday - Saturday
Add a button and add the following function.
Private Sub Constant_demo_Click()
   msgbox("Line 1: " & Weekday("2013-05-16",1))
   msgbox("Line 2: " & Weekday("2013-05-16",2))
   msgbox("Line 3: " & Weekday("2013-05-16",2))
   msgbox("Line 4: " & Weekday("2010-02-16"))
   msgbox("Line 5: " & Weekday("2010-02-17"))
   msgbox("Line 6: " & Weekday("2010-02-18"))
End Sub
When you execute the above function, it produces the following output.
Line 1: 5
Line 2: 4
Line 3: 4
Line 4: 3
Line 5: 4
Line 6: 5


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Find Last Digit of a^b for Large Numbers in C++

In this problem, we are given two numbers a and b. Our task is to find Last Digit of a^b for Large Numbers. 
Let’s take an example to understand the problem, 
Input: a = 4 b = 124
Output: 6
Explanation: 
The value of a^b is 4.523128486 * 1074
The solution to the problem is based on the fact that all the exponents of a number will be repeated after 4 exponent values.
So, we will find the value of b%4. Also, for any base value, the last digit of its power is decided by the last digit of the base value.
So, the resultant value will be calculated as
Last value of a  ^ (b%4)
Live Demo
#include <bits/stdc++.h>
using namespace std;

int calcModulus(char b[], int a)
{
   int mod = 0;

   for (int i = 0; i < strlen(b); i++)
      mod = (mod * 10 + b[i] - '0') % a;

   return mod;
}

int calcLastDigitInExpo(char a[], char b[]) {

   int len_a = strlen(a), len_b = strlen(b);

   if (len_a == 1 && len_b == 1 && b[0] == '0' && a[0] == '0')
      return 1;
   if (len_b == 1 && b[0] == '0')
      return 1;
   if (len_a == 1 && a[0] == '0')
      return 0;

   int exponent = (calcModulus(b, 4) == 0) ? 4 : calcModulus(b, 4);
   int base = a[len_a - 1] - '0';
   int result = pow(base, exponent);
   return result % 10;
}

int main()
{
   char a[] = "559", b[] = "4532";
   cout<<"The last digit in of the value is "<<calcLastDigitInExpo(a, b);
   return 0;
}
The last digit in of the value is 1
Batch Script - Relational Operators

Relational operators allow of the comparison of objects. Below are the relational operators available.
The following code snippet shows how the various operators can be used.
@echo off 
SET /A a = 5 
SET /A b = 10 
if %a% EQU %b% echo A is equal to than B 
if %a% NEQ %b% echo A is not equal to than B 
if %a% LSS %b% echo A is less than B 
if %a% LEQ %b% echo A is less than or equal B
if %a% GTR %b% echo A is greater than B 
if %a% GEQ %b% echo A is greater than or equal to B
The above command produces the following output.
A is not equal to than B
A is less than B
A is less than or equal B

 Print
 Add Notes
 Bookmark this page
Minimum Steps | Practice | GeeksforGeeks

Anuj has challenged Arun to climb N stairs but at only in powers of P and Q. Now Arun being a lazy guy wants to do this in minimum number of steps possible. So he has asked for your help to calculate the minimum number of steps he requires to take for climbing N stairs ( 1 step = some power of P or Q stairs (including zeroth power) ).

Example 1:
Input: 
N = 15, P = 2, Q = 3
Output:
3
Explanation:
We can make 15 by (8,4,3)
or (9,3,3) both takes 3 steps.
 
Example 2:
Input: 
N = 19, P = 4, Q = 3
Output:
2
Explanation:
In the second case, we can make
19 by (16,3) which is 2 steps.
 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function moves() which takes three integers N, P and Q as inputs and returns the number of steps that Arun needs to take to climb N stairs in powers of P & Q. If fit is not possible print -1.
 
Expected Time Complexity: O(N. log(N))
Expected Auxiliary Space: O(N. log(N))
 
Constraints:
1 ≤ N, P, Q ≤ 105
No Comments to load
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
C++ Program to Find the Mode in a Data Set

This is a C++ program to find the Mode in a data set.
Begin
   function insertinset() to insert data in the set.
   Create newnode and temp(t) node.
   Node to be inserted in the list using newnode.
   If head is null then
      assign new node to head and increase the count.
   During insertion perform insertion sort for sorting data.
   If the newnode->data is equal to any of the element present in the set,
      then just increment count.
End
#include <iostream>
using namespace std;
struct set // a structure set to declare variables
{
   int data;
   int cnt;
   set *n;
};
set* insertinset(set *head, int n) {
   set *newnode = new set; //to use structure set’s variables.
   set *t = new set;
   newnode->data = n;
   newnode->cnt = 0;
   newnode->n = NULL;
   if(head == NULL) {
      head = newnode;
      head->cnt++;
      return head;
   } else {
      t = head;
      if(newnode->data < head->data) {
         newnode->n = head;
         head = newnode;
         newnode->cnt++;
         return head;
      } else if(newnode->data == head->data) {
         head->cnt++;
         return head;
      }
      while(t->n!= NULL) {
         if(newnode->data == (t->n)->data) {
            (t->n)->cnt++;
            return head;
         }
         if(newnode->data < (t->n)->data)
            break;
         t=t->n;
      }
      newnode->n = t->n;
      t->n = newnode;
      newnode->cnt++;
      return head;
   }
}
int main() {
   int n, i, num, max = 0, c;
   set *head = new set;
   head = NULL;
   cout<<"\nEnter the number of data element to be sorted: ";
   cin>>n;
   for(i = 0; i < n; i++) {
      cout<<"Enter element "<<i+1<<": ";
      cin>>num;
      head = insertinset(head, num); //call the function
   }
   cout<<"\nSorted Distinct Data ";
   while(head != NULL) // if head is not equal to null
   {
      if(max < head->cnt) {
         c = head->data;
         max = head->cnt;
      }
      cout<<"->"<<head->data<<"("<<head->cnt<<")"; //return the count of the data.
      head = head->n;
   }
   cout<<"\nThe Mode of given data set is "<<c<<" and occurred "<<max<<" times.";
   return 0;
}
Enter the number of data element to be sorted: 10
Enter element 1: 1
Enter element 2: 2
Enter element 3: 0
Enter element 4: 2
Enter element 5: 3
Enter element 6: 7
Enter element 7: 6
Enter element 8: 2
Enter element 9: 1
Enter element 10: 1
Sorted Distinct Data ->0(1)->1(3)->2(3)->3(1)->6(1)->7(1)
The Mode of given data set is 1 and occurred 3 times.
Batch Script - Deleting from the Registry

Deleting from the registry is done via the REG DEL command. Note that in order to delete values from the registry you need to have sufficient privileges on the system to perform this operation.
The REG DELETE command has the following variations. In the second variation, the default value will be removed and in the last variation all the values under the specified key will be removed.
REG DELETE [ROOT\]RegKey /v ValueName [/f] 
   REG DELETE [ROOT\]RegKey /ve [/f] 
   REG DELETE [ROOT\]RegKey /va [/f]

Where
ValueName − The value, under the selected RegKey, to edit.
ValueName − The value, under the selected RegKey, to edit.
/f − Force an update without prompting "Value exists, overwrite Y/N".
/f − Force an update without prompting "Value exists, overwrite Y/N".
@echo off
REG DELETE HKEY_CURRENT_USER\Console /v Test /f
REG QUERY HKEY_CURRENT_USER\Console /v Test
In the above example, the first part is to delete a key into the registry under the location HKEY_CURRENT_USER\Console. This key has the name of Test. The second command just displays what was deleted to the registry by using the REG QUERY command. From this command, we should expect an error, just to ensure that our key was in fact deleted.
Following will be the output of the above program. The first line of the output shows that the ‘Delete’ functionality was successful and the second output shows an error which was expected to confirm that indeed our key was deleted from the registry.
The operation completed successfully. 
ERROR: The system was unable to find the specified registry key or value.

 Print
 Add Notes
 Bookmark this page
C Program to Find a pair with the given difference - GeeksforGeeks

21 Dec, 2021
Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples:  
Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78
Output: Pair Found: (2, 80)

Input: arr[] = {90, 70, 20, 80, 50}, n = 45
Output: No Such Pair
 
The simplest method is to run two loops, the outer loop picks the first element (smaller element) and the inner loop looks for the element picked by outer loop plus n. Time complexity of this method is O(n^2).We can use sorting and Binary Search to improve time complexity to O(nLogn). The first step is to sort the array in ascending order. Once the array is sorted, traverse the array from left to right, and for each element arr[i], binary search for arr[i] + n in arr[i+1..n-1]. If the element is found, return the pair. Both first and second steps take O(nLogn). So overall complexity is O(nLogn). The second step of the above algorithm can be improved to O(n). The first step remain same. The idea for second step is take two index variables i and j, initialize them as 0 and 1 respectively. Now run a linear loop. If arr[j] – arr[i] is smaller than n, we need to look for greater arr[j], so increment j. If arr[j] – arr[i] is greater than n, we need to look for greater arr[i], so increment i. Thanks to Aashish Barnwal for suggesting this approach. The following code is only for the second step of the algorithm, it assumes that the array is already sorted.  
C
// C program to find a pair with the given difference#include <stdio.h>  // The function assumes that the array is sorted bool findPair(int arr[], int size, int n){    // Initialize positions of two elements    int i = 0;      int j = 1;      // Search for a pair    while (i<size && j<size)    {        if (i != j && arr[j]-arr[i] == n)        {            printf("Pair Found: (%d, %d)", arr[i], arr[j]);            return true;        }        else if (arr[j]-arr[i] < n)            j++;        else            i++;    }      printf("No such pair");    return false;}  // Driver program to test above functionint main(){    int arr[] = {1, 8, 30, 40, 100};    int size = sizeof(arr)/sizeof(arr[0]);    int n = 60;    findPair(arr, size, n);    return 0;}
Output:  
Pair Found: (40, 100)
Hashing can also be used to solve this problem. Create an empty hash table HT. Traverse the array, use array elements as hash keys and enter them in HT. Traverse the array again look for value n + arr[i] in HT.  
Please refer complete article on Find a pair with the given difference for more details!
Amazon
Binary Search
Visa
C Language
C Programs
Searching
Sorting
Amazon
Visa
Searching
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
Strings in C
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
C Program to read contents of Whole File
Header files in C/C++ and its uses
Future class in Dart Programming

There are different classes and keywords in Dart which we can use when we want to run Asynchronous code. The future class allows us to run asynchronous code and we can also avoid the callback hell with the help of it. A future mainly represents the result of an asynchronous operation.
In Dart, there are many standards library calls that return a future, some of them are −
http.get
http.get
SharedPreference.getInstance()
SharedPreference.getInstance()
A future in Dart can have two states, these are −
Completed - When the operation of the future finishes and the future complete with a value or with an error.
Completed - When the operation of the future finishes and the future complete with a value or with an error.
Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future.
Uncompleted - When a function is called, and it returned a future, the function queues up and returns an uncompleted future.
Future<T>
In Dart, if a future doesn't produce any usable value then the future's type is Future<void>. Also, if the function doesn't explicitly return any value, then the return type is also Future<void>.
Let's consider a small example where we are declaring a future that will display a message in a delayed fashion.
Consider the example shown below:
   Future<void> printDelayedMessage() {
      return Future.delayed(Duration(seconds: 4), () => print('Delayed Output.'));
}

void main() {
   printDelayedMessage();
   print('First output ...');
}
In the above example, we have a function named printDelayedMessage() that returns a future of type void, and we have a future that is using a method named delayed through which we are able to print the delayed output to the terminal.
First output ...
Delayed Output.
It should be noted the second line of the output will be printed after 4 seconds.
Futures in Dart also allows us to register callbacks with the help of the then methods.
Consider an example shown below −
void main() {
   var userEmailFuture = getUserEmail();
   // register callback
   userEmailFuture.then((userId) => print(userId));
   print('Hello');
}

// method which computes a future
Future<String> getUserEmail() {
   // simulate a long network call
   return Future.delayed(Duration(seconds: 4), () => "mukul@tutorialspoint.com");
}
Hello
mukul@tutorialspoint.com
Tryit Editor v3.7

CSS Style Images
Tryit: Image hover - Fade in a box
Type Hinting in PHP 7

PHP 7 uses two types of hinting in scalar type declaration and return type declaration −
Weak type hinting
Strict type hinting
By default, PHP 7 works in weak type checking mode.Weak type checking will not give any error or fatal error.When a type declaration mismatch occurs it will simply execute the code without throwing any error.
By using strict_typesdeclare(), we can control the weak type checking.
declare(strict_types=0);
//weak type-checking; we should set the strict value = 0
Live Demo
<?php
   $x=10; // integer variable x =10 value
   $y=20.20; // using floating point number y=20.20 value
   function add(int $x, int $y){
      return $x + $y;
   }
   echo add($x, $y);
?>
The code will produce the following output −
30
In the above example, we are not using a strict value for a parameter. We used two integer variables, x, and y. For x=10 and y is using the floating number 20.20, but y will not produce any error; it will simply give the output integer value 30.
Live Demo
<?php
   function returnadd(int ...$integers){
      return array_sum($integers);
   }
   var_dump(returnadd(2, '3', 4.1));
?>
The output for the above program will be −
int(9)
Strict type hinting will give a Fatal Error when a type declaration mismatch occurs. We can say that strict type hinting accepts a variable of the exact type of the type declaration, else it will throw the TypeError mismatch.
In the strict type hinting, the first statement in a file must be declared (strict_types=1), otherwise, it will produce a compiler error. It does not affect the other included files which are not specified in files, which means it only affects the specific file it is used.
The strict type hinting directive is completely compile-time and cannot be controlled at runtime.
Live Demo
<?php
   declare (strict_types=1);
   function returnadd(float $x , float $y){
      return $x+$y;
   }
   var_dump(returnadd(3.1,2.1)); //output float(5.2)
   var_dump(returnadd(3, "2 days")); //fatal error
?>
The above strict type hinting program will be −
float(5.2)
Fatal error: Uncaught TypeError: Argument 2 passed to returnadd() must be of the type float, string given, called in C:\xampp\htdocs\gud.php on line 7 and defined in C:\xampp\htdocs\gud.php:3 Stack trace: #0 C:\xampp\htdocs\gud.php(7): returnadd(3, '2 days') #1 {main} thrown in C:\xampp\htdocs\gud.php on line 3
Live Demo
<?php
   declare(strict_types=1); // strict mode checking
   $x='1'; // string
   $y=20; //integer number
   function add(int $x, int $y){
      return $x + $y;
   }
   var_dump(add($x, $y));
?>
It will produce the output “fatal error”
In the above strict type declaration example, if we declare the strict_type value is 1, the code will give the output “Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, a string is given”.
Batch Script - Copying Registry Keys

Copying from the registry is done via the REG COPY command. Note that in order to copy values from the registry, you need to have sufficient privileges on the system to perform this operation on both the source location and the destination location.
REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey

@echo off 
REG COPY HKEY_CURRENT_USER\Console HKEY_CURRENT_USER\Console\Test 
REG QUERY HKEY_CURRENT_USER\Console\Test
In the above example, the first part is to copy the contents from the location HKEY_CURRENT_USER\Console into the location HKEY_CURRENT_USER\Console\Test on the same machine. The second command is used to query the new location to check if all the values were copied properly.
Following is the output of the above program. The first line of the output shows that the ‘Copy’ functionality was successful and the second output shows the values in our copied location.
The operation completed successfully.
HKEY_CURRENT_USER\Console\Test
   HistoryNoDup REG_DWORD 0x0
   FullScreen REG_DWORD 0x0
   ScrollScale REG_DWORD 0x1
   ExtendedEditKeyCustom REG_DWORD 0x0
   CursorSize REG_DWORD 0x19
   FontFamily REG_DWORD 0x0
   ScreenColors REG_DWORD 0x7
   TrimLeadingZeros REG_DWORD 0x0
   WindowSize REG_DWORD 0x190050
   LoadConIme REG_DWORD 0x1
   PopupColors REG_DWORD 0xf5
   QuickEdit REG_DWORD 0x0
   WordDelimiters REG_DWORD 0x0
   ColorTable10 REG_DWORD 0xff00
   ColorTable00 REG_DWORD 0x0
   ColorTable11 REG_DWORD 0xffff00
   ColorTable01 REG_DWORD 0x800000
   ColorTable12 REG_DWORD 0xff

 Print
 Add Notes
 Bookmark this page
Java String compareTo() Method

❮ String Methods

Compare two strings:
String myStr1 = "Hello";
String myStr2 = "Hello";
System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal

Try it Yourself »

The compareTo() method compares two strings 
lexicographically.
The comparison is based on the Unicode value of each character in the 
strings.
The method returns 0 if the string is equal to the other string.
  A value less than 0 is returned if the string is less than the other string 
  (less characters) and a value greater than 0 if the string is greater than the other string 
  (more characters).
Tip: Use 
compareToIgnoreCase() to compare two strings lexicographyically, ignoring 
lower case and upper case differences.
Tip: Use the equals() method to compare two strings without consideration of Unicode values.
public int compareTo(String string2)
public int compareTo(Object object)

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
PostgreSQL - REGEXP_MATCHES Function - GeeksforGeeks

01 Feb, 2021
The PostgreSQL REGEXP_MATCHES() function is used to match a POSIX regular expression against a string and subsequently returns the strings that match the pattern.
Syntax:REGEXP_MATCHES(source_string, pattern [, flags])


Let’s analyze the above syntax:
The source is a string from which the regular expression matches and returns the substring.
The pattern is a POSIX regular expression for matching the source string.
The flags argument handles the function when more tha one character matches the pattern.
The REGEXP_MATCHES() function returns the queried string based on the matches.
Example 1:
Suppose, you have a social networking’s post as follows:
'Learning #Geeksforgeeks #geekPower'


The following statement allows you to extract the hashtags such as Geeksforgeeks and geekPower:
SELECT 
    REGEXP_MATCHES('Learning #Geeksforgeeks #geekPower', 
         '#([A-Za-z0-9_]+)', 
        'g');


Output:
Example 2:
This is common for all patterns that can be matched using the Regular Expressions as shown in the below example:
SELECT REGEXP_MATCHES('ABC', '^(A)(..)$', 'g');


Output:
PostgreSQL-function
PostgreSQL-String-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Introduction to Stored Procedures
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Joins
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Rename Table
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
PyQt5 - QRadioButton Widget

A QRadioButton class object presents a selectable button with a text label. The user can select one of many options presented on the form. This class is derived from QAbstractButton class.
Radio buttons are autoexclusive by default. Hence, only one of the radio buttons in the parent window can be selected at a time. If one is selected, previously selected button is automatically deselected. Radio buttons can also be put in a QGroupBox or QButtonGroup to create more than one selectable fields on the parent window.
The following listed methods of QRadioButton class are most commonly used.
setChecked()
Changes the state of radio button
setText()
Sets the label associated with the button
text()
Retrieves the caption of button
isChecked()
Checks if the button is selected
Default signal associated with QRadioButton object is toggled(), although other signals inherited from QAbstractButton class can also be implemented.
Here two mutually exclusive radio buttons are constructed on a top level window.
Default state of b1 is set to checked by the statement −
Self.b1.setChecked(True)

The toggled() signal of both the buttons is connected to btnstate() function. Use of lambda allows the source of signal to be passed to the function as an argument.
self.b1.toggled.connect(lambda:self.btnstate(self.b1))
self.b2.toggled.connect(lambda:self.btnstate(self.b2))

The btnstate() function checks state of button emitting toggled() signal.
if b.isChecked() == True:
      print b.text()+" is selected"
   else:
      print b.text()+" is deselected"
Complete code for QRadioButton example is as below −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Radiodemo(QWidget):
   def __init__(self, parent = None):
      super(Radiodemo, self).__init__(parent)
		
      layout = QHBoxLayout()
      self.b1 = QRadioButton("Button1")
      self.b1.setChecked(True)
      self.b1.toggled.connect(lambda:self.btnstate(self.b1))
      layout.addWidget(self.b1)
		
      self.b2 = QRadioButton("Button2")
      self.b2.toggled.connect(lambda:self.btnstate(self.b2))

      layout.addWidget(self.b2)
      self.setLayout(layout)
      self.setWindowTitle("RadioButton demo")
		
   def btnstate(self,b):
      if b.text() == "Button1":
         if b.isChecked() == True:
            print b.text()+" is selected"
         else:
            print b.text()+" is deselected"
				
      if b.text() == "Button2":
         if b.isChecked() == True:
            print b.text()+" is selected"
         else:
            print b.text()+" is deselected"
				
def main():

   app = QApplication(sys.argv)
   ex = Radiodemo()
   ex.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   main()
The above code produces the following output −
Button1 is deselected
Button2 is selected
Button2 is deselected
Button1 is selected


    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Get only specific values in an array of objects in JavaScript?

Let’s say the following is our array of objects −
var details = [{
   studentName: "John",
   studentMarks: 92
},
{
   studentName: "David",
   studentMarks: 89
},
{
   studentName: "Mike",
   studentMarks: 98
},
];
To get only specific values in an array of objects in JavaScript, use the concept of filter().
var details = [{
   studentName: "John",
   studentMarks: 92
},
{
   studentName: "David",
   studentMarks: 89
},
{
   studentName: "Mike",
   studentMarks: 98
},
];
var specificValuesFromArray = details.filter(obj => obj.studentMarks ===
92 || obj.studentMarks === 98);
console.log(specificValuesFromArray)
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo177.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo177.js
[
   { studentName: 'John', studentMarks: 92 },
   { studentName: 'Mike', studentMarks: 98 }
]
Updating nested document in MongoDB

To update the nested document, use $set. Let us create a collection with documents −
> db.demo315.insertOne({ _id :101,
...  details: [
...     {Name: 'Chris', subjects: [{id:1001, SubjectName:"MySQL"}]}
...  ]
... }
...)
{ "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo315.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "subjects" : [
            {
               "id" : 1001,
               "SubjectName" : "MySQL"
            }
         ]
      }
   ]
}
Following is the query to update the nested document in MongoDB −
> db.demo315.update ({_id:101}, { '$set': {"details.0.subjects.1.id" :1004} })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo315.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "details" : [
      {
         "Name" : "Chris",
         "subjects" : [
            {
               "id" : 1001,
               "SubjectName" : "MySQL"
            },
            {
               "id" : 1004
            }
         ]
      }
   ]
}
Python 3 - Number sin() Method

The sin() method returns the sine of x, in radians.
Following is the syntax for sin() method −
sin(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the sine of the parameter x.
The following example shows the usage of sin() method.
#!/usr/bin/python3
import math

print ("sin(3) : ",  math.sin(3))
print ("sin(-3) : ",  math.sin(-3))
print ("sin(0) : ",  math.sin(0))
print ("sin(math.pi) : ",  math.sin(math.pi))
print ("sin(math.pi/2) : ",  math.sin(math.pi/2))
When we run the above program, it produces the following result −
sin(3) :  0.14112000806
sin(-3) :  -0.14112000806
sin(0) :  0.0
sin(math.pi) :  1.22460635382e-16
sin(math.pi/2) :  1


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Automating Scrolling using Python-Opencv by Color Detection - GeeksforGeeks

13 Jan, 2021
Prerequisites: 
Opencv
PyAutoGUI
It is possible to perform actions without actually giving any input through touchpad or mouse. This article discusses how this can be done using opencv module. Here we will use color detection to scroll screen. When a certain color is detected by the program during execution the screen starts to scroll on its own.
Import module
Use cv2 to capture video, here to use default webcam use 0, and for any other cam use 1.
Read the captured video and store the video frame in a variable
Get every color of the frame.
Create a mask of the color required to take as input to scroll using their acceptable color ranges. Here it is taken as green.
Get contours and hierarchy from mask
Pass contours using for loop and calculate the area.
Add scroll mechanism when required color is detected(Green here).
Show the frame using cv2.imshow()and pass the frame name and the frame variable to show every captured frame, put the frame capture process in a while loop. To come out of the process use a wait key and break statement.
Then stop the window of webcam.
Below is the implementation.
Python3
import cv2import numpy as npimport pyautogui  low_green = np.array([25, 52, 72])high_green = np.array([102, 255, 255])  cap = cv2.VideoCapture(0)  prev_y = 0  while True:    ret, frame = cap.read()    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)    mask = cv2.inRange(hsv, low_green, high_green)    contours, hierarchy = cv2.findContours(        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)      for i in contours:        area = cv2.contourArea(i)        if area > 1000:            x, y, w, h = cv2.boundingRect(i)            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)            if y < prev_y:                pyautogui.press('space')            prev_y = y    cv2.imshow('frame', frame)    if cv2.waitKey(1) == ord('q'):        break  cap.release()cap.closeAllWindow()
Input:
Detecting green color
Python-OpenCV
Python-projects
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
exit() vs _Exit() in C/C++

The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It calls the constructor of class only. It is declared in “stdlib.h” header file in C language. It does not return anything.
The following is the syntax of exit()
void exit(int status_value);
Here,
status_value − The value which is returned to parent process.
The following is an example of exit()
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int main() {
   int x = 10;
   printf("The value of x : %d\n", x);
   exit(0);
   printf("Calling of exit()");
   return 0;
}
The value of x : 10
In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the statement in the printf(). The calling of exit() is as follows −
int x = 10;
printf("The value of x : %d\n", x);
exit(0);
The function _Exit() is used to terminate the process normally and it returns the control to host environment. It does not perform any cleanup task.
The following is the syntax of _Exit()
void _Exit(int status_value);
Here,
status_value − The value which is returned to parent process.
The following is an example of _Exit()
#include <stdio.h>
#include <stdlib.h>
int main() {
   int x = 10;
   printf("The value of x : %d\n", x);
   _Exit(0);
   printf("Calling of _Exit()");
   return 0;
}
In the above program, neither it will display anything nor it will show error.
SAP Scripts - Print Preview of a Document

In SAP Script, it is also possible to preview a document before printing. To perform Print Preview of the document, go to Text → Print Preview.
We have opened a document with the following text −
               Signed                                        
Enclosures  
Prepared      Approved     Confirmed                                
Receipts   Expenditures 
&uline(130)&  

&rfcash-anzsb(Z)& &Rfcash-anzhb(Z)& 

When you go to Text → Print Preview, it will show you the printing format of the document. You can select various Print Preview options.
You can select a particular page for Print Preview or printing. When Print Preview is selected from the option, you can see a preview of the existing document as seen in the following screenshot.

    25 Lectures 
     6 hours 

 Sanjo Thomas

    26 Lectures 
     2 hours 

 Neha Gupta

    30 Lectures 
     2.5 hours 

 Sumit Agarwal

    30 Lectures 
     4 hours 

 Sumit Agarwal

    14 Lectures 
     1.5 hours 

 Neha Malik

    13 Lectures 
     1.5 hours 

 Neha Malik
 Print
 Add Notes
 Bookmark this page
Write a function to delete a Linked List in C++ Programming

Here, we will create a function that will delete all elements of a linked list one by one.
In c/c++, there is no specific function to perform this task but in java, the automatic garbage collection is done to ease deleting linked list.
Now, let’s see the implementation of this program,
 Live Demo
#include <iostream>
using namespace std;
class Node{
   public:
   int data;
   Node* next;
};
void deleteLinkedList(Node** head_ref){
   Node* current = *head_ref;
   Node* next;
   while (current != NULL){
      cout<<current->data<<"\t";
      next = current->next;
      free(current);
      current = next;
   }
   *head_ref = NULL;
}
void push(Node** head_ref, int new_data){
   Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main(){
   Node* head = NULL;
   push(&head, 25);
   push(&head, 10);
   push(&head, 5);
   push(&head, 90);
   push(&head, 68);
   cout<<"Elements of linked list : ";
   deleteLinkedList(&head);
   cout << "\nLinked list deleted";
}
Elements of linked list : 68 90 5 10 25
Linked list deleted
PHP Autoloading Classes

In order to use class defined in another PHP script, we can incorporate it with include or require statements. However, PHP's autoloading feature doesn't need such explicit inclusion. Instead, when a class is used (for declaring its object etc.) PHP parser loads it automatically, if it is registered with spl_autoload_register() function. Any number of classes can thus be registered. This way PHP parser gets a laast chance to load class/interface before emitting error.
spl_autoload_register(function ($class_name) {
   include $class_name . '.php';
});
The class will be loaded from its corresponding .php file when it comes in use for first time
This example shows how a Class is registered for autoloading
<?php
spl_autoload_register(function ($class_name) {
   include $class_name . '.php';
});
$obj = new test1();
$obj2 = new test2();
echo "objects of test1 and test2 class created successfully";
?>
This will produce following result. −
objects of test1 and test2 class created successfully
However, if corresponding .php file having clas definition is not found, following error will be displayed.
Warning: include(): Failed opening 'test10.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 4
PHP Fatal error: Uncaught Error: Class 'test10' not found
 Live Demo
<?php
spl_autoload_register(function($className) {
   $file = $className . '.php';
   if (file_exists($file)) {
      echo "$file included\n";
      include $file;
   } else {
      throw new Exception("Unable to load $className.");
   }
});
try {
   $obj1 = new test1();
   $obj2 = new test10();
} catch (Exception $e) {
   echo $e->getMessage(), "\n";
}
?>
This will produce following result. −
Unable to load test1.
JSTL - fn:escapeXml() Function

The fn:escapeXml() function escapes characters that can be interpreted as XML markup.
The fn:escapeXml() function has the following syntax −
java.lang.String escapeXml(java.lang.String)

Following is the example to explain the functionality of the fn:escapeXml() function −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

<html>
   <head>
      <title>Using JSTL Functions</title>
   </head>

   <body>
      <c:set var = "string1" value = "This is first String."/>
      <c:set var = "string2" value = "This <abc>is second String.</abc>"/>

      <p>With escapeXml() Function:</p>
      <p>string (1) : ${fn:escapeXml(string1)}</p>
      <p>string (2) : ${fn:escapeXml(string2)}</p>

      <p>Without escapeXml() Function:</p>
      <p>string (1) : ${string1}</p>
      <p>string (2) : ${string2}</p>

   </body>
</html>
You will receive the following result −
With escapeXml() Function:
string (1) : This is first String.
string (2) : This <abc>is second String.</abc>
 
Without escapeXml() Function −
string (1) : This is first String.
string (2) : This is second String.


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
CSS Minifier & Compressor

Editable CSS Code
12345678#fileUpload { white-space:nowrap;position:relative;color:#575765;z-index:999}#uploadmenu a{ color:#424242; text-decoration:none; padding:0px;}#uploadmenu div{ width:290px;}#uploadmenu div{ margin:0px 2px 0px 0px; padding:4px 5px 5px 5px; text-align:center; float:none; list-style:none; line-height:24px; border-bottom: 1px dashed #BCBCBC; }#uploadmenu div:last-child{ border-bottom:none;}#uploadmenu div a { font-size:13px; color:#424242; text-decoration:none; }#uploadmenu div a:hover {color:#aaa; text-decoration:none; }X
Privacy Policy
Cookies Policy
Terms of Use
I can print out each element of an array by iterating through all values, but can't get a specific element in MongoDB

To fetch a specific element, iterate with forEach(). Let us create a collection with documents −
> db.demo742.insertOne({ "userDetails": [ { "userName":"Robert", "CountryName":"UK" }, { "userName":"David", "CountryName":"AUS" } ]} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead790b57bb72a10bcf0677")
}
Display all documents from a collection with the help of find() method −
> db.demo742.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5ead790b57bb72a10bcf0677"),
   "userDetails" : [
      {
         "userName" : "Robert",
         "CountryName" : "UK"
      },
      {
         "userName" : "David",
         "CountryName" : "AUS"
      }
   ]
}
Following is the query to get element from an array −
> var ListOfCountryName= {};
> db.demo742.find({}).forEach(function(doc) {
...    doc.userDetails.forEach(function (d){
...       ListOfCountryName[d.CountryName] =d.CountryName;
...    });
... }
... )
> printjson(ListOfCountryName);
This will produce the following output −
{ "UK" : "UK", "AUS" : "AUS" }