code-rag-bench/online-tutorials huggingface dataset:
How to subset a data.table object using a range of values in R?

To subset a data.table object using a range of values, we can use single square brackets and choose the range using %between%. For example, if we have a data.table object DT that contains a column x and the values in x ranges from 1 to 10 then we can subset DT for values between 3 to 8 by using the command DT[DT$x %between% c(3,8)].
Loading data.table package and creating a data.table object −
library(data.table)
x1<-rnorm(20)
x2<-rnorm(20,100,3.25)
dt1<-data.table(x1,x2)
dt1
       x1         x2
1:   0.06546822   102.83348
2:   1.05756760   99.28015
3:   0.09397791   97.36582
4:  -0.44478256   96.22510
5:  -0.17392089   99.56077
6:   0.32834773   95.85831
7:  -0.04563975   104.88298
8:   0.95807930   95.31325
9:   1.25349243   101.72948
10:  0.47676550   96.76459
11: -1.26790256   98.76222
12: -1.36220203   97.91117
13: -1.31999499   102.81730
14:  1.69391374   96.00380
15: -0.10801512   101.69544
16: -1.13463486   108.11833
17: -0.13885823   102.34798
18: -0.54403332   99.68874
19:  0.55865944   97.33505
20:  0.76511431   96.53975
Subsetting rows of dt1 for values 0.5 to 1 of x1 −
dt1[dt1$x1 %between% c(0.5,1)]
      x1         x2
1: 0.9580793  95.31325
2: 0.5586594  97.33505
3: 0.7651143  96.53975
y1<-rpois(20,5)
y2<-rpois(20,2)
dt2<-data.table(y1,y2)
dt2
    y1 y2
1:  7  1
2:  3  2
3:  1  5
4:  4  2
5:  5  3
6:  4  1
7:  3  2
8:  5  0
9:  5  2
10: 7  4
11: 5  4
12: 6  2
13: 6  4
14: 6  2
15: 5  2
16: 1  1
17: 3  1
18: 2  4
19: 4  0
20: 4  1
Subsetting rows of dt1 for values 2 to 6 of y2 −
dt2[dt2$y2 %between% c(2,6)]
    y1 y2
1:  3  2
2:  1  5
3:  4  2
4:  5  3
5:  3  2
6:  5  2
7:  7  4
8:  5  4
9:  6  2
10: 6  4
11: 6  2
12: 5  2
13: 2  4
How to get the widget name in the event in Tkinter?

Tkinter is a Python library that is used to create and develop functional GUI-based applications. Tkinter provides widgets that can be used for constructing the visual and functional representation of the application.
Let us suppose that we have defined some widgets in our application. If we want to get a widget's name in an event, then it can be achieved by using event.widget["text"] keywords inside a function. We can print the name by using it inside the print() function.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the tkinter window
win.geometry("700x300")

# Define a function to delete the shape
def on_click():
   print (win.winfo_children())

# Create a canvas widget
canvas=Canvas(win, width=500, height=300)
canvas.pack()

# Create a button to delete the button
Button(win, text="Click", command=on_click).pack()

win.mainloop()
If we run the above code, it will display a window with a button.
If we click the button, the output will show the name of the widget on the screen.
[<tkinter.Canvas object .!canvas>, <tkinter.Button object .!button>]
How does * operator work on list in Python?

The star(*) operator unpacks the sequence/collection into positional arguments. So if you have a list and want to pass the items of that list as arguments for each position as they are there in the list, instead of indexing each element individually, you could just use the * operator. 
def multiply(a, b):
  return a * b
values = [1, 2]
print(multiply(*values))
This will unpack the list so that it actually executes as −
print(multiply(1, 2))
This will give the output −
2
How to calculate initial cash flows?

The solution is mentioned below −
Fixed capital = $ 2000
Working capital = $ 200
Salvage value = $ 1600
Book value = $ 1200
Tax rate = 28%
Initial cash flows = FC+WC-S + (S-B) * T
                    = 2000 + 200 – 1600 + (1600 – 1200) * 0.28
                    = 2000 + 200 – 1600 + 112
                    = 2312 – 1600
                    = = $712
