code-rag-bench/online-tutorials huggingface dataset:
DateTime.Compare() Method in C#

22 Jan, 2019
This method is used to compare two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.
Syntax:
public static int Compare (DateTime t1, DateTime t2);
Parameters:
t1: The first object to compare.
t2: The second object to compare.
Return Value: This method returns a signed number indicating the relative values of t1 and t2.
Less than zero : If t1 is earlier than t2.Zero : If t1 is the same as t2.Greater than zero : If t1 is later than t2.
Below programs illustrate the use of DateTime.Compare(DateTime, DateTime) Method:
Example 1:
// C# program to demonstrate the// DateTime.Compare(DateTime,// DateTime) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        // creating object of DateTime        DateTime date1 = new DateTime(2010, 1,                                  1, 4, 0, 15);          // creating object of DateTime        DateTime date2 = new DateTime(2010, 1,                                 1, 4, 0, 14);          // comparing date1 and date2        // using Compare() method;        int value = DateTime.Compare(date1, date2);          // checking        if (value > 0)            Console.Write("date1 is later than date2. ");        else if (value < 0)            Console.Write("date1 is earlier than date2. ");        else            Console.Write("date1 is the same as date2. ");    }}
date1 is later than date2.

Example 2:
// C# program to demonstrate the// DateTime.Compare(DateTime, // DateTime) Methodusing System;  class GFG {      // Main Method    public static void Main()    {          // calling check() method        check(new DateTime(2010, 1, 3, 4, 0, 15),              new DateTime(2010, 1, 4, 4, 0, 15));          check(new DateTime(2010, 1, 5, 4, 0, 15),              new DateTime(2010, 1, 4, 4, 0, 15));          check(new DateTime(2010, 1, 5, 4, 0, 15),              new DateTime(2010, 1, 5, 4, 0, 15));    }      public static void check(DateTime date1,                            DateTime date2)    {          // comparing date1 and date2        // using Compare() method;        int value = DateTime.Compare(date1, date2);          // checking        if (value > 0)            Console.WriteLine(" {0:d} is later than {1:d}. ",                                               date1, date2);        else if (value < 0)            Console.WriteLine(" {0:d} is earlier than {1:d}. ",                                                 date1, date2);        else            Console.WriteLine(" {0:d} is the same as {1:d}. ",                                                date1, date2);    }}
01/03/2010 is earlier than 01/04/2010. 
01/05/2010 is later than 01/04/2010. 
01/05/2010 is the same as 01/05/2010.

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.compare?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.begin_fill() function in Python

29 Jun, 2021
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to call just before drawing a shape to be filled. It doesn’t take any argument.
Syntax :
turtle.begin_fill()
Below is the implementation of the above method with an example :
Example:
Python3
# importing packageimport turtle # set turtle position# and colorturtle.up()turtle.goto(0,-30)turtle.down()turtle.color("yellow") # start fill blockturtle.begin_fill() # all instruction within this# block are filled with turtle# color as set aboveturtle.circle(60) # end fill blockturtle.end_fill() # hide the turtleturtle.hideturtle()
 
 
Output :
 
 
varshagumber28
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Plotly - Online and Offline Plotting

The following chapter deals with the settings for the online and offline plotting. Let us first study the settings for online plotting.
Data and graph of online plot are save in your plot.ly account. Online plots are generated by two methods both of which create a unique url for the plot and save it in your Plotly account.
py.plot()  − returns the unique url and optionally open the url.
py.plot()  − returns the unique url and optionally open the url.
py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook.
py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook.
We shall now display simple plot of angle in radians vs. its sine value. First, obtain ndarray object of angles between 0 and 2π using arange() function from numpy library. This ndarray object serves as values on x axis of the graph. Corresponding sine values of angles in x which has to be displayed on y axis are obtained by following statements −
import numpy as np
import math #needed for definition of pi
xpoints = np.arange(0, math.pi*2, 0.05)
ypoints = np.sin(xpoints)
Next, create a scatter trace using Scatter() function in graph_objs module.
trace0 = go.Scatter(
   x = xpoints,
   y = ypoints
)
data = [trace0]
Use above list object as argument to plot() function.
py.plot(data, filename = 'Sine wave', auto_open=True)

Save following script as plotly1.py
import plotly
plotly.tools.set_credentials_file(username='lathkar', api_key='********************')
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
import math #needed for definition of pi

xpoints = np.arange(0, math.pi*2, 0.05)
ypoints = np.sin(xpoints)
trace0 = go.Scatter(
   x = xpoints, y = ypoints
)
data = [trace0]
py.plot(data, filename = 'Sine wave', auto_open=True)
Execute the above mentioned script from command line. Resultant plot will be displayed in the browser at specified URL as stated below.
$ python plotly1.py
High five! You successfully sent some data to your account on plotly. 
View your plot in your browser at https://plot.ly/~lathkar/0

