code-rag-bench/online-tutorials huggingface dataset:
Find Weekday using Zeller's Algorithm

Zeller’s Algorithm is used to find the weekday from a given date. The formula to find weekday using Zeller’s Algorithm is here:
The formula is containing some variables; They are −
d − The day of the date.
m: It is the month code. From March to December it is 3 to 12, for January it is 13, and for February it is 14. When we consider January or February, then given year will be decreased by 1.
y − Last two digits of the year
c − first two digits of the year
w − The weekday. When it is 0, it is Saturday, when it is 6, it means Friday
Input:
The day, month and the year: 4, 1, 1997
Output:
It was: Saturday
zellersAlgorithm(day, month, year)
Input: The date of the day.
Output: Which day it was, (Sunday to Saturday).
Begin
   if month > 2, then
      mon := month
   else
      mon := 12 + month
      decrease year by 1
   y := last two digit of the year
   c := first two digit of the year
   w := day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + 5*c
   w := w mod 7
   return weekday[w] //weekday will hold days from Saturday to Friday
End
#include<iostream>
#include<cmath>
using namespace std;

string weekday[7] = {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
                               
string zellersAlgorithm(int day, int month, int year) {
   int mon;
   if(month > 2)
      mon = month;    //for march to december month code is same as month
   else {
      mon = (12+month);    //for Jan and Feb, month code will be 13 and 14
      year--; //decrease year for month Jan and Feb
   }
         
   int y = year % 100;    //last two digit
   int c = year / 100;    //first two digit
   int w = (day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + (5*c));
   w = w % 7;
   return weekday[w];
}

int main() {
   int day, month, year;
   cout << "Enter Day: "; cin >>day;
   cout << "Enter Month: "; cin >>month;
   cout << "Enter Year: "; cin >>year;
   cout << "It was: " <<zellersAlgorithm(day, month, year);
}
Enter Day: 04
Enter Month: 01
Enter Year: 1997
It was: Saturday
Python Grouping similar substrings in list

In this tutorial, we are going to write a program that groups similar substrings from a list. Let's see an example to understand it more clearly.
strings = ['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript', 'python-1', 'python-2',
'javascript-1']
[['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript'], ['python-1', 'python-2'],
['javascript-1']]
We are going to use the groupby method from itertools module to solve the problem. The groupby method will group all the similar string into an iter object. For the given list we have split the string with - and pass the first part of the string to the groupby method.
Let's see the steps involved in solving this problem.
Initialize the list of strings.
Import the itertools module.
Initialize an empty list.
Now, pass the strings and a lambda function to the itertools.groupby method.
The lambda function should return first part of the string after splitting it with −
The groupby method will return a list of the tuples with the element and its group.
In every iteration, convert the group of similar elements into a list.
Append the list to the empty list.
Print the result.
 Live Demo
# importing the itertools module
import itertools
# initializing the strings
strings = ['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript', 'python-1', 'python-2', 'javascript-1']
# empty list
result = []
# iterator
# lambda function will return first part from the string
iterator = itertools.groupby(strings, lambda string: string.split('-')[0])
# iterating over the result
# element and its group
for element, group in iterator:
   # appending the group by converting it into a list
   result.append(list(group))
# printing the result
print(result)
If you run the above code, then you will get the following result.
[['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript'],
ython-1', 'python-2'], ['javascript-1']]
If you have any doubts in the tutorial, mention them in the comment section.
Calculate the Mean of each Row of an Object in R Programming – rowMeans() Function - GeeksforGeeks

05 Jun, 2020
rowMeans() function in R Language is used to find out the mean of each row of a data frame, matrix, or array.
Syntax: rowMeans(data)
Parameter:data: data frame, array, or matrix
Example 1
# R program to illustrate # rowMean function     # Create example values   # Set seedset.seed(1234)    # Create example data                                      data <- data.frame(matrix(round(runif(12, 2, 20)),                               nrow = 4, ncol = 3))   # Print dataprint(rowMeans(data))                                      
Output:
[1] 11.666667 12.666667  9.666667 10.333333
Example 2:
# R program to illustrate # rowMean function   # Create example data with NAdata_na <- data.frame(matrix(round(runif(12, 2, 20)),                               nrow = 4, ncol = 3))                                 data_na[rbinom(length(data_na), 1, 0.3) == 1] <- NAdata_na <- as.data.frame(data_na)       print(rowMeans(data_na, na.rm = TRUE)) 
Output:
[1]  3 16  9  3
R DataFrame-Function
R Math-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
Byte Code in Java - GeeksforGeeks

19 Oct, 2021
Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source code(JAVA Program). This intermediate code makes Java a platform-independent language.
Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine). The byte code is the common piece between the compiler(which creates it) and the Interpreter (which runs it).
Let us look at this phenomenon, step by step
Suppose you are writing your first JAVA program.
Java
/*package whatever //do not write package name here */import java.io.*;  class GFG {    public static void main (String[] args) {        System.out.println("GFG!");    }}
GFG!

The above-written code is called JAVA source code.
The compiler compiles the source code.
Finally, Interpreter executes the compiled source code.
Whenever we write any program, it is not written in machine code. We write it in a high-level language like JAVA, C++, Python, etc. But the computer understands only the machine code. So when we execute our program, it is first converted into machine code or Byte code by the compiler and then executed by the Interpreter. 
This intermediate code or the byte can run on any platform making, JAVA a platform-independent language.
Picked
TrueGeek-2021
Java
TrueGeek
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
Types of Internet Protocols
Class getResource() method in Java with Examples

27 Dec, 2019
The getResource() method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object.
Syntax:
public URL getResource(String resourceName)

Parameter: This method accepts a parameter resourceName which is the resource to get.
Return Value: This method returns the specified resource of this class in the form of URL objects.
Exception This method throws:
NullPointerException if name is null
Below programs demonstrate the getResource() method.
Example 1:
// Java program to demonstrate// getResource() method  import java.util.*;  public class Test {      public int obj = 10;      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());          String resourceName = "obj";          // Get the resource of myClass        // using getResource() method        System.out.println(            resourceName + " resource of myClass: "            + myClass.getResource(resourceName));    }}
Class represented by myClass: class Test
obj resource of myClass: null

Example 2:
// Java program to demonstrate// getResource() method  import java.util.*;  class Main {      private Object obj;      public static void main(String[] args)        throws ClassNotFoundException, NoSuchFieldException    {          // returns the Class object for this class        Class myClass = Class.forName("Main");          System.out.println("Class represented by myClass: "                           + myClass.toString());          String resourceName = "obj";          try {            // Get the resource of myClass            // using getResource() method            System.out.println(                resourceName + " resource of myClass: "                + myClass.getResource(resourceName));        }        catch (Exception e) {            System.out.println(e);        }    }}
Class represented by myClass: class Main
obj resource of myClass: null

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResource-java.lang.String-
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.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python – Group keys to values list

10 May, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this task can be performed.
Method #1 : Using loop + defaultdict()The combination of above functionalities can be used to perform this task. In this, we capture all the elements in a list by initializing defaultdict with list datatype and keep on appending all the values to associated key.
# Python3 code to demonstrate working of # Group keys to values list# Using loop + defaultdict()from collections import defaultdict  # initializing listtest_list = [{'gfg' : 1, 'is' : 4, 'best' : 7},              {'gfg' : 9, 'is' : 8, 'best' : 3},             {'gfg' : 4, 'is' : 4, 'best' : 7},             {'gfg' : 7, 'is' : 2, 'best' : 8},             {'gfg' : 1, 'is' : 4, 'best' : 7},             {'gfg' : 10, 'is' : 9, 'best' : 2},             {'gfg' : 0, 'is' : 5, 'best' : 6}]  # printing original listprint("The original list is : " + str(test_list))  # Group keys to values list# Using loop + defaultdict()res = defaultdict(set)for sub in test_list:    for key, val in sub.items():        res[key].add(val)  # printing result print("The grouped key values : " + str(dict(res))) 
The original list is : [{‘best’: 7, ‘gfg’: 1, ‘is’: 4}, {‘best’: 3, ‘gfg’: 9, ‘is’: 8}, {‘best’: 7, ‘gfg’: 4, ‘is’: 4}, {‘best’: 8, ‘gfg’: 7, ‘is’: 2}, {‘best’: 7, ‘gfg’: 1, ‘is’: 4}, {‘best’: 2, ‘gfg’: 10, ‘is’: 9}, {‘best’: 6, ‘gfg’: 0, ‘is’: 5}]The grouped key values : {‘best’: {8, 2, 3, 6, 7}, ‘gfg’: {0, 1, 4, 7, 9, 10}, ‘is’: {8, 9, 2, 4, 5}}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy np.disp() method

02 Dec, 2019
With the help of np.disp() method, we can get the string into a display buffer and by using stringIO class we can get the values from buffer by using np.disp() method.
Syntax : np.disp(message, device)Return : Will not return anything without StringIO class.
Example #1 :In this example by using np.disp() method, we are able to collect message from parameter and put that message into display buffer by using this method.
# import numpy and stringIOimport numpy as npfrom io import StringIO  buf = StringIO()# using np.disp() methodnp.disp(u'Geeks For Geeks', device = buf)buf.getvalue()
Output :
‘Geeks For Geeks\n’
Example #2 :
# import numpy and stringIOimport numpy as npfrom io import StringIO  buf = StringIO()# using np.disp() methodnp.disp(u'Author "Jitender Kumar"', device = buf)buf.getvalue()
Output :
‘Author “Jitender Kumar”\n’
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Difference between big O notations and tilde

09 Jun, 2021
In asymptotic analysis of algorithms we often encounter terms like Big-Oh, Omega, Theta and Tilde, which describe the performance of an algorithm. You can refer to the following links to get more insights about asymptotic analysis :
Analysis of Algorithms Different NotationsDifference between Big Oh, Big Omega and Big Theta
Analysis of Algorithms 
Different Notations
Difference between Big Oh, Big Omega and Big Theta
In this article we are going to see the difference between the two notations: Big Oh and Tilde.
1. Big Oh notation (O) :This notation is basically used to describe the asymptotic upper bound. Mathematically, we can describe it as :
f(n) = O(g(n)) 
if there exist positive constants c and 
n0 such that 
0 <= f(n) <= c*g(n) 
for all n >= n0
The above notation depicts that at the point n=n0, the growth of the function g(n) increases gradually. In algorithms we always deal with larger values of n i.e. n→∞. So, we can also define the Big-Oh notation as :
Therefore, f(n) = O(g(n)) if the above limit value lies in the range [ 0 , ∞ )
Example – 
2. Tilde Notation (~) :Tilde notation is used when we want to make a simple approximation of a complex function. It simply drops the lower order terms. It is denoted by ~g(n).If f(n)~g(n) indicates that the value of f(n)/g(n) tends towards 1 for a larger value of n. Mathematically, we can express it as :
Example 1.  can be written as ~because when we divide both the functions and find the limit for larger value of n, it will become 1.
2 – In an AVL tree before we insert or delete a key, we first compare and find the location of the key. The number of comparisons required in the worst case is :
h+1, where h is the height of the tree. 
The height will be , since AVL tree is a height balanced tree. 
Therefore, we can replace the value of h in the expression and it becomes :
We can ignore the lower order term and it becomes ~. So, the number of comparisons in an AVL tree is approximated to ~.
Some important points about ~ notation in asymptotic analysis –
It follows equivalence relation property.
It is identical to big theta notation. There is a minute difference in the arbitrary constant as in big theta notation there can be different values for the constants in the lower bound as well as upper bound but in the case of Tilde, we always get f/g value as 1 or tending towards 1.
The differences between Big Oh and Tilde notations are :
The arbitrary constant incase of Big Oh notation is c which is greater than zero.
0 <= f(n) <= c*g(n) ; c>0, n>=n0
If the time complexity of any algorithm is 
,it  is given by O() and the constant is ignored.
Algorithms-Analysis of Algorithms
Picked
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Three address code in Compiler
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Phases of a Compiler
Difference between DELETE, DROP and TRUNCATE
Code Optimization in Compiler Design
Segmentation in Operating System
User Datagram Protocol (UDP)
Peephole Optimization in Compiler Design
Python | Find elements of a list by indices

18 Apr, 2019
Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2.
Examples:
Input : lst1 = [10, 20, 30, 40, 50]
        lst2 = [0, 2, 4]
Output : [10, 30, 50]
Explanation: 
Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively. 

Input : lst1 = ['Hello', 'geeks', 'for', 'geeks']
        lst2 = [1, 2, 3]
Output : ['geeks', 'for', 'geeks']

 Below are some Pythonic approaches to do the above task.
Approach #1 : Naive(List comprehension)
The first approach to find the desired elements is to use list comprehension. We traverse through ‘lst2’ and for each ith element, we output lst1[i].
# Python3 program to Find elements of a # list by indices present in another list  def findElements(lst1, lst2):    return [lst1[i] for i in lst2]              # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]

 Approach #2 : Using Python map()
We can also use Python map() method where we apply lst1.__getitem__ function on lst2 which return lst1[i] for each element ‘i’ of lst2.
# Python3 program to Find elements of a # list by indices present in another list  def findElements(lst1, lst2):    return list(map(lst1.__getitem__, lst2))              # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]

 Approach #3 : Using itemgetter()
# Python3 program to Find elements of a # list by indices present in another listfrom operator import itemgetter   def findElements(lst1, lst2):    return list((itemgetter(*lst2)(lst1)))              # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]

 Approach #4 : Using numpy
# Python3 program to Find elements of a # list by indices present in another listimport numpy as np   def findElements(lst1, lst2):    return list(np.array(lst1)[lst2])              # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find max and second max salary for a MySQL Employee table?

You can get max and second max salary from an Employee table using LIMIT OFFSET. The syntax is as follows −
SELECT yourColumnName1,yourColumnName2,....N from yourTableName ORDER BY
yourColumnName desc limit 2 offset 0;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table EmployeeMaxAndSecondMaxSalary
   -> (
   -> EmployeeId int,
   -> Employeename varchar(20),
   -> EmployeeSalary int
   -> );
Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into EmployeeMaxAndSecondMaxSalary values(1,'John',34566);
Query OK, 1 row affected (0.20 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(2,'Bob',56789);
Query OK, 1 row affected (0.17 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(3,'Carol',44560);
Query OK, 1 row affected (0.26 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(4,'Sam',76456);
Query OK, 1 row affected (0.29 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(5,'Mike',65566);
Query OK, 1 row affected (0.14 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(6,'David',89990);
Query OK, 1 row affected (0.19 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(7,'James',68789);
Query OK, 1 row affected (0.12 sec)

mysql> insert into EmployeeMaxAndSecondMaxSalary values(8,'Robert',76543);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from EmployeeMaxAndSecondMaxSalary;
The following is the output −
+------------+--------------+----------------+
| EmployeeId | Employeename | EmployeeSalary |
+------------+--------------+----------------+
|          1 | John         | 34566          |
|          2 | Bob          | 56789          |
|          3 | Carol        | 44560          |
|          4 | Sam          | 76456          |
|          5 | Mike         | 65566          |
|          6 | David        | 89990          |
|          7 | James        | 68789          |
|          8 | Robert       | 76543          |
+------------+--------------+----------------+
8 rows in set (0.00 sec)
The following is the query to get the max and second max salary using limit offset −
mysql> select EmployeeId,Employeename,EmployeeSalary from EmployeeMaxAndSecondMaxSalary order by
   -> EmployeeSalary desc limit 2 offset 0;
The output displays the record of 2 employees with the maximum salary −
+------------+--------------+----------------+
| EmployeeId | Employeename | EmployeeSalary |
+------------+--------------+----------------+
|          6 | David        |          89990 |
|          8 | Robert       |          76543 |
+------------+--------------+----------------+
2 rows in set (0.00 sec)
How to create FileFilter for JFileChooser in Java and display File Type accordingly?

To create FileFilter, use the FileNamExtensionFilter class. The following is an example to display File Type in JFileChooser −
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class SwingDemo {
   public static void main(String[] args) {
      JFileChooser file = new JFileChooser();
      file.setAcceptAllFileFilterUsed(false);
      FileNameExtensionFilter extFilter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
      file.addChoosableFileFilter(extFilter);
      file.showOpenDialog(null);
   }
}
How to get substring between two similar characters in JavaScript?

Let’s say we have the following string with some colons −
var values="This is:the first program in JavaScript:After that I will do Data Structure program";
We need to get the substring between the colon. The output should be −
the first program in JavaScript

For this, use the concept of split().
Following is the code −
var values="This is:the first program in JavaScript:After that I will do Data Structure program";
var result=[];
result=values.split(":");
console.log(result[1]);
To run the above program, you need to use the following command −
node fileName.js.

Here, my file name is demo273.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo273.js
the first program in JavaScript
Print the longest prefix of the given string which is also the suffix of the same string in C Program.

Given a string in which we have to check that the length of the longest prefix which is also a suffix of the string like there is a string “abcab” so here “ab” is of length 2 and is the longest substring with same prefix and suffix.
Input: str[] = { “aabbccdaabbcc” }
Output: 6
Input: abdab
Output: 2
If we will start the pointer from start and end of the string than they will get overlapped at some point so instead of doing that we will break the string from middle and start matching left and right string. If they are equal return size of any one of the matched string else try for shorter lengths on both the sides.
int longest(char str[], int n)
START
STEP 1 : DECLARE length AS 0 AND i AS n/2
STEP 2 : IF n < 2 THEN
   RETURN 1
STEP 3 :LOOP WHILE TILL str[i]!='\0'
   IF str[i] == str[length] THEN,
      INCREMENT length BY 1
      INCREMENT i BY 1
   ELSE
      IF length == 0 THEN,
         INCREMENT i BY 1
      ELSE
         DECREMENT length BY 1
      END IF
   END IF
END WHILE
RETURN length
STOP
#include <stdio.h>
int longest(char str[], int n){
   int length = 0, i = n/2;
   if( n < 2 )
      return 1;
   while( str[i]!='\0' ){
      //When we find the character like prefix in suffix,
      //we will move the length and i to count the length of the similar prefix and suffix
      if (str[i] == str[length]){
         ++length;
         ++i;
      } else //When prefix and suffix not equal{
         if(length == 0)
            ++i;
         else
            --length;
      }
   }
   return length;
}
int main(int argc, char const *argv[]){
   char str[] = {"abccmmabcc"};
   int n = sizeof(str)/sizeof(str[0]);
   int length = longest(str, n);
   printf("Length = %d", length);
   return 0;
}
If we run above program then it will generate following output:
Length = 4
Logical Operators in C++

The concept of logical operators is simple. They allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to a true or false value. Then the value of the conditions is used to determine the overall value of the op1 operator op2 or !op1 grouping.
The logical OR operator (||) returns the boolean value true if either or both operands are true and returns false otherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical OR has left-to-right associativity. The operands to the logical OR operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions.
The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical OR expression. The second operand is evaluated only if the first operand evaluates to false (0). This eliminates needless evaluation of the second operand when the logical OR expression is true.
The logical AND operator (&&) returns the boolean value true if both operands are true and return false otherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical AND has left-to-right associativity. The operands to the logical AND operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions.
The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical AND expression. The second operand is evaluated only if the first operand evaluates to true (nonzero). This evaluation eliminates needless evaluation of the second operand when the logical AND expression is false.
The logical negation operator (!) reverses the meaning of its operand. The operand must be of arithmetic or pointer type (or an expression that evaluates to arithmetic or pointer type). The operand is implicitly converted to type bool. The result is true if the converted operand is false; the result is false if the converted operand is true. The result is of type bool.
#include<iostream>
using namespace std;
int main() {
   bool x = true, y = false;
   cout << (x || y) << endl;
   cout << (x && y) << endl;
   cout << (!x) << endl;
   return 0;
}
This will give the output −
1
0
0
This is because one of the 2 is false, so and is false, one is true so or is true and not of true(x) is false, ie, 0.
JavaScript - Date getMonth() Method

Javascript date getMonth() method returns the month in the specified date according to local time. The value returned by getMonth() is an integer between 0 and 11. 0 corresponds to January, 1 to February, and so on.
Its syntax is as follows −
Date.getMonth()

Returns the Month in the specified date according to local time.
Try the following example.
<html>
   <head>
      <title>JavaScript getMonth Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var dt = new Date( "December 25, 1995 23:15:00" );
         document.write("getMonth() : " + dt.getMonth() ); 
      </script>      
   </body>
</html>
getMonth() : 11 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
What does an auto keyword do in C++?

Auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used. All this changed with the introduction of auto to do type deduction from the context in C++11. Before C++ 11, each data type needs to be explicitly declared at compile time, limiting the values of an expression at runtime but after a new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself.
With type inference capabilities, we can spend less time having to write out things compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the runtime of the program.
The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.
#include<iostream>
#incllude<vector>
using namespace std;

int main() {
   vector<int> vec(10);       // Auto deduce type to be iterator of a vector of ints.
   for(auto it = vec.begin(); it != vec.end(); vec ++)
   {
      cin >> *it;
   }
   return 0;
}
How can I create a stored procedure to update values in a MySQL table?

We can create a stored procedure with IN operator to update values in a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Bangalore  | Computers  |
+------+---------+------------+------------+
4 rows in set (0.01 sec)
Now, by creating the procedure named ‘update_studentinfo’ as follow, we can update the values in ‘student_info’ table −
mysql> DELIMITER // ;
mysql> Create Procedure Update_studentinfo ( IN p_id INT, IN p_address varchar(20))
   -> BEGIN
   -> UPDATE student_info
   -> SET
   -> address = p_address WHERE id = p_id;
   -> END //
Query OK, 0 rows affected (0.13 sec)
Now, invoke the procedure with the values we want to update in the table as follows −
mysql> Delimiter ; //
mysql> CALL Update_studentinfo(125, 'Shimla');
Query OK, 1 row affected (0.14 sec)

mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Shimla     | Computers  |
+------+---------+------------+------------+
4 rows in set (0.00 sec)
The above result set shows that the address of record having id = 125 updated in the table.
How to detect long press in Android?

This example demonstrates how do I detect long Press in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textStyle="bold"
      android:text="Hold touch to detect Long Press"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   GestureDetector gestureDetector;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      gestureDetector = new GestureDetector(this, new GestureListener());
   }
   private class GestureListener extends GestureDetector.SimpleOnGestureListener {
      @Override
      public void onLongPress(MotionEvent e) {
         super.onLongPress(e);
         Toast.makeText(MainActivity.this, "Long pressed", Toast.LENGTH_SHORT).show();
      }
   }
   public boolean onTouchEvent(MotionEvent event) {
      gestureDetector.onTouchEvent(event);
      return super.onTouchEvent(event);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
C Program for Naive algorithm for Pattern Searching

Pattern matching in C− We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed. We tend to create a function that receives 2 character arrays and returns the position if matching happens otherwise returns -1.
Input: txt = "HERE IS A NICE CAP"
   pattern = "NICE"
Output: Pattern found at index 10
Input: txt = "XYZXACAADXYZXYZX"
   pattern = "XYZX"
Output: Pattern found at index 0
   Pattern found at index 9
   Pattern found at index 12
We are solving this problem with Naive Pattern Searching. This algorithm is useful for smaller texts. Naive is a simple and inefficient way to see wherever one string occurs within another is to examine every place it could be at, one by one, to examine if it's there.
The time complexity of the Naive Algorithm is O(mn), where m is the size of the pattern to be searched and n is the size of the container string.
Pattern searching is a very crucial problem in computer science. Whenever we seek for a string in notepad/word file or browser or database or in some information,
pattern searching algorithms are used to show the search results.
naive_algorithm(pattern, text)
Input − The text and the pattern
Output − locations, where the pattern is present in the text
Start
   pat_len := pattern Size
   str_len := string size
   for i := 0 to (str_len - pat_len), do
      for j := 0 to pat_len, do
         if text[i+j] ≠ pattern[j], then
         break
   if j == patLen, then
   display the position i, as there pattern found
End
 Live Demo
#include <stdio.h>
#include <string.h>
int main (){
   char txt[] = "tutorialsPointisthebestplatformforprogrammers";
   char pat[] = "a";
   int M = strlen (pat);
   int N = strlen (txt);
   for (int i = 0; i <= N - M; i++){
      int j;
      for (j = 0; j < M; j++)
         if (txt[i + j] != pat[j])
      break;
      if (j == M)
         printf ("Pattern matches at index %d \n", i);
   }
   return 0;
}
Pattern matches at 6
Pattern matches at 25
Pattern matches at 39
Asynchronous programming in C# using Async and Await keyword

Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. The application stops responding. Using the asynchronous approach, the applications continue with other tasks as well.
The async and await keywords in C# are used in async programming. Using them, you can work with .NET Framework resources, .NET Core, etc.  Asynchronous methods defined using the async keyword are called async methods.
An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding to messages if the processing takes more time than expected.
Let us see what is discussed above −
private void OnRequestDownload(object sender, RoutedEventArgs e) {
   var req = HttpWebRequest.Create(_requestedUri);
   var res = req.GetResponse();
}
To solve the above issue, use the async and await keywords −
private async void OnRequestDownload(object sender, RoutedEventArgs e) {
   var req= HttpWebRequest.Create(_requestedUri);
   var res = await req.GetResponseAsync();
}
How to get hour, minutes and seconds in android using offset time API class?

This example demonstrate about How to get hour, minutes and seconds in android using offset time API class.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/date"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Local Date"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show hour, minutes and seconds.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.time.OffsetTime;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView = findViewById(R.id.date);
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
         OffsetTime offset = OffsetTime.now();
         textView.setText(String.valueOf(offset.getHour() + " : " + offset.getMinute() + " : " + offset.getSecond()));
      }
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it is showing current hour, minutes and seconds.
Click here to download the project code
How to convert JSON text to JavaScript JSON object?

The JSON parse() method is used for converting a JSON text to a JavaScript object.
Following is the code for converting JSON text to JavaScript JSON object −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JSON parse() Method</h1>
<div class="sample">
{"name":"Rohan", "sports":["Cricket","Football"], "country":"India"}
</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to parse the above JSON string
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let resultEle = document.querySelector(".result");
   let parsedJson = JSON.parse(sampleEle.innerHTML);
   document.querySelector(".Btn").addEventListener("click", () => {
      resultEle.innerHTML = "Name = " + parsedJson.name + "<br>";
      resultEle.innerHTML += "Country = " + parsedJson.country + "<br>";
      resultEle.innerHTML += "Sports = " + parsedJson.sports;
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “CLICK HERE” button −
Jasmine JavaScript Testing - toBe vs toEqual

Arrays can be compared in 2 ways −
They refer to the same array object in memory.
They refer to the same array object in memory.
They may refer to different objects but their contents are all equal.
They may refer to different objects but their contents are all equal.
For case 1, jasmine provides the toBe method. This checks for reference.
For example,
describe("Array Equality", () => {
   it("should check for array reference equility", () => {
      let arr = [1, 2, 3];
      let arr2 = arr
      // Runs successfully
      expect(arr).toBe(arr2);
      // Fails as references are not equal
      expect(arr).toBe([1, 2, 3]);
   });
});
This will give the output −
1) Array Equality should check for array equility
Message:
   Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().
For case 2 we can use the toEqual method and deep compare the arrays. For
example,
describe("Array Equality", () => {
   it("should check for array reference equility", () => {
      let arr = [1, 2, 3];
      let arr2 = arr;
      // Runs successfully
      expect(arr).toEqual(arr2);
      // Runs successfully
      expect(arr).toEqual([1, 2, 3]);
   });
});
This will give the output −
1 spec, 0 failures
Geek-onacci Number || | Practice | GeeksforGeeks

Geek created a random series and given a name geek-onacci series. Given four integers A, B, C, N. A, B, C represents the first three numbers of geek-onacci series. Find the Nth number of the series. The nth number of geek-onacci series is a sum of the last three numbers (summation of N-1th, N-2th, and N-3th geek-onacci numbers)

Note: The answer can be very large. So, output answer modulo 109 + 7. 
Input: 
1. The first line of the input contains a single integer  T denoting the number of test cases. The description of T test cases follows.
2. The first line of each test case contains four space-separated integers A, B, C, and N.

Output: For each test case, print Nth geek-onacci number

Constraints:
1. 1 <= T <= 102
2. 1 <= A, B, C <= 105
3. 4 <= N <= 104

Example:
Input:
3
1 3 2 4
1 3 2 5
1 3 2 6
Output:
6
11
19
0
mohammedfahad17086 days ago
#include <iostream>using namespace std;
  int geek(int a,int b,int c,int N){    int count =3;    int sum=0;    while(count<N){        sum = ((a + b) % 1000000007 + c ) % 1000000007;        a=b;        b=c;        c=sum;        count++;    }    return c;}int main() { int n;cin>>n;int a,b,c,N;for(int i=0;i<n;i++){    cin>>a>>b>>c>>N;    cout<<geek(a,b,c,N)<<endl;}return 0;}
0
Debojyoti Sinha1 year ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.01
#include <bits stdc++.h="">using namespace std;int geekonacciNumber(int A, int B, int C, int N){    int D;        for(int i = 4; i <= N; i++)    {        D = ((A + B) % 1000000007 + C ) % 1000000007;                A = B;        B = C;        C = D;    }        return D;}int main(){    ios_base::sync_with_stdio(false);     cin.tie(NULL);        int T;    cin >> T;        while(T--)    {        int A, B, C, N;        cin >> A >> B >> C >> N;                cout << geekonacciNumber(A, B, C, N) << "\n";    }        return 0;}
0
Rahul sharma1 year ago
Rahul sharma
0
Rahul sharma
This comment was deleted.
0
Rahul sharma
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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

To convert String to float, use the valueOf() method.
Let’s say we have the following string value.
String str = "0.8";
Converting the string to float.
Float floatVal = Float.valueOf(str).floatValue();
The following is the complete example.
 Live Demo
public class Demo {
   public static void main(String args[]) {
      String str = "0.8";
      Float floatVal = Float.valueOf(str).floatValue();
      System.out.println("Float: "+floatVal);
   }
}
Float: 0.8
How to get text from each cell of an HTML table using Selenium?

We can get text from each cell of an HTML table with Selenium webdriver.A <table> tag is used to define a table in an html document. A table consists of rows represented by <tr> and columns represented by <td>. The table headers are identified by <th> tag.
Let us consider a table from which we will get text from each cell.
Let us see the html code representation for the above table−
To retrieve the rows count of the table, we will use−
List<WebElement> rows =driver.findElements(By.tagName("tr"));
int rws_cnt= rows.size();
To retrieve the columns count of the table, we will use−
List<WebElement> cols =driver.findElements(By.tagName("td"));
int cols_cnt= cols.size();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class TableCellValue{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
         WebDriver driver = new ChromeDriver();
         String u="https://sqengineer.com/practice-sites/practice-tables-selenium/";
         driver.get(u);
         driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
         // identify table
         WebElement t = driver.findElement(By.xpath("//*[@id='table1']/tbody"));
         // count rows with size() method
         List<WebElement> rws = t.findElements(By.tagName("tr"));
         int rws_cnt = rws.size();
         //iterate rows of table
         for (int i = 0;i < rws_cnt; i++) {
         // count columns with size() method
         List<WebElement> cols = rws.get(i).findElements(By.tagName("td"));
         int cols_cnt = cols.size();
         //iterate cols of table
         for (int j = 0;j < cols_cnt; j++) {
         // get cell text with getText()
         String c = cols.get(j).getText();
      System.out.println("The cell value is: " + c);
   }
}
      driver.quit();
   }
}