Here FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate
A toy manufacturer company had following data New equipment cost = 700000Salvagevalue= 475000
Additional expenses = 17500Bookvalue= 390000 Tax rate = 18% Calculate initial cash flow
A toy manufacturer company had following data New equipment cost = 700000Salvagevalue= 475000
Additional expenses = 17500Bookvalue= 390000 Tax rate = 18% Calculate initial cash flow
The solution is explained below −
Initial cash flows = FC+WC-S + (S-B) * T
                    = 700000 + 17500 – 475000 + (475000 – 390000) * 0.18
                    = 700000 + 17500 – 475000 + 15300
                    = 732800 – 4750000
                    = $257800
Here FC = fixed capital, WC = working capital, S = Salvage value, B = Book value, T = Tax rate
Queue.Clone() Method in C#

15 Feb, 2019
This method is used to create a shallow copy of the Queue. It just creates a copy of the Queue. The copy will have a reference to a clone of the internal elements but not a reference to the original elements.
Syntax: public virtual object Clone ();
Return Value: The method returns an Object which is just the shallow copy of the Queue.
Example 1: Let’s see an example without using a Clone() method and directly copying a Queue using assignment operator ‘=’. In the below code, we can see even if we Dequeue() elements from myQueue2, contents of myQueue is also changed. This is because ‘=’ just assigns the reference of myQueue to myQueue2 and does not create any new Queue. But Clone() creates a new Queue.
// C# program to Copy a Queue using // the assignment operatorusing System;using System.Collections;  class GFG {      // Main Method    public static void Main(string[] args)    {          Queue myQueue = new Queue();        myQueue.Enqueue("Geeks");        myQueue.Enqueue("Class");        myQueue.Enqueue("Noida");        myQueue.Enqueue("UP");          // Creating a copy using the         // assignment operator.        Queue myQueue2 = myQueue;           myQueue2.Dequeue();          PrintValues(myQueue);    }      public static void PrintValues(IEnumerable myCollection)    {        // This method prints all the        // elements in the Stack.        foreach(Object obj in myCollection)            Console.WriteLine(obj);    }}
Class
Noida
UP

Example 2: Here myQueue is unchanged.
// C# program to illustrate the use // of Object.Clone() Method using System;using System.Collections;  class GFG {      // Main Method    public static void Main(string[] args)    {          Queue myQueue = new Queue();        myQueue.Enqueue("Geeks");        myQueue.Enqueue("Class");        myQueue.Enqueue("Noida");        myQueue.Enqueue("UP");          // Creating copy using Clone() method.        Queue myQueue2 = (Queue)myQueue.Clone();         myQueue2.Dequeue();          PrintValues(myQueue);    }      public static void PrintValues(IEnumerable myCollection)    {        // This method prints all the        // elements in the Stack.        foreach(Object obj in myCollection)            Console.WriteLine(obj);        Console.WriteLine();    }}
Geeks
Class
Noida
UP

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.queue.clone?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Queue
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Abstract Class and Interface in C#
C# Dictionary with examples
C# | How to check whether a List contains a specified element
C# | Arrays of Strings
C# | IsNullOrEmpty() Method
String.Split() Method in C# with Examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
How to catch OSError Exception in Python?

OSError serves as the error class for the os module, and is raised when an error comes back from an os-specific function.
We can re-write the given code as follows to handle the exception and know its type.
#foobar.py
import os
import sys
try:
for i in range(5):
print i, os.ttyname(i)
except Exception as e:
print e
print sys.exc_type
If we run this script at linux terminal
$ python foobar.py
We get the following output
OUTPUT
0 /dev/pts/0
1 /dev/pts/0
2 /dev/pts/0
3 [Errno 9] Bad file descriptor
<type 'exceptions.OSError'>
Python – PyTorch numel() method

26 May, 2020
PyTorch torch.numel() method returns the total number of elements in the input tensor.
Syntax: torch.numel(input)
Arguments
input: This is input tensor.
Return: It returns the length of the input tensor.
# Importing the PyTorch library import torch     # A constant tensor of size na = torch.randn(4, 6)print(a)  # Applying the numel function and # storing the result in 'out'out = torch.numel(a)print(out)
Output:
-0.8263  0.9807 -1.4688  0.2117 -0.8356 -0.0228
-0.8815  1.3652 -0.1892 -1.1241  0.2755  1.3006
 0.0559  0.2389  0.7944  2.6587 -2.0908  1.2973
-0.2056  0.4110  0.2163  0.3091  0.5559 -0.2468
[torch.FloatTensor of size 4x6]
24

Example 2:
# Importing the PyTorch library import torch     # A constant tensor of size na = torch.FloatTensor([1, 4, 6, 8])print(a)  # Applying the numel function and # storing the result in 'out'out = torch.numel(a)print(out)
Output:
 1
 4
 6
 8