Just above the displayed graph, you will find tabs Plot, Data, Python & Rand Forking history.
Currently, Plot tab is selected. The Data tab shows a grid containing x and y data points. From Python & R tab, you can view code corresponding to current plot in Python, R, JSON, Matlab etc. Following snapshot shows Python code for the plot as generated above −
Plotly allows you to generate graphs offline and save them in local machine. The plotly.offline.plot() function creates a standalone HTML that is saved locally and opened inside your web browser.
Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display the plot in the notebook.
Note − Plotly's version 1.9.4+ is needed for offline plotting.
Change plot() function statement in the script and run. A HTML file named temp-plot.html will be created locally and opened in web browser.
plotly.offline.plot(
   { "data": data,"layout": go.Layout(title = "hello world")}, auto_open = True)
How to count number of data types in an array in JavaScript ?

09 Jul, 2021
Given an array and the task is to count the number of data types used to create that array.
Example:
Input: [1, true, “hello”, [], {}, undefined, function(){}] Output: { boolean: 1, function: 1, number: 1, object: 2, string: 1, undefined: 1 }Input: [function(){}, new Object(), [], {}, NaN, Infinity, undefined, null, 0] Output: { function: 1, number: 3, object: 4, undefined: 1 }
strong>Approach 1: In this approach We use the Array.reduce() method and initialize the method with an empty object. 
Javascript
<script>// JavaScript program to count number of data types in an arraylet countDtypes = (arr) => {    return arr.reduce((acc, curr) => {             // Check if the acc contains the type or not            if (acc[typeof curr]) {                 // Increase the type with one                acc[typeof curr]++;            } else {                 /* If acc not contains the type                then initialize the type with one */                acc[typeof curr] = 1            }            return acc        }, {}) // Initialize with an empty array}   let arr = [function() {}, new Object(), [], {}, NaN, Infinity, undefined, null, 0];  console.log(countDtypes(arr));</script>
  
Output:
 
{
   function: 1,
   number: 3,
   object: 4,
   undefined: 1
}
 
Approach 2: In this approach, we use the Array.forEach() method to iterate the array. And create an empty array and at every iteration, we check if the type of present iteration present in the newly created object or not. If yes then just increase the type with 1 otherwise create a new key by the name of the type and initialize with 1.
 
Javascript
<script>// JavaScript program to count number of data types in an arraylet countDtypes = (arr) => {    let obj = {}     arr.forEach((val) => {         // Check if obj contains the type or not        if (obj[typeof val]) {             // Increase the type with one            obj[typeof val]++;        } else {             // Initialize a key (type) into obj            obj[typeof val] = 1;        }    })    return obj}   let arr = [function() {}, new Object(), [], {},    NaN, Infinity, undefined, null, 0]; console.log(countDtypes(arr));</script>
Output:
{
  boolean: 1,
  function: 1,
  number: 1,
  object: 2,
  string: 1,
  undefined: 1
}
gulshankumarar231
javascript-array
JavaScript-Methods
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | os.path.getatime() method

22 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.getatime() method in Python is used to get the time of last access of the specified path. This method returns a floating point value which represents the number of seconds since the epoch. This method raise OSError if the file does not exist or is somehow inaccessible.
Note: The epoch represents the point where the time starts. It is platform dependent. For Unix, the epoch is January 1, 1970, 00:00:00 (UTC).
Syntax: os.path.getatime(path)
Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a floating-point value of class ‘float’ that represents the time (in seconds) of last access of the specified path.
Code #1: Use of os.path.getatime() method
# Python program to explain os.path.getatime() method     # importing os and time module import osimport time  # Pathpath = '/home/User/Documents/file.txt'  # Get the time of last# access of the specified# path since the epochaccess_time = os.path.getatime(path)print("Last access time since the epoch:", access_time)  # convert the time in# seconds since epoch# to local timelocal_time = time.ctime(access_time)print("Last access time(Local time):", local_time)
Last access time since the epoch: 1558447897.0442736
Last access time (Local time): Tue May 21 19:41:37 2019

Code #2: Handling error while using os.path.getatime() method
# Python program to explain os.path.getatime() method     # importing os, time and sys module import osimport sysimport time  # Pathpath = '/home/User/Documents/file2.txt'  # Get the time of last# access of the specified# path since the epochtry:    access_time = os.path.getatime(path)    print("Last access time since the epoch:", access_time)  except OSError:    print("Path '%s' does not exists or is inaccessible" %path)    sys.exit()  # convert the time in# seconds since epoch# to local timelocal_time = time.ctime(access_time)print("Last access time(Local time):", local_time)    # above code will print# 'File does not exists or is inaccessible'# if the specified path does not# exists or is inaccessible  
Path '/home/User/Documents/file2.txt' does not exists or is inaccessible