[torch.FloatTensor of size 4]
4

Python-PyTorch
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
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
Python OOPs Concepts
Introduction To PYTHON
How to Append a Character to a String in C

22 Jun, 2021
Given a string str and a character ch, this article tells about how to append this character ch to this string str at the end.Examples:  
Input: str = "Geek", ch = 's'
Output: "Geeks"

Input: str = "skee", ch = 'G'
Output: "skeeG"
Approach:  
Get the string str and character chUse the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.h is the header file required for string functions.Syntax:  
Get the string str and character ch
Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.h is the header file required for string functions.Syntax:  
char *strncat(char *dest, const char *src, size_t n)
Parameters: This method accepts the following parameters:  
dest: the string where we want to append.
src: the string from which ‘n’ characters are going to append.
n: represents the maximum number of character to be appended. size_t is an unsigned integral type.
       3. Print or return the appended string str.
Below is the implementation of the above approach: 
C
// C program to Append a Character to a String #include <stdio.h>#include <string.h> int main(){    // declare and initialize string    char str[6] = "Geek";     // declare and initialize char    char ch = 's';     // print string    printf("Original String: %s\n", str);    printf("Character to be appended: %c\n", ch);     // append ch to str    strncat(str, &ch, 1);     // print string    printf("Appended String: %s\n", str);     return 0;}
Original String: Geek
Character to be appended: s
Appended String: Geeks
 
bohmann2
C-String
C Programs
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Adding Labels to Method and Functions in Java - GeeksforGeeks

29 Oct, 2020
The concept of labels in Java is being taken from assembly language. In Java break and continue are the control statements that control the flow of the program. Labels too can be considered as the control statement, but there is one mandatory condition, that within the loop, the label can only be used with break and continue keyword.
Usage of Labels:
The break statement is helpful for coming out of the inner loop after the occurrence of some conditions, and the label is used to come out of the outer loop using the break statement in the inner loop.
The label is defined with a colon (:) after the name of the label, and before the loop.
Below is the demo syntax of the code using labels and without a label.
Without Using Label 
while (condition)  
{
 if (specific condition )
 { 
       break;
    // when control will reach to this break 
        // statement,the control will come out of while loop.
  } 
 else
     {
        // code that needs to be executed
    // if condition in if block is false.
     }
}


With Labels
// labelName is the name of the label
labelName:

while (condition)  
{
 if (specific condition )
     {  
       break labelName;
    // it will work same as if break is used here.
     }
 else
     {
        // code that needs to be executed 
    // if condition in if block is false.
     } 
}




Below are some programs using the main function which will help to understand how the label statements work, and where they can be used.
Use Of Label In Single For Loop
Java
// Java program to demonstrate // the use of label in for loop  import java.io.*;  class GFG {    public static void main(String[] args)    {    label1:        for (int i = 0; i < 5; i++) {            if (i == 3)                break label1;            System.out.print(i + " ");        }    }}
0 1 2 

Java
// Java program to demonstrate the use // of label in nested for loopimport java.io.*;  class GFG {        public static void main(String[] args)    {    outerLoop:        for (int i = 0; i < 5; i++) {        innerLoop:            for (int j = 0; j < 5; j++) {                if (i != j) {                    System.out.println("If block values "                                       + i);                    break outerLoop;                }                else {                    System.out.println("Else block values "                                       + i);                    continue innerLoop;                }            }        }    }}
Else block values 0
If block values 0
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Implementation of One Time Pad Cipher

Python includes a hacky implementation module for one-time-pad cipher implementation. The package name is called One-Time-Pad which includes a command line encryption tool that uses encryption mechanism similar to the one-time pad cipher algorithm.
You can use the following command to install this module −
pip install onetimepad

If you wish to use it from the command-line, run the following command −
onetimepad

The following code helps to generate a one-time pad cipher −
import onetimepad

cipher = onetimepad.encrypt('One Time Cipher', 'random')
print("Cipher text is ")
print(cipher)
print("Plain text is ")
msg = onetimepad.decrypt(cipher, 'random')

print(msg)
You can observe the following output when you run the code given above −
Note − The encrypted message is very easy to crack if the length of the key is less than the length of message (plain text).
In any case, the key is not necessarily random, which makes one-time pad cipher as a worth tool.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to match tab and newline but not space using Python regular expression?

The following code matches tab and newline but not space from given string using regex.
import re
print re.findall(r"[\n\t]","""I find
    Tutorialspoint useful""")
This gives the output
['\n']
How to convert Stream to TreeSet in Java?

Let us first create a Stream:
Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");
Now convert Stream to TreeSet:
Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
The following is an example to convert String to TreeSet in Java:
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("UK", "US", "India", "Australia", "Armenia", "Canada", "Poland");
      Set<String> set = stream.collect(Collectors.toCollection(TreeSet::new));
      set.forEach(val -> System.out.println(val));
   }
}
Armenia
Australia
Canada
India
Poland
UK
US
Program for Mean Absolute Deviation in C++

Given with an array of natural numbers and the task is to calculate the mean absolute deviation and for that we must require the knowledge of mean, variance and standard deviation.
There are steps that need to be followed for calculating the mean absolute deviation
Calculate the mean
Calculate the mean
Calculate absolute deviation
Calculate absolute deviation
Add all the calculated deviations
Add all the calculated deviations
Apply the formula
Apply the formula
Input 
arr[] = { 34,21,56,76,45,11}
Output 
mean absolute deviation is : 18.5
Input 
arr[] = {10, 15, 15, 17, 18, 21}
Output 
mean absolute mean absolute deviation is : 2.66
Input the elements of an array
Input the elements of an array
Calculate the mean of an array
Calculate the mean of an array
Calculate deviation using formula
Sum = Sum + abs(arr[i] - Mean(arr, n))
Calculate deviation using formula
Sum = Sum + abs(arr[i] - Mean(arr, n))
calculate mean absolute deviation by dividing the total deviation with total
number of elements in an array
calculate mean absolute deviation by dividing the total deviation with total
number of elements in an array
(abs(arr[0] – mean) + abs(arr[1] – mean) + . . + abs(arr[n-1] – mean) / n
Start
Step 1→ declare function to calculate mean
   float mean(float arr[], int size)
      declare float sum = 0
      Loop For int i = 0 and i < size and i++
         Set sum = sum + arr[i]
      End
      return sum / size
Step 2→ Declare function to calculate deviation
   float deviation(float arr[], int size)
   declare float sum = 0
   Loop For int i = 0 and i < size and i++
      Set sum = sum + abs(arr[i] - mean(arr, size))
   End
   return sum / size
Step 3→ In main()
   Declare float arr[] = { 34,21,56,76,45,11}
   Declare int size = sizeof(arr) / sizeof(arr[0])
   Call deviation(arr, size)
Stop
 Live Demo
#include <bits/stdc++.h>
using namespace std;
//calculate mean using mean function
float mean(float arr[], int size){
   float sum = 0;
   for (int i = 0; i < size; i++)
      sum = sum + arr[i];
   return sum / size;
}
//calculate mean deviation
float deviation(float arr[], int size){
   float sum = 0;
   for (int i = 0; i < size; i++)
      sum = sum + abs(arr[i] - mean(arr, size));
   return sum / size;
}
int main(){
   float arr[] = { 34,21,56,76,45,11};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"mean absolute deviation is : "<<deviation(arr, size);
   return 0;
}
If run the above code it will generate the following output −
mean absolute deviation is : 18.5
Python 3 - Number floor() Method

The floor() method returns the floor of x i.e. the largest integer not greater than x.
Following is the syntax for floor() method −
import math

math.floor( x )

Note − This function is not accessible directly, so we need to import the math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns the largest integer not greater than x.
The following example shows the usage of the floor() method.
#!/usr/bin/python3
import math   # This will import math module

print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
print ("math.floor(100.72) : ", math.floor(100.72))
print ("math.floor(math.pi) : ", math.floor(math.pi))
When we run the above program, it produces the following result −
math.floor(-45.17) :  -46
math.floor(100.12) :  100
math.floor(100.72) :  100
math.floor(math.pi) :  3


    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
Matplotlib.axes.Axes.set_ylim() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_ylim() function in axes module of matplotlib library is used to set the y-axis view limits.
Syntax: Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None)
Parameters: This method accepts the following parameters.
bottom : This parameter is the bottom ylim in data coordinates
top : This parameter is the top ylim in data coordinates
emit : This parameter is used to notify observers of limit change.
auto : This parameter is used to turn on autoscaling of the x-axis.
ymin, ymax: These parameter are equivalent to bottom and top and it is an error to pass both ymin and bottom or ymax and top.
Returns:This method returns the following
bottom, top:This returns the new y-axis limits in data coordinates.
Below examples illustrate the matplotlib.axes.Axes.set_ylim() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionfrom matplotlib.widgets import Cursorimport numpy as npimport matplotlib.pyplot as plt    np.random.seed(19680801)  fig, ax = plt.subplots(facecolor ='# A0F0CC')  x, y = 4*(np.random.rand(2, 100) - .5)ax.plot(x, y, 'g')ax.set_ylim(-3, 3)  cursor = Cursor(ax, useblit = True, color ='red',                linewidth = 2)      ax.set_title('matplotlib.axes.Axes.set_ylim() Example\n',             fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  fig1, ax1 = plt.subplots()fig2, ax2 = plt.subplots()ax1.set(xlim =(-0.5, 1.5), ylim =(-0.5, 1.5),               autoscale_on = False)ax2.set(xlim =(0.5, 0.75), ylim =(0.5, 0.75),               autoscale_on = False)  x, y, s, c = np.random.rand(4, 200)s *= 200  ax1.scatter(x, y, s, c)ax2.scatter(x, y, s, c)    def GFG(event):    if event.button != 1:        return    x, y = event.xdata, event.ydata    ax2.set_xlim(x - 0.1, x + 0.1)    ax2.set_ylim(y - 0.1, y + 0.1)    fig2.canvas.draw()  fig1.canvas.mpl_connect('button_press_event', GFG)   ax1.set_title('matplotlib.axes.Axes.set_ylim()\ Example\n Original Window ',             fontsize = 14, fontweight ='bold')ax2.set_title('Zoomed window ',             fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Angular 10 getCurrencySymbol() Method - GeeksforGeeks

24 May, 2021
In this article, we are going to see what is getCurrencySymbol in Angular 10 and how to use it. getCurrencySymbol is used to retrieve the currency symbol for a given currency code
Syntax:
getCurrencySymbol(code, locale, format)
Parameters:
code: The currency code
locale: A locale code for the locale format rule to use.
format: The format.
Return Value:
string: the formatted date string.
NgModule: Module used by getCurrencySymbol 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 getCurrencySymbol.
import { LOCALE_ID, NgModule } from '@angular/core';
In app.component.ts import getCurrencySymbol 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 {  getCurrencySymbol }  from '@angular/common';  import {Component}  from '@angular/core';  @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = getCurrencySymbol("USD", "wide");}
app.component.html
<h1>  GeeksforGeeks</h1>  <p>{{curr }} 100</p>
Output:
Example 2:
app.component.ts
import {  getCurrencySymbol }  from '@angular/common';  import {Component}  from '@angular/core';  @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = getCurrencySymbol("INR", "narrow");}
app.component.html
<h1>  GeeksforGeeks</h1>  <p>{{curr }} 304</p>
Output:
Reference: https://angular.io/api/common/getCurrencySymbol
Angular10
AngularJS-Function
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to check similarity between two strings in MySQL?