Reference: https://docs.python.org/3/library/os.path.html
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Merging sorted arrays together JavaScript

Suppose we have two sorted arrays (increasing order) like this −
const arr1 = [1, 2, 3, 0, 0, 0];
const arr2 = [2, 5, 6];
We are required to write a JavaScript function that takes in two such arrays and returns a new array that contains all the elements from these arrays in a sorted manner.
Therefore, for the above arrays, the output should look like −
const output = [1, 2, 2, 3, 5, 6];
const arr1 = [1, 2, 3, 0, 0, 0];
const arr2 = [2, 5, 6];
const mergeSortedArrays = (arr1, arr2) => {
   let { length: l1 } = arr1;
   let { length: l2 } = arr2;
   while(l2){
      arr1[l1++] = arr2[--l2];
   };
   const sorter = (a, b) => a - b;
   arr1.sort(sorter);
};
mergeSortedArrays(arr1, arr2);
console.log(arr1);
And the output in the console will be −
[
   0, 0, 0, 1, 2,
   2, 3, 5, 6
]
How to find the standard error of mean in R?

The standard error of mean is the standard deviation divided by the square root of the sample size. The easiest way to find the standard error of mean is using the formula to find its value.
> set.seed(1)
We will find the standard errors for a normal random variable, sequence of numbers from one to hundred, a random sample, a binomial random variable, and uniform random variable using the same formula. And at the end, I will confirm whether we used the correct method or not for all types of variables we have considered here.
> x<-rnorm(10)
> x
[1] -0.6264538 0.1836433 -0.8356286  1.5952808 0.3295078 -0.8204684
[7]  0.4874291 0.7383247  0.5757814 -0.3053884
> SE_x<-sd(x)/sqrt(10)
> SE_x
[1] 0.246843
> y<-1:100
> y
[1]   1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18
[19] 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
[37] 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
[55] 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[73] 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
[91] 91 92 93 94 95 96 97 98 99 100
> SE_y<-sd(y)/sqrt(100)
> SE_y
[1] 2.901149
> z<-sample(1:100,20,replace=TRUE)
> z
[1] 73 79 85 37 89 37 34 89 44 79 33 84 35 70 74 42 38 20 28 20
> SE_z<-sd(z)/sqrt(20)
> SE_z
[1] 5.582161
> a<-rbinom(20,100,0.6)
> a
[1] 63 66 59 58 48 66 59 65 60 56 55 55 56 57 56 66 53 62 61 51
> SE_a<-sd(a)/sqrt(20)
> SE_a
[1] 1.141098
> b<-runif(30,2,5)
> b
[1]  4.928512 4.195378 3.070181 3.294421 2.444635 2.039233 4.146698 2.309553
[9]  3.338853 3.920303 4.975516 3.486781 3.453049 2.520327 4.264463 3.361686
[17] 3.533509 2.622635 2.685974 3.787136 3.724617 2.231193 2.106622 3.928386
[25] 4.785846 3.794277 3.682702 3.578083 4.955286 3.522925
> SE_b<-sd(b)/sqrt(30)
> SE_b
[1] 0.1552736
> c<-sample(20)
> c
[1] 19 4 2 16 1 12 7 9 15 10 11 18 13 3 17 8 14 20 6 5
> SE_c<-sd(c)/sqrt(20)
> SE_c
[1] 1.322876
If we don’t know the sample size then we can use length function as follows −
> SE_c<-sd(c)/sqrt(length(c))
> SE_c
[1] 1.322876
Here, the standard error for uniform random variable and binomial random variable are not correct because their standard deviations are not calculated by sd function.
Length of Last Word in C++

Suppose we have a string s. s can hold any English letters and white-spaces. We have to find the length of last word in the string. If there is no last word, then return 0.
So, if the input is like "I love Programming", then the output will be 11
To solve this, we will follow these steps −
n := 0
n := 0
for each word temp in a string −n := size of temp
for each word temp in a string −
n := size of temp
n := size of temp
return n
return n
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int lengthOfLastWord(string s){
      stringstream str(s);
      string temp;
      int n = 0;
      while (str >> temp)
         n = temp.size();
      return n;
   }
};
main(){
   Solution ob;
   cout << (ob.lengthOfLastWord("I love Programming"));
}
"I love Programming"
11
Python - Remove duplicate values across Dictionary Values - GeeksforGeeks

10 May, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the duplicate values across all the dictionary value lists. This problem can have application in data domains and web development domains. Let’s discuss certain ways in which this task can be performed.
Input : test_dict = {‘Manjeet’: [1], ‘Akash’: [1, 8, 9]}Output : {‘Manjeet’: [], ‘Akash’: [8, 9]}
Input : test_dict = {‘Manjeet’: [1, 1, 1], ‘Akash’: [1, 1, 1]}Output : {‘Manjeet’: [], ‘Akash’: []}
Method #1 : Using Counter() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we use Counter() to extract all frequencies and list comprehension to assign the value with single occurrence in value list.
# Python3 code to demonstrate working of # Remove duplicate values across Dictionary Values# Using Counter() + list comprehensionfrom collections import Counter  # initializing dictionarytest_dict = {'Manjeet' : [1, 4, 5, 6],            'Akash' : [1, 8, 9],            'Nikhil': [10, 22, 4],            'Akshat': [5, 11, 22]}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # Remove duplicate values across Dictionary Values# Using Counter() + list comprehensioncnt = Counter()for idx in test_dict.values():    cnt.update(idx)res = {idx: [key for key in j if cnt[key] == 1]                for idx, j in test_dict.items()}  # printing result print("Uncommon elements records : " + str(res)) 
The original dictionary : {‘Akshat’: [5, 11, 22], ‘Nikhil’: [10, 22, 4], ‘Manjeet’: [1, 4, 5, 6], ‘Akash’: [1, 8, 9]}Uncommon elements records : {‘Akshat’: [11], ‘Nikhil’: [10], ‘Manjeet’: [6], ‘Akash’: [8, 9]}
Python dictionary-programs
Python
Python Programs
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Implementing Threading without inheriting the Thread Class in Python - GeeksforGeeks

05 Sep, 2020
We are going implement threading in Python using a Class without sub-classing the superclass called Thread.
To make the best use of the underlying processor and to improve the performance of our application, we can create multiple threads that can execute in parallel. Making the best use of the processor and also our application will give the best user experience, it will be fast.
There are three ways to create threads in Python:
Using a functionExtending thread classWithout extending thread class
Using a function
Extending thread class
Without extending thread class
We will implement the last approach is also called the hybrid approach. We will define a Class but the Class will not extend the parent class thread instead we are going to directly define any function inside that we want. Instead, we will create an instance of the thread and then pass the object and the function which we want to execute within that object as the target and the argument is the second argument. Then invoke the Thread start method.
Example 1:Implementing Thread by printing the first 10 natural numbers 
Python3
# importing thread modulefrom threading import *  # class does not extend thread classclass MyThread:    def display(self):        i = 0        print(current_thread().getName())        while(i <= 10):            print(i)            i = i + 1  # creating object of out classobj = MyThread()  # creating thread objectt = Thread(target = obj.display)  # invoking threadt.start()
Output:
Thread-1
0
1
2
3
4
5
6
7
8
9
10

Example 2:Implementing Thread by printing even numbers within a given range
Python3
# importing thread modulefrom threading import *  # class does not extend thread classclass MyThread:    def display(self):        i = 10         j = 20        print(current_thread().getName())        for num in range(i, j + 1):            if(num % 2 == 0):                print(num)  # creating an object of our class                obj = MyThread()  # creating a thread objectt = Thread(target = obj.display)  # invoking the threadt.start()
 Output:
Thread-1 
10 
12 
14 
16 
18 
20

Python-threading
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Chi-square distance in Python - GeeksforGeeks

19 Jul, 2021
Chi-square distance calculation is a statistical method, generally measures similarity between 2 feature matrices. Such distance is generally used in many applications like similar image retrieval, image texture, feature extractions etc. The Chi-square distance of 2 arrays ‘x’ and ‘y’ with ‘n’ dimension is mathematically calculated using below formula :  
In this article, we will learn how to calculate Chi-square distance using Python. Below given 2 different methods for calculating Chi-square Distance. Let’s see both of them with examples. Method #1: Calculating Chi – square distance manually using above formula.  
Python3
# importing numpy libraryimport numpy as np # Function to calculate Chi-distancedef chi2_distance(A, B):     # compute the chi-squared distance using above formula    chi = 0.5 * np.sum([((a - b) ** 2) / (a + b)                      for (a, b) in zip(A, B)])     return chi # main functionif __name__== "__main__":    a = [1, 2, 13, 5, 45, 23]    b = [67, 90, 18, 79, 24, 98]     result = chi2_distance(a, b)    print("The Chi-square distance is :", result)
Input : a = [1, 2, 13, 5, 45, 23]
        b = [67, 90, 18, 79, 24, 98] 
Output : The Chi-square distance is : 133.55428601494035

Input : a = [91, 900, 78, 30, 602, 813]
        b = [57, 49, 36, 759, 234, 928]
Output :  The Chi-square distance is : 814.776999405035
   Method #2: Using scipy.stats.chisquare() method 
Syntax: scipy.stats.chisquare(f_obs, f_exp=None, ddof=0, axis=0) Parameters: ==> f_obs : array1 ==> f_exp : array2, optional ==> ddof(Delta degrees of freedom – adjustment for p-value) : int, optional ==> axis : int or None, optional The default value of ddof and axis is 0.Returns: ==> chisq : float or ndarray ==> p-value of the test : float or ndarray  
 