Similarity between two strings can be checked with the help of ‘strcmp()’ function. Here are the conditions.
If both strings are equal, then it returns 0.
If both strings are equal, then it returns 0.
If first string is less than the second string, it returns -1.
If first string is less than the second string, it returns -1.
If first string is greater than the second string, it returns 1.
If first string is greater than the second string, it returns 1.
Here is an example.
Case 1 − If both strings are equal.
The following is the query.
mysql > SELECT STRCMP("demo", "demo");
The following is the output of the above query.
+------------------------+
| STRCMP("demo", "demo") |
+------------------------+
| 0                      |
+------------------------+
1 row in set (0.00 sec)
Case 2 − If first string is less than the second string.
The following is the query.
mysql> SELECT STRCMP("demo", "demo1234");
The following is the output of the above query.
+----------------------------+
| STRCMP("demo", "demo1234") |
+----------------------------+
| -1                         |
+----------------------------+
1 row in set (0.00 sec)
Case 3 − If first string is greater than the second string.
The following is the query.
mysql> SELECT STRCMP("demo1", "demo");
The following is the output.
+-------------------------+
| STRCMP("demo1", "demo") |
+-------------------------+
| 1                       |
+-------------------------+
1 row in set (0.00 sec)
jQuery Effect - toggle( switch ) Method

The toggle( switch ) method toggle displaying each of the set of matched elements based upon the passed parameter. If true parameter shows all elements, false hides all elements.
Here is the simple syntax to use this method −
selector.toggle( switch );