Python3
# importing scipyfrom scipy.stats import chisquare k = [3, 4, 6, 2, 9, 5, 2]print(chisquare(k))
Output :  
Power_divergenceResult(statistic=8.516129032258064, pvalue=0.20267440425509237)
 
abhishek0719kadiyan
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Perl | log() Function - GeeksforGeeks

25 Jun, 2019
log() function in Perl returns the natural logarithm of value passed to it. Returns $_ if called without passing a value. log() function can be used to find the log of any base by using the formula:
Syntax: log(value)
Parameter:value: Number of which log is to be calculated
Returns:Floating point number in scalar context
Example 1:
#!/usr/bin/perl -w  # Calculating log of base 10 # using log functionprint "log10(2): ", log10(2), "\n";print "log10(7): ", log10(7), "\n";print "log10(9): ", log10(9), "\n";  # Function for log10 calculatorsub log10 {    my $n = shift;          # using pre-defined log function    return log($n) / log(10);}
Output:
log10(2): 0.301029995663981
log10(7): 0.845098040014257
log10(9): 0.954242509439325

 Example 2:
#!/usr/bin/perl -w  # Calculating log of different # base using log functionprint "log3(2): ", log3(2), "\n";print "log5(7): ", log5(7), "\n";print "log2(9): ", log2(9), "\n";  # Function for log3 calculatorsub log3 {    my $n = shift;          # using pre-defined log function    return log($n) / log(3);}  # Function for log5 calculatorsub log5{    my $n = shift;          # using pre-defined log function    return log($n) / log(5);}  # Function for log2 calculatorsub log2 {    my $n = shift;          # using pre-defined log function    return log($n) / log(2);}
Output:
log3(2): 0.630929753571457
log5(7): 1.20906195512217
log2(9): 3.16992500144231

Perl-function
Perl-Math-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | Inheritance in OOPs
Perl | Opening and Reading a File
Perl | Multidimensional Hashes
Perl | ne operator
Perl | Scope of Variables
Perl | Hashes
Perl | Data Types
Perl | defined() Function
Prototype - Event observe() Method

This method registers an event handler on a DOM element.
To register a function as an event handler, the DOM element that you want to observe must already exist in the DOM.
Event.observe(element,eventName,handler[,useCapture=false]);

Here are the explanations about the passed parameters −
element − The DOM element you want to observe; as always in Prototype, this can be either an actual DOM reference, or the ID string for the element.
element − The DOM element you want to observe; as always in Prototype, this can be either an actual DOM reference, or the ID string for the element.
evenetName − The standardized event name, as per the DOM level supported by your browser. This includes click, mousedown, mouseup, mouseover, mousemove and mouseout.
evenetName − The standardized event name, as per the DOM level supported by your browser. This includes click, mousedown, mouseup, mouseover, mousemove and mouseout.
handler −  This is the event handler function. This can be an anonymous function you create on-the-fly.
handler −  This is the event handler function. This can be an anonymous function you create on-the-fly.
useCapture − Optionally, you can request capturing instead of bubbling.  The details are in the http://www.w3.org/TR/DOM-Level-2Events/events.html.
useCapture − Optionally, you can request capturing instead of bubbling.  The details are in the http://www.w3.org/TR/DOM-Level-2Events/events.html.
NA.
Here is an example, which observe click event and take an action whenever a click event occurs.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         // Register event 'click' and associated call back.
         Event.observe(document, 'click', respondToClick);
  
         // Callback function to handle the event.
         function respondToClick(event) {
            alert("You pressed the button...." );
         }
      </script>
   </head>

   <body>
      <p id = "note"> Click anywhere to see the result.</p>
      <p id = "para1">This is paragraph 1</p>
      <p id = "para2">This is paragraph 2</p>
      <div id = "division">This is divsion.</div>
   </body>
</html>
 Click anywhere to see the result.
This is paragraph 1
This is paragraph 2

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
Redis - Set Sunionstore Command

Redis SUNIONSTORE command is used to store the members of the set resulting from the union of all the given sets. Keys that do not exist are considered to be empty sets.
Integer reply, the number of elements in the resulting set.
Following is the basic syntax of Redis SUNIONSTORE command.
redis 127.0.0.1:6379> SUNIONSTORE DESTINATION KEY KEY1..KEYN

redis 127.0.0.1:6379> SADD myset1 "hello" 
(integer) 1 
redis 127.0.0.1:6379> SADD myset1 "world" 
(integer) 1 
redis 127.0.0.1:6379> SADD myset1 "bar" 
(integer) 1 
redis 127.0.0.1:6379> SADD myset2 "hello" 
(integer) 1 
redis 127.0.0.1:6379> SADD myset2 "bar" 
(integer) 1 
redis 127.0.0.1:6379> SUNIONSTORE myset myset1 myset2 
(integer) 1 
redis 127.0.0.1:6379> SMEMBERS myset 
1) "bar" 
2) "world" 
3) "hello" 
4) "foo"


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
What are the DCL commands in DBMS?

Data control language (DCL) is used to access the stored data. It is mainly used for revoke and to grant the user the required access to a database. In the database, this language does not have the feature of rollback.
It is a part of the structured query language (SQL).
It is a part of the structured query language (SQL).
It helps in controlling access to information stored in a database. It complements the data manipulation language (DML) and the data definition language (DDL).
It helps in controlling access to information stored in a database. It complements the data manipulation language (DML) and the data definition language (DDL).
It is the simplest among three commands.
It is the simplest among three commands.
It provides the administrators, to remove and set database permissions to desired users as needed.
It provides the administrators, to remove and set database permissions to desired users as needed.
These commands are employed to grant, remove and deny permissions to users for retrieving and manipulating a database.
These commands are employed to grant, remove and deny permissions to users for retrieving and manipulating a database.
The Data Definition Language (DDL) commands are as follows −
It is employed to grant a privilege to a user. GRANT command allows specified users to perform specified tasks
Syntax
GRANT privilege_name on objectname to user;
Here,
privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
objectname is table name
objectname is table name
user is the name of the user to whom we grant privileges
user is the name of the user to whom we grant privileges
It is employed to remove a privilege from a user. REVOKE helps the owner to cancel previously granted permissions.
Syntax
 REVOKE privilege_name on objectname from user;
Here,
privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
privilege names are SELECT,UPDATE,DELETE,INSERT,ALTER,ALL
objectname is table name
objectname is table name
user is the name of the user whose privileges are removing
user is the name of the user whose privileges are removing
GRANT SELECT, UPDATE ON employees TO Bhanu
Explanation − Firstly, to give the permissions to user, we have to use GRANT command. The privileges are SELECT because to view the records and UPDATE to modify the records. The objectname is table name which is Employee. The user name is bhanu.
REVOKE SELECT, UPDATE ON employees TO Bhanu
Explanation − Firstly, to revoke the permissions to user, we have to use REVOKE command. The privileges Need to revoke are SELECT because to view the records and UPDATE to modify the records. The objectname is table name which is Employee. The user name is Bhanu.
Python program to calculate age in year - GeeksforGeeks

27 Jul, 2021
Given birth date in y/m/d format, write a Python program to find the present age in years.
Examples: 
Input : 1997/2/3
Output : 21 years (for present year i.e 2018)

Input : 2010/12/25
Output : 8 years (for present year i.e 2018)
Approach # 1: The naive approach to find the current age in years is to find the difference between the current year and birth year. Refer the Naive approach from here.
Approach #2: Using datetime module Python provides datetime module to deal with all datetime related issues in python. Using datetime we can find the age by subtracting birth year from current year. Along with this, we need to focus on the birth month and birthday. For this, we check if current month and date are less than birth month and date. If yes subtract 1 from age, otherwise 0. 
Python3
# Python3 code to  calculate age in years from datetime import date def calculateAge(birthDate):    today = date.today()    age = today.year - birthDate.year -         ((today.month, today.day) <         (birthDate.month, birthDate.day))     return age     # Driver codeprint(calculateAge(date(1997, 2, 3)), "years")
21 years
 
  Approach #3 : Efficient datetime approach The above approaches do not deal with a special case i.e. when birth date is February 29 and the current year is not a leap year. This case has to be raised as an exception because the calculation of birthdate may be inaccurate. This method includes try and catch for this exception. 
Python3
# Python3 code to  calculate age in yearsfrom datetime import date def calculateAge(born):    today = date.today()    try:        birthday = born.replace(year = today.year)     # raised when birth date is February 29    # and the current year is not a leap year    except ValueError:        birthday = born.replace(year = today.year,                  month = born.month + 1, day = 1)     if birthday > today:        return today.year - born.year - 1    else:        return today.year - born.year         # Driver codeprint(calculateAge(date(1997, 2, 3)), "years")
21 years
 
Approach #4: Using divisionIn this approach, we calculate the number of date from the birth date till current date. Divide the number of date by the days in a year i.e 365.2425. 
Python3
# Python3 code to  calculate age in yearsfrom datetime import date def calculateAge(birthDate):    days_in_year = 365.2425       age = int((date.today() - birthDate).days / days_in_year)    return age         # Driver codeprint(calculateAge(date(1997, 2, 3)), "years")
21 years
 
adnanirshad158
date-time-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Proper stack and heap usage in C++?