Here is the description of all the parameters used by this method −
switch − A switch to toggle the display on.
switch − A switch to toggle the display on.
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://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {

            $("#false").click(function(){
               $(".target").toggle(false);
            });

            $("#true").click(function(){
               $(".target").toggle(true);
            });
				
         });
      </script>
		
      <style>
         p {background-color:#bca; width:250px; border:1px solid green;}
      </style>
   </head>
	
   <body>
      <p>Click on any of the following buttons:</p>
		
      <button id = "false"> False Switch </button>
      <button id = "true"> True Switch </button>

      <div class = "target">
         <img src = "../images/jquery.jpg" alt = "jQuery" />
      </div>
   </body>
</html>
This will produce following result −
Click on any of the following buttons −

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
Java Program to convert array to String for one dimensional and multi-dimensional arrays

For converting array to 1D and 2D arrays, let us first create a one-dimensional and two-dimensional array −
String str[] = {"p", "q", "r", "s", "t", "u", "v", "w","x", "y", "z"};
doubled [][]= {
   {1.2, 1.3, 2.1, 4.1},
   {1.5, 2.3},
   {2.5, 4.4},
   {3.8},
   {4.9},
   {3.2, 2.1, 3.2, 7.2}
};
Converting array to string for one-dimensional array −
Arrays.toString(str);
Converting array to string for two-dimensional array −
Arrays.deepToString(d);
import java.util.Arrays;
public class Demo {
   public static void main(String args[]) {
      String str[] = {"p", "q", "r", "s", "t", "u", "v", "w","x", "y", "z"};
      doubled [][]= {
         {1.2, 1.3, 2.1, 4.1},
         {1.5, 2.3},
         {2.5, 4.4},
         {3.8},
         {4.9},
         {3.2, 2.1, 3.2, 7.2}
      };
      System.out.println("One dimensional = "+Arrays.toString(str));
      System.out.println("Two dimensional = "+Arrays.deepToString(d));
   }
}
One dimensional = [p, q, r, s, t, u, v, w, x, y, z]
Two dimensional = [[1.2, 1.3, 2.1, 4.1], [1.5, 2.3], [2.5, 4.4], [3.8], [4.9], [3.2, 2.1, 3.2, 7.2]]
std::to_string in C++ - GeeksforGeeks

26 Jul, 2017
Convert numerical value to string
Syntax :
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Parameters :
val - Numerical value.

Return Value :
A string object containing the representation of val as a sequence of characters.

// CPP program to illustrate// std::to_string#include <bits/stdc++.h>  // Driver codeint main(){      // Converting float to string    std::string str1 = std::to_string(12.10);      // Converting integer to string    std::string str2 = std::to_string(9999);      // Printing the strings    std::cout << str1 << '\n';    std::cout << str2 << '\n';    return 0;}
Output:
12.100000
9999

Problem : Find a specific digit in a given integer.Example :
Input : number  = 10340, digit = 3
Output : 3 is at position 3

// CPP code to find a digit in a number// using std::tostring#include <bits/stdc++.h>  // Driver codeint main(){      // Converting number to string    std::string str = std::to_string(9954);      // Finding 5 in the number    std::cout << "5 is at position " << str.find('5') + 1;}
Output :
5 is at position 3

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cpp-strings-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
Socket Programming in C/C++
C++ Classes and Objects
Operator Overloading in C++
Bitwise Operators in C/C++
Virtual Function in C++
Iterators in C++ STL
Constructors in C++
Copy Constructor in C++
AngularJS - Ajax

AngularJS provides $http control which works as a service to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner −
function studentController($scope,$https:) {
   var url = "data.txt";

   $https:.get(url).success( function(response) {
      $scope.students = response; 
   });
}

Here, the file data.txt contains student records. $http service makes an ajax call and sets response to its property students. students model can be used to draw tables in HTML.
[
   {
      "Name" : "Mahesh Parashar",
      "RollNo" : 101,
      "Percentage" : "80%"
   },
   {
      "Name" : "Dinkar Kad",
      "RollNo" : 201,
      "Percentage" : "70%"
   },
   {
      "Name" : "Robert",
      "RollNo" : 191,
      "Percentage" : "75%"
   },
   {
      "Name" : "Julian Joe",
      "RollNo" : 111,
      "Percentage" : "77%"
   }
]

<html>
   <head>
      <title>Angular JS Includes</title>
      
      <style>
         table, th , td {
            border: 1px solid grey;
            border-collapse: collapse;
            padding: 5px;
         }
         table tr:nth-child(odd) {
            background-color: #f2f2f2;
         }
         table tr:nth-child(even) {
            background-color: #ffffff;
         }
      </style>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "" ng-controller = "studentController">
      
         <table>
            <tr>
               <th>Name</th>
               <th>Roll No</th>
               <th>Percentage</th>
            </tr>
         
            <tr ng-repeat = "student in students">
               <td>{{ student.Name }}</td>
               <td>{{ student.RollNo }}</td>
               <td>{{ student.Percentage }}</td>
            </tr>
         </table>
      </div>
      
      <script>
         function studentController($scope,$http) {
            var url = "/data.txt";

            $http.get(url).then( function(response) {
               $scope.students = response.data;
            });
         }
      </script>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
      </script>
      
   </body>
</html>
To execute this example, you need to deploy testAngularJS.htm and data.txt file to a web server. Open the file testAngularJS.htm using the URL of your server in a web browser and see the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    40 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Count no. of characters and words in a string in PL/SQL

We are given a string of any length and the task is to calculate the count of characters and words in a string using PL/SQL.
PL/SQL is a combination of SQL along with the procedural features of programming
languages.It was developed by Oracle Corporation in the early 90's to enhance the
capabilities of SQL. PL/SQL is one of three key programming languages embedded in the
Oracle Database, along with SQL itself and Java.
In PL/SQL block, we have DECLARE block which is used to declare the variables used in
programming and we have BEGIN block where we write the logic for the given problem,
Input − string str = “Tutorials Point”
Output− count of characters is: 15
      Count of words are: 2
Explanation-: In the given string we have a total 2 words so word count is 2 and in those words we have 14 characters plus one is for one space in a given string.
Input − string str = “Honesty is the best policy”
Output − count of characters is: 26
      Count of words are: 5
Explanation − In the given string we have a total 5 words so word count is 5 and in those words we have 24 characters plus four is for four spaces in a given string.
Input the string of any length and store it in a variable let’s say, str
Input the string of any length and store it in a variable let’s say, str
Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.
Calculate the length of the string using the length() function that will return an integer value as per the number of letters in the string including the spaces.
Traverse the loop starting from i to 0 and till length of a string str
Traverse the loop starting from i to 0 and till length of a string str
Use function substr() that will return the number of substrings in a string that is the number of words in a string
Use function substr() that will return the number of substrings in a string that is the number of words in a string
And, increase the count of characters with every iteration of a loop which is going till the length of a string.
And, increase the count of characters with every iteration of a loop which is going till the length of a string.
Print the count of characters and words in a string.
Print the count of characters and words in a string.
DECLARE
      str VARCHAR2(40) := 'Tutorials Point';
      nchars NUMBER(4) := 0;
      nwords NUMBER(4) := 1;
      s CHAR;
BEGIN
   FOR i IN 1..Length(str) LOOP
      s := Substr(str, i, 1);
      nchars:= nchars+ 1;
      IF s = ' ' THEN
      nwords := nwords + 1;
      END IF;
END LOOP;
dbms_output.Put_line('count of characters is:'
   ||nchars);

dbms_output.Put_line('Count of words are: '
   ||nwords);
END;
If we run the above code it will generate the following output −
count of characters is: 15
Count of words are: 2
Call a Function with a Button or a Key in Tkinter

Let assume that we want to call a function whenever a button or a key is pressed for a particular application. We can bind the function that contains the operation with a button or key using the bind('<button or Key>,' callback_function) method. Here, you can bind any key to the event or function that needs to be called.
In this example, we have created a function that will open a dialog box whenever we click a button.
#Import the required libraries
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("700x350")

#Define a function for opening the Dialog box
def open_prompt():
   messagebox.showinfo("Message", "Click Okay to Proceed")

#Create a Label widget
Label(win, text= "Click to Open the MessageBox").pack(pady=15)

#Create a Button for opening a dialog Box
ttk.Button(win, text= "Open", command= open_prompt).pack()

win.mainloop()
Running the above code will display a window containing a label and a button.
Upon clicking the "Open" button", it will call a function to open a dialog box.
How to deal with warning message “Removed X rows containing missing values” for a column of an R data frame while creating a plot?

If we have missing values/NA in our data frame and create a plot using ggplot2 without excluding those missing values then we get the warning “Removed X rows containing missing values”, here X will be the number of rows for the column that contain NA values. But the plot will be correct because it will be calculated by excluding the NA’s. To avoid this error, we just need to pass the subset of the data frame column that do not contains NA values as shown in the below example.
Consider the below data frame with y column having few NA values −
 Live Demo
set.seed(112)
x<-sample(0:10,25,replace=TRUE)
y<-sample(c(21:25,NA),25,replace=TRUE) df<-data.frame(x,y)
df
   x  y
1  4  21
2  10  NA
3  10  23
4  10 22
5  2  NA
6  1 NA
7  0 25
8  8 NA
9  1 22
10 4 23
11 2 21
12 3 23
13 9 25
14 6 25
15 7 21
16 10 24
17 6 NA
18 6 NA
19 8 NA
20 4 24
21 1 23
22 7 21
23 1 21
24 0 22
25 4 NA
Loading ggplot2 package and creating point chart for x and y columns of df −
library(ggplot2) ggplot(df,aes(x,y))+geom_point()
Warning message −
Removed 5 rows containing missing values (geom_point) −
Here, we are getting the warning message for missing values.
Creating the point chart for x and y by excluding the NA values −
ggplot(data=subset(df,!is.na(y)),aes(x,y))+geom_point()
Output of the plot would be same as shown above but the warning message will not be there −
Impala - Order By Clause

The Impala ORDER BY clause is used to sort the data in an ascending or descending order, based on one or more columns. Some databases sort the query results in ascending order by default.
Following is the syntax of the ORDER BY clause.
select * from table_name ORDER BY col_name [ASC|DESC] [NULLS FIRST|NULLS LAST]

You can arrange the data in the table in ascending or descending order using the keywords ASC or DESC respectively.
In the same way, if we use NULLS FIRST, all the null values in the table are arranged in the top rows; and if we use NULLS LAST, the rows containing null values will be arranged last.
Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 1  | Ramesh   |  32 | Ahmedabad | 20000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
+----+----------+-----+-----------+--------+ 
Fetched 6 row(s) in 0.51s

Following is an example of arranging the data in the customers table, in ascending order of their id’s using the order by clause.
[quickstart.cloudera:21000] > Select * from customers ORDER BY id asc;

On executing, the above query produces the following output.
Query: select * from customers ORDER BY id asc 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
+----+----------+-----+-----------+--------+ 
Fetched 6 row(s) in 0.56s

In the same way, you can arrange the data of customers table in descending order using the order by clause as shown below.
[quickstart.cloudera:21000] > Select * from customers ORDER BY id desc;

On executing, the above query produces the following output.
Query: select * from customers ORDER BY id desc 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 6  | Komal    | 22  | MP        | 32000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  |
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
+----+----------+-----+-----------+--------+ 
Fetched 6 row(s) in 0.54s

 Print
 Add Notes
 Bookmark this page
Class getDeclaredFields() method in Java with Examples - GeeksforGeeks

25 Jan, 2022
The getDeclaredFields() method of java.lang.Class class is used to get the fields of this class, which are the fields that are private, public, protected or default and its members, but not the inherited ones. The method returns the fields of this class in the form of array of Field objects. Syntax: 
public Field[] getDeclaredFields()
               throws SecurityException
Parameter: This method does not accept any parameter.Return Value: This method returns the fields of this class in the form of 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 getDeclaredFields() method.Example 1:
Java
// Java program to demonstrate getDeclaredFields() method import java.util.*; public class Test {    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 getDeclaredFields() method        System.out.println(            "DeclaredFields of myClass: "            + Arrays.toString(                  myClass.getDeclaredFields()));    }}
Class represented by myClass: class Test
DeclaredFields of myClass: []
 
Example 2:
Java
// Java program to demonstrate getDeclaredFields() method import java.util.*; class Main {     public Object obj;     Main()    {         class Arr {        };         obj = new Arr();    }     public static void main(String[] args)        throws ClassNotFoundException    {        // returns the Class object for this class        Class myClass = Class.forName("Main");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the fields of myClass        // using getDeclaredFields() method        System.out.println(            "DeclaredFields of myClass: "            + Arrays.toString(                  myClass.getDeclaredFields()));    }}
Class represented by myClass: class Main
DeclaredFields of myClass: [public java.lang.Object Main.obj]
 
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getDeclaredFields–
saurabh1990aror
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.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java