The stack − All variables declared inside the function will take up memory from the stack. So, any local variable inside a function lives on the stack.
The heap − This is unused memory of the program and can be used to allocate the memory dynamically when program runs. So If we want something to live longer than the function that declared it, we must allocate it on the heap.
int main() {
   int a; //get memory allocated on stack.
   int *ptr=new int[7]; //memory for 7 integers allocated on heap.
}
The main issue in heap memory is fragmentation whereas memory shortage problem is seen more likely in stack. Memory size can be changed in heap which can’t be changed in stack.
How to create a new local group using PowerShell?

To create a new local group on the local or the remote system using PowerShell, we can use the NewLocalGroup command. 
New-LocalGroup -Name "TestGroup" -Description "Test Group"
Name       Description
----       -----------
TestGroup Test Group
You can verify it from the Computer Management GUI.
To create the local group on the remote systems, you can use Invoke-Command. For example,
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   New-LocalGroup -Name 'TestGroup' -Description 'New Test Group'
}
The above command will create a New Local group named ‘TestGroup’ on the remote systems, Test1-Win2k12, and Test1-Win2k16.
New-LocalGroup command is available in the module Microsoft.PowerShell.LocalAccounts which is part of the PowerShell version 5.1 or higher versions. If you have the older PowerShell version system then you can use the cmd command.
Net localgroup 'TestGroup2' /add
For the remote servers,
Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16 -ScriptBlock{
   Net Localgroup ‘TestGroup2’ /add
}
Filtering Operators in LINQ

Filtering is an operation to restrict the result set such that it has only selected elements satisfying a particular condition.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Operators {
   class Program {
      static void Main(string[] args) {

         string[] words = { "humpty", "dumpty","set", "on", "a", "wall" };

         IEnumerable<string> query = from word in words where word.Length == 3 select word;
		 
         foreach (string str in query)
            Console.WriteLine(str);
            Console.ReadLine();            
      }
   }
}
Module Module1

   Sub Main()
      Dim words As String() = {"humpty", "dumpty", "set", "on", "a", "wall"}

      Dim query = From word In words Where word.Length = 3 Select word

      For Each n In query
         Console.WriteLine(n)
		 
      Next
         Console.ReadLine()
   End Sub
   
End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
set


    23 Lectures 
     1.5 hours 

 Anadi Sharma

    37 Lectures 
     13 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
How to remove swap files using Python?

Swap files have the extension .swp. Easiest way to remove all swap files from a folder recursively is to use the string function endswith with the extension name(.swp) to match file names and delete these files. 
import os, os.path
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: x.endswith('.swp'), files):
        os.remove(os.path.join(root, file))
This program will recursively search the directory, "my_folder" and delete all files that end with .swp.
Set Column Names when Using cbind Function in R - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to set the column names when using cbind() function in R Programming language.
Let’s create and combine two vectors for demonstration:
R
# create two vectors with integer and string typesvector1 = c(1,2,3,4,5)  vector2 = c("sravan","bobby",            "ojsawi","gnanesh",            "rohith")  # displayprint(vector1)print(vector2)  # combine two vectors using cbind()print(cbind(vector1, vector2))
Output:
[1] 1 2 3 4 5
[1] "sravan"  "bobby"   "ojsawi"  "gnanesh" "rohith"  
    vector1 vector2  
[1,] "1"     "sravan"  
[2,] "2"     "bobby"  
[3,] "3"     "ojsawi"  
[4,] "4"     "gnanesh"
[5,] "5"     "rohith"
colnames() function in R Language is used to set the names to columns of a matrix.
Syntax:colnames(x) <- value
Parameters:x: Matrixvalue: Vector of names to be set
Example: R program to set the column names using colnames() function.
R
# create two vectors with integer and string typesvector1 = c(1,2,3,4,5)  vector2 = c("sravan","bobby","ojsawi",            "gnanesh","rohith")  # displayprint(vector1)print(vector2)  # combine two vectors using cbind()combined = cbind(vector1,vector2)  # Applying colnamescolnames(combined) = c("vector 1", "vector 2")      # displaycombined
Output:
Here, we have to give column names in the cbind() function itself.
Syntax: cbind(column_name = data1, column_name= data2,.........,column_name=data n)
where
data is the input data to be combinescolumn_name is the new column name.
data is the input data to be combines
column_name is the new column name.
Example: R program to set the column name within cbind() function for three vectors
R
# create three vectors with integer and string typesvector1 = c(1,2,3,4,5)  vector2 = c("sravan","bobby","ojsawi",            "gnanesh","rohith")  vector3 = c(12,34,21,34,51)  # displayprint(vector1)print(vector2)print(vector3)  # combine three vectors with in  cbind() functioncombined = cbind("ID"=vector1,                 "NAME"=vector2,"AGE"=vector3)  # displaycombined
Output:
Picked
R DataFrame-Programs
R Vector-Programs
R-DataFrame
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Merge DataFrames by Column Names in R
C# | Remove all elements from a HashSet - GeeksforGeeks

01 Feb, 2019
A HashSet is an unordered collection of the unique elements. It comes under the System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.Clear Method is used to remove all the elements from a HashSet object.
Syntax:
mySet.Clear(); 

Here, mySet is the name of the HashSet.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to remove all elements from HashSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of integers        HashSet<int> mySet = new HashSet<int>();          // Inserting even numbers less than        // equal to 20 in HashSet mySet1        for (int i = 0; i < 10; i++) {            mySet.Add(i * 2);        }          // Displaying the number of elements in HashSet        Console.WriteLine(mySet.Count);          // Removing all the elements from HashSet        mySet.Clear();          // Displaying the number of elements in HashSet        // after removing all the elements from it        Console.WriteLine(mySet.Count);    }}
10
0

Example 2:
// C# code to remove all elements from HashSetusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of strings        HashSet<string> mySet = new HashSet<string>();          // Inserting elements in HashSet        mySet.Add("Geeks");        mySet.Add("and");        mySet.Add("GeeksforGeeks");        mySet.Add("are");        mySet.Add("the");        mySet.Add("best");          // Displaying the number of elements in HashSet        Console.WriteLine(mySet.Count);          // Removing all the elements from HashSet        mySet.Clear();          // Displaying the number of elements in HashSet        // after removing all the elements from it        Console.WriteLine(mySet.Count);          // Inserting elements in HashSet        mySet.Add("Join");        mySet.Add("Geeks");        mySet.Add("Classes");          // Displaying the number of elements in HashSet        Console.WriteLine(mySet.Count);    }}
6
0
3

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.clear?view=netframework-4.7.2
CSharp-Generic-HashSet
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
How to get the current year in JavaScript?

To get the current year, use the getFullYear() JavaScript method. JavaScript date getFullYear() method returns the year of the specified date according to local time. The value returned by getFullYear() is an absolute number. For dates between the years 1000 and 9999, getFullYear() returns a four-digit number, for example, 2008.
You can try to run the following code to get the current year −
Live Demo
<html>
   <head>
      <title>JavaScript getFullYear Method</title>
   </head>
   <body>
      <script>
         var dt = new Date("December 30, 2017 21:25:10");
         document.write("getFullYear() : " + dt.getFullYear() );
      </script>
   </body>
</html>
getFullYear() : 2017
Working with two-dimensional array at runtime in C programming

Write a C program to calculate sum and product of all elements in two-dimensional array using run time compilation.
Runtime compilation or initialization is also called as dynamic allocation. Allocation of memory at the time of execution (run time) is known as dynamic memory allocation.
Runtime compilation or initialization is also called as dynamic allocation. Allocation of memory at the time of execution (run time) is known as dynamic memory allocation.
The functions calloc() and malloc() support allocating of dynamic memory.
The functions calloc() and malloc() support allocating of dynamic memory.
In this program, we will calculate the sum of all elements and product of all elements of two-dimensional array at run time.
Logic for computing sum of all elements in 2D array −
printf("Sum array is : \n");
for(i=0;i<2;i++){
   for(j=0;j<3;j++){
      sum[i][j]=A[i][j]+B[i][j];
      printf("%d\t",sum[i][j]);
   }
   printf("\n");
}
Logic for computing product of all elements in 2D array −
printf("Product array is : \n");
for(i=0;i<2;i++){
   for(j=0;j<3;j++){
      product[i][j]=A[i][j]*B[i][j];
      printf("%d\t",product[i][j]);
   }
   printf("\n");
}
}
 Live Demo
#include<stdio.h>
void main(){
   //Declaring the array - run time//
   int A[2][3],B[2][3],i,j,sum[i][j],product[i][j];
   //Reading elements into the array's A and B using for loop//
   printf("Enter elements into the array A: \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("A[%d][%d] :",i,j);
         scanf("%d",&A[i][j]);
      }
      printf("\n");
   }
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         printf("B[%d][%d] :",i,j);
         scanf("%d",&B[i][j]);
      }
      printf("\n");
   }
   //Calculating sum and printing output//
   printf("Sum array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         sum[i][j]=A[i][j]+B[i][j];
         printf("%d\t",sum[i][j]);
      }
      printf("\n");
   }
   //Calculating product and printing output//
   printf("Product array is : \n");
   for(i=0;i<2;i++){
      for(j=0;j<3;j++){
         product[i][j]=A[i][j]*B[i][j];
         printf("%d\t",product[i][j]);
      }
      printf("\n");
   }
}
Enter elements into the array A:
A[0][0] :A[0][1] :A[0][2] :
A[1][0] :A[1][1] :A[1][2] :
B[0][0] :B[0][1] :B[0][2] :
B[1][0] :B[1][1] :B[1][2] :
Sum array is :
000
000
Product array is :
000
000