code-rag-bench/online-tutorials huggingface dataset:
Can interfaces have Static methods in Java?

An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation.
Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.
In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface.
 Live Demo
interface MyInterface{
   public void demo();
   public static void display() {
      System.out.println("This is a static method");
   }
}
public class InterfaceExample{
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.demo();
      MyInterface.display();
   }
}
This is the implementation of the demo method
This is a static method
MongoEngine - Document Inheritance

It is possible to define an inherited class of any user defined Document class. The inherited class may add extra fields if required. However, since such as a class is not a direct subclass of Document class, it will not create a new collection, instead its objects are stored in a collection used by its parent class. In the parent class, meta attribute ‘allow_inheritance the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection.
In the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection.
from mongoengine import *
con=connect('newdb')
class employee (Document):
name=StringField(required=True)
branch=StringField()
meta={'allow_inheritance':True}
class salary(employee):
dept=StringField()
sal=IntField()
e1=employee(name='Bharat', branch='Chennai').save()
s1=salary(name='Deep', branch='Hyderabad', dept='Accounts', sal=25000).save()
We can verify that two documents are stored in employee collection as follows −
{
"_id":{"$oid":"5ebc34f44baa3752530b278a"},
"_cls":"employee",
"name":"Bharat",
"branch":"Chennai"
}
{
"_id":{"$oid":"5ebc34f44baa3752530b278b"},
"_cls":"employee.salary",
"name":"Deep",
"branch":"Hyderabad",
"dept":"Accounts",
"sal":{"$numberInt":"25000"}
}
Note that, in order to identify the respective Document class, MongoEngine adds a “_cls” field and sets its value as "employee" and "employee.salary".
If you want to provide extra functionality to a group of Document classes, but without overhead of inheritance, you can first create an abstract class and then derive one or more classes from the same. To make a class abstract, meta attribute ‘abstract’ is set to True.
from mongoengine import *
con=connect('newdb')

class shape (Document):
   meta={'abstract':True}
   def area(self):
      pass

class rectangle(shape):
   width=IntField()
   height=IntField()
   def area(self):
      return self.width*self.height

r1=rectangle(width=20, height=30).save()
 Print
 Add Notes
 Bookmark this page
Conversion of four-digit hex to ASCII in 8051

We have already seen how to convert Hexadecimal digit to its ASCII equivalent. In this section, we will see how to convert two-byte (4-digit) Hexadecimal number to ASCII. Each nibble of these numbers is converted to its ASCII value.
We are using one subroutine to convert a hexadecimal digit to ASCII. In this program, we are calling the subroutine multiple times.
In the memory, we are storing 2-byte Hexadecimal number at location 20H and 21H. After converted ASCII values are stored at location 30H to 33H.
The hexadecimal number is 2FA9H. The ASCII equivalent is 32 46 41 39.
        MOVR0,#20H;set source address 20H to R0
        MOVR1,#30H;Set destination address 30H to R1
        MOVR5,#02H;Set the counter as 2 for 2-bytes

LOOP:   MOVA,@R0; Get the first byte from location 20H
        MOVR4,A; Store the content of A to R4
        SWAPA; Swap Nibbles of A
        ANLA,#0FH; Mask upper nibble of A
        ACALL HEX2ASC; Call subroutine to convert HEX to ASCII
        MOV@R1,B; Store the ASCII to destination
        INCR1; Increment the dest address

        MOVA,R4; Take the original number again
        ANLA,#0FH; Mask upper nibble of A
        ACALL HEX2ASC ; Call subroutine to convert HEX to ASCII
        MOV@R1,B; Store the ASCII to destination
        INCR1; Increment the destination address

        INCR0; Increase R0 for next source address
        DJNZR5,LOOP ; Decrease the byte count, and iterate
HALT:   SJMP HALT ;Stop the program
;This is a subroutine to convert Hex to ASCII. It takes A and B registers. A is holding the input, and B is for output

HEX2ASC:    MOVR2,A; Store the content of A into R2

CLRC;Clear the Carry Flag
SUBBA,#0AH;Subtract 0AH from A
JCNUM ;When carry is present, A is numeric
ADDA,#41H;Add41H for Alphabet
SJMP STORE ;Jumpto store the value
NUM: MOVA,R2;Copy R2 to A
ADDA,#30H;Add 30H with A to get ASCII
STORE: MOVB,A;Store A content to B
RET
In this program, we are taking the number into the accumulator. Then to get the hexadecimal digits individually, we will apply masking logic. 
Here the HEX2 ASC subroutine is using the register A and B. A is acting like the input argument and B as output.
SQL | BETWEEN & IN Operator - GeeksforGeeks

11 Jan, 2022
BETWEEN
The SQL BETWEEN condition allows you to easily test if an expression is within a range of values (inclusive). The values can be text, date, or numbers. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement. The SQL BETWEEN Condition will return the records where expression is within the range of value1 and value2. 
Syntax:  
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Examples: Consider the following Employee Table,  
 
Queries
 
Using BETWEEN with Numeric Values: List all the Employee Fname, Lname who is having salary between 30000 and 45000.  
SELECT Fname, Lname
FROM Employee
WHERE Salary
BETWEEN 30000 AND 45000;
Output:  
Using BETWEEN with Date Values: Find all the Employee having Date of Birth Between 01-01-1985 and 12-12-1990.  
SELECT Fname, Lname
FROM Employee
where DOB
BETWEEN '1985-01-01' AND '1990-12-30';
Output:  
Using NOT operator with BETWEEN Find all the Employee name whose salary is not in the range of 30000 and 45000.  
SELECT Fname, Lname
FROM Employee
WHERE Salary
NOT BETWEEN 30000 AND 45000;
Output:  
 
IN
IN operator allows you to easily test if the expression matches any value in the list of values. It is used to remove the need of multiple OR condition in SELECT, INSERT, UPDATE or DELETE. You can also use NOT IN to exclude the rows in your list. We should note that any kind of duplicate entry will be retained. Syntax:  
SELECT column_name(s)
FROM table_name
WHERE column_name IN (list_of_values);
 
Queries
 
Find the Fname, Lname of the Employees who have Salary equal to 30000, 40000 or 25000.  
SELECT Fname, Lname
FROM Employee
WHERE Salary IN (30000, 40000, 25000);
Output:  
Find the Fname, Lname of all the Employee who have Salary not equal to 25000 or 30000.
SELECT Fname, Lname
FROM Employee
WHERE Salary NOT IN (25000, 30000);
Output:  
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
parthbanathia
rkbhola5
SQL-Clauses-Operators
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction of ER Model
Introduction of B-Tree
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
How to find Nth highest salary from a table
SQL | ALTER (RENAME)
SQL Trigger | Student Database
SQL | Views
Difference between DDL and DML in DBMS
How to display multiple lines of text in Tkinter Label?

Tkinter Label widgets are created by defining the Label(parent, **options) constructor in the program. We use the Label widget to display Text or Images in any application. If we want to display a text, we have to assign a value to the text attribute in the constructor. You can also add multiple lines of text in the label widget by using \n next line attribute. It will separate the current text to the next line in the Label widget.
# Import the tkinter library
from tkinter import *

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

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

# Add a label widget
label= Label(win, text= "Hello There!\n How are you?", font= ('Aerial', 17))
label.pack()

win.mainloop()
Executing the above code will display a multiline Label Widget.
Flutter – Magic 8 Ball App

15 Jan, 2021
We will be building a Magic 8 Ball app that will give you the answers to all fun tricky questions (basically it is a fun game app that will change its state of image Flatbutton using Stateful widgets). For this, we will use Stateless and Stateful Flutter widgets, a Flatbutton. 
We will be using VS Code IDE for this project, you can also use Android Studio or any other IDE. Now, First, create the Flutter project with the initial steps and follow the below steps:
Step 1: Create an images folder in the project directory and add the required images.
Note: The images used in the article can be download images from here if you want to follow along.
Step 2: Now, include the images in pubspec.yaml file to use them in the app.
Note: Use proper indentation, otherwise your images will not be included.
Step 3: Now, add the following code in main.dart file:
Dart
// importing flutter and dart packagesimport 'package:flutter/material.dart';import 'dart:math';  // Creates a Material Appvoid main() => runApp(      MaterialApp(        home: BallPage(),      ),    );  // Creates a Scaffold with// appbar using Stateless widget class BallPage extends StatelessWidget {  @override  Widget build(BuildContext context) {    return Scaffold(      backgroundColor: Colors.green[100],      appBar: AppBar(        backgroundColor: Colors.green[600],        title: Text('GeeksforGeeks'),      ),      body: Ball(),    );  }}  // Creates a Stateful widget class Ball extends StatefulWidget {  Ball({Key key}) : super(key: key);    @override  _BallState createState() => _BallState();}  class _BallState extends State<Ball> {  int ballNumber = 1;      @override      // Returns app with centered image Flatbutton    Widget build(BuildContext context) {    return Center(      child: FlatButton(        onPressed: () {          setState(() {                          // Random.nextInt(n) returns random            // integer from 0 to n-1            ballNumber = Random().nextInt(5) + 1;          });        },                  // Adding images        child: Image.asset('images/ball$ballNumber.png'),      ),    );  }}
Output: 
android
Flutter
Technical Scripter 2020
Dart
Flutter
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Listview.builder in Flutter
Flutter - Custom Bottom Navigation Bar
Splash Screen in Flutter
Flutter - Asset Image
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - Stack Widget
Flutter - Search Bar
Why to use char[] array over a string for storing passwords in Java?

20 Jun, 2022
1. Strings are immutable:  Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in the String pool for re-usability there are high chances that it will remain in memory for long duration, which is a security threat. Strings are immutable and there is no way that the content of Strings can be changed because any change will produce new String. Within an array, the data can be wiped explicitly after its work is completed. The array can be overwritten and the password won’t be present anywhere in the system, even before garbage collection.
2. Security: Any one who has access to memory dump can find the password in clear text and that’s another reason to use encrypted password than plain text.  So Storing password in character array clearly mitigates security risk of stealing password. 
3. Log file safety: With an array, one can explicitly wipe the data , overwrite the array and the password won’t be present anywhere in the system. With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.
Java
//Java program to illustrate preferring char[] arrays//over strings for passwords in Javapublic class PasswordPreference{      public static void main(String[] args)    {          String strPwd = "password";        char[] charPwd = new char[] {'p','a','s','s','w','o','r','d'};                 System.out.println("String password: " + strPwd );        System.out.println("Character password: " + charPwd );    }}
Output: 
String password: password
Character password: [C@15db9742
4. Java Recommendation: Java has methods like JPasswordField of javax.swing as the method public String getText() which returns String is Deprecated from Java 2 and is replaced by public char[] getPassword() which returns Char Array.
This article is contributed by Kanika Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
sagar0719kumar
kashishsoda
ankur035
Java-Array-Programs
Java-String-Programs
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use bcrypt for hashing passwords in PHP?

04 Jul, 2019
Everyone knows and understands that storing the password in a clear text in the database is a quite rude thing and not secure. Yet, several do it because it makes an internet site quite easy for password recovery or testing.The bcrypt is a password hashing technique used to build password security. It is used to protect the password from hacking attacks because of the password is stored in bcrypted format.
The password_hash() function in PHP is an inbuilt function which is used to create a new password hash. It uses a strong & robust hashing algorithm. The password_hash() function is very much compatible with the crypt() function. Therefore, password hashes created by crypt() may be used with password_hash() and vice-versa. The functions password_verify() and password_hash() just the wrappers around the function crypt(), and they make it much easier to use it accurately.
Syntax:
string password_hash( $password, $algo, $options )
The following algorithms are currently supported by password_hash() function:
PASSWORD_DEFAULT
PASSWORD_BCRYPT
PASSWORD_ARGON2I
PASSWORD_ARGON2ID
Parameters: This function accepts three parameters as mentioned above and described below:
password: It stores the password of the user.
algo: It is the password algorithm constant that is used continuously while denoting the algorithm which is to be used when the hashing of password takes place.
options: It is an associative array, which contains the options. If this is removed and doesn’t include, a random salt is going to be used, and the utilization of a default cost will happen.
Return Value: It returns the hashed password on success or False on failure.
Example:
Input : echo password_hash("GFG@123", PASSWORD_DEFAULT);
Output : $2y$10$.vGA19Jh8YrwSJFDodbfoHJIOFH)DfhuofGv3Fykk1a

Below programs illustrate the passwor_hash() function in PHP:
Program 1:
<?php  echo password_hash("GFG@123", PASSWORD_DEFAULT);?>
$2y$10$Z166W1fBdsLcXPVQVfPw/uRq1ueWMA6sLt9bmdUFz9AmOGLdM393G

Program 2:
<?php  $options = [    'cost' => 12,];  echo password_hash("GFG@123", PASSWORD_BCRYPT, $options);?>
$2y$12$jgzGJmLsUHGNjmDK98MbWe82e3CIJZuflAj6lE1I.dlyhSVfz42oq

Program 3:
<?php  $timeTarget = 0.069; // 69 milliseconds   $cost = 8;do {    $cost++;    $start = microtime(true);    password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);    $end = microtime(true);} while (($end - $start) < $timeTarget);  echo "The appropriate cost is: " . $cost;?>
The appropriate cost is: 10

Program 4:
<?phpecho 'Argon2i hash: ' . password_hash('GFG@123', PASSWORD_ARGON2I);?>
Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YUNvTkJBT2dEejQuUVQvRQ$+96jm/eISqZ7+P9n0DrsBf25piwfnLRy2Yy1VYmb9iI

Reference: https://www.php.net/manual/en/function.password-hash.php
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numbers in a list within a given range

30 Jun, 2022
Given a list, print the number of numbers in the given range.  
Examples: 
Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80
Output : 6

Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40
Output : 4 
 
Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter. At the end of traversal, the value of the counter will be the answer for the number of numbers in specified range.Below is the Python implementation of the above approach
Python
# Python program to count the# number of numbers in a given range# using traversal and multiple line code def count(list1, l, r):    c = 0    # traverse in the list1    for x in list1:        # condition check        if x>= l and x<= r:            c+= 1    return c     # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print count(list1, l, r)
Output:  
6
Single Line Approach:We can write a single line for traversal and checking condition together:  
x for x in list1 if l <= x <= r
The return value(true) of the condition check is stored in a list, and at the end the length of the list returns the answer.Below is the Python implementation of the above approach  
Python
# Python program to count the# number of numbers in a given range def count(list1, l, r):         # x for x in list1 is same as traversal in the list    # the if condition checks for the number of numbers in the range    # l to r    # the return is stored in a list    # whose length is the answer    return len(list(x for x in list1 if l <= x <= r)) # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print count(list1, l, r)
Output: 
6 
Approach#3 : Using sum We can use sum in this  problem. We use list comprehension to iterate over the list and check number is in range or not if it is present comparison will have 1 as have else 0 as value. Sum function return the sum of total of parameters.
Python3
# Python program to count the# number of numbers in a given range def count(list1, l, r):         # Traversing the list with on line for loop    # check if number is in range of not    return sum( l <= x <= r for x in list1) # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print( count( list1, l, r ) )
Output:
6
gulshankumarar231
satyam00so
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
GCD of two numbers in PL/SQL

12 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given two numbers and task is to find the GCD (Greatest Common Divisor) or HCF (Highest Common Factor) value of the numbers.Examples:
Input:  num1 = 4, num2 = 6
Output: gcd of (num1, num2) = 2

Input: num1 = 8, num2 = 48
Output: gcd of (num1, num2) = 8

Approach is to take two numbers and find their GCD value using Euclidean algorithm.
Below is the required implementation:
DECLARE       -- declare variable num1, num2 and t     -- and these three variables datatype are integer      num1 INTEGER;     num2 INTEGER;     t    INTEGER; BEGIN     num1 := 8;       num2 := 48;       WHILE MOD(num2, num1) != 0 LOOP         t := MOD(num2, num1);           num2 := num1;           num1 := t;     END LOOP;       dbms_output.Put_line('GCD of '                          ||num1                          ||' and '                          ||num2                          ||' is '                          ||num1); END;   -- Program End 
Output :
GCD of 8 and 48 is 8

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL Correlated Subqueries
MySQL | Regular expressions (Regexp)
Parameterless Method in Scala

12 Jun, 2019
Prerequisites – Scala | Functions
A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle.
Example:
// Scala program to illustrate// Parameterless method invocationclass GeeksforGeeks(name: String, ar: Int){    // A parameterless method    def author = println(name)    def article = println(ar)          // An empty-parenthesis method    def printInformation() =     {        println("User -> " + name + ", Articles -> " + ar)    }}  // Creating object object Main {     // Main method    def main(args: Array[String])     {                   // Creating object of Class 'Geeksforgeeks'        val GFG = new GeeksforGeeks("John", 50)        GFG.author     // calling method without parenthesis    } } 
Output:
John
There are generally two conventions for using parameter less method. One is when there are not any parameters. Second one is when method does not change the mutable state. One must avoid the invocations of parameterless methods which look like field selections by defining methods that have side-effects with parenthesis.An example of calling a parameterless method with a parenthesis giving a Compilation error.
Example:
// Scala program to illustrate// Parameterless method invocationclass GeeksforGeeks(name: String, ar: Int){    // A parameterless method    def author = println(name)    def article = println(ar)          // An empty-parenthesis method    def printInformation() =     {        println("User -> " + name + ", Articles -> " + ar)    }}  // Creating objectobject Main {     // Main method    def main(args: Array[String])     {                   // Creating object of Class 'Geeksforgeeks'        val GFG = new GeeksforGeeks("John", 50)        GFG.author()     //calling method without parenthesis    } } 
Output:
prog.scala:23: error: Unit does not take parametersGFG.author() //calling method without parenthesis^one error found
Note: An empty parenthesis method can be called without parenthesis but it is always recommended and accepted as convention to call empty-paren methods with parenthesis.
Picked
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Scala List filter() method with example
Class and Object in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Map
Scala Lists
Scala | Arrays
Operators in Scala
Scala Constructors
Enumeration in Scala
Count number of edges in an undirected graph in C++

Given the task is to count the number of edges in an undirected graph. An undirected graph is a set of vertices which are connected together to form a graph, whose all the edges are bidirectional. Undirected graphs can travel in any direction from one node to another connected node.
Below is a visual representation of the undirected graph.
Now, according to the problem we have to find the number of edges in the undirected graph.
Edges in a graph are the lines to which two vertices are joined.
Input −
insert(graph_list, 0, 1);
insert(graph_list, 0, 2);
insert(graph_list, 1, 2);
insert(graph_list, 1, 4);
insert(graph_list, 2, 4);
insert(graph_list, 2, 3);
insert(graph_list, 3, 4);
Output −
count of edges are: 7
Initialise a list to store all the vertices of the graph’s list and insert the values accordingly.
Initialise a list to store all the vertices of the graph’s list and insert the values accordingly.
In function count_edges, declare a variable count=0 which is to return the count of the edges.
In function count_edges, declare a variable count=0 which is to return the count of the edges.
Traverse the list using a loop until we reach the last vertice and add the value of count with graph_list[i].size() and store it back to the count variable.
Traverse the list using a loop until we reach the last vertice and add the value of count with graph_list[i].size() and store it back to the count variable.
After we reach the last vertice, divide the value of count by two, and print the result.
After we reach the last vertice, divide the value of count by two, and print the result.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//function to insert vertices
void insert(list<int> graph_list[], int u, int v){
   graph_list[u].push_back(v);
   graph_list[v].push_back(u);
}
//function to count the total number of edges
void count_edges(list<int> graph_list[], int v){
   int count=0;
   //traverse the loop till the vertice is found
   for (int i = 0 ; i < v ; i++){
      count += graph_list[i].size();
   }
   count = count/2;
   cout<<"count of edges are: "<<count;
}
int main(int argc, char* argv[]){
   //creating 5 vertices in a graph
   int vertices = 5;
   //declare list to create a graph and pass the vertices
   list<int> graph_list[vertices];
   //call insert function passing the list variable, vertice, linked vertice
   insert(graph_list, 0, 1);
   insert(graph_list, 0, 2);
   insert(graph_list, 1, 2);
   insert(graph_list, 1, 4);
   insert(graph_list, 2, 4);
   insert(graph_list, 2, 3);
   insert(graph_list, 3, 4);
   //calling count function that will count the edges
   count_edges(graph_list, vertices);
   return 0 ;
}
If we run the above code we will get the following output −
count of edges are: 7
How to select part of a Timestamp in a MySQL Query?

To select part of a timestamp in a query, you need to use YEAR() function. The syntax is as follows in MySQL.
select YEAR(yourTimestampColumnName) as anyAliasName from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table SelectPartOfTimestampDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ShippingTime TIMESTAMP
   -> );
Query OK, 0 rows affected (1.11 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(now());
Query OK, 1 row affected (0.20 sec)
mysql> insert into SelectPartOfTimestampDemo(ShippingTime)
values(date_add(now(),interval -2 year));
Query OK, 1 row affected (0.17 sec)
mysql> insert into SelectPartOfTimestampDemo(ShippingTime)
values(date_add(now(),interval -3 year));
Query OK, 1 row affected (0.18 sec)
mysql> insert into SelectPartOfTimestampDemo(ShippingTime)
values(date_add(now(),interval -1 year));
Query OK, 1 row affected (0.18 sec)
mysql> insert into SelectPartOfTimestampDemo(ShippingTime)
values(date_add(now(),interval 1 year));
Query OK, 1 row affected (0.16 sec)
mysql> insert into SelectPartOfTimestampDemo(ShippingTime)
values(date_add(now(),interval 2 year));
Query OK, 1 row affected (0.48 sec)
mysql> insert into SelectPartOfTimestampDemo(ShippingTime)
values(date_add(now(),interval 3 year));
Query OK, 1 row affected (0.10 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from SelectPartOfTimestampDemo;
The following is the output −
+----+---------------------+
| Id | ShippingTime        |
+----+---------------------+
|  1 | 2019-02-08 15:03:27 |
|  2 | 2017-02-08 15:03:50 |
|  3 | 2016-02-08 15:04:03 |
|  4 | 2018-02-08 15:04:06 |
|  5 | 2020-02-08 15:04:10 |
|  6 | 2021-02-08 15:04:24 |
|  7 | 2022-02-08 15:04:30 |
+----+---------------------+
7 rows in set (0.00 sec)
Here is the query to select part of a timestamp using YEAR() function −
mysql> select YEAR(ShippingTime) as PartOfTimeStamp from SelectPartOfTimestampDemo;
The following is the output −
+-----------------+
| PartOfTimeStamp |
+-----------------+
|            2019 |
|            2017 |
|            2016 |
|            2018 |
|            2020 |
|            2021 |
|            2022 |
+-----------------+
7 rows in set (0.00 sec)
How to select first and last row record using LIMIT in MySQL?

Let us first create a table. The query to create a table is as follows
mysql> create table FirstAndLastDataDemo
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20),
   -> EmployeeAge int
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command. The query is as follows
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23);
Query OK, 1 row affected (0.15 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13);
Query OK, 1 row affected (0.11 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24);
Query OK, 1 row affected (0.14 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14);
Query OK, 1 row affected (0.18 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31);
Query OK, 1 row affected (0.10 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)
values('James',18);
Query OK, 1 row affected (0.16 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)
values('Maxwell',28);
Query OK, 1 row affected (0.17 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27);
Query OK, 1 row affected (0.12 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using a select statement.
mysql> select *from FirstAndLastDataDemo;
The following is the output
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
| 1          | John         | 23          |
| 2          | Bob          | 13          |
| 3          | Larry        | 24          |
| 4          | Sam          | 14          |
| 5          | Mike         | 31          |
| 6          | James        | 18          |
| 7          | Maxwell      | 28          |
| 8          | David        | 27          |
| 9          | Chris        | 22          |
+------------+--------------+-------------+
9 rows in set (0.00 sec)
To get first row and last row record using LIMIT, the following is the query
mysql> (SELECT *from FirstAndLastDataDemo LIMIT 1)
   -> UNION
   -> (SELECT *from FirstAndLastDataDemo LIMIT 8,1);
The following is the output displaying the first and last row record
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
| 1          | John         | 23          |
| 9          | Chris        | 22          |
+------------+--------------+-------------+
2 rows in set (0.00 sec)
Delegation vs Inheritance in C#

A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.
To declare a delegate.
delegate <return type> <delegate-name> <parameter list>
Delegation has run-time flexibility i.e. you can easily change it at runtime. The instance you create in Delegation is of a known class.
Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
This is how we create a base and derived class in Inheritance.
<access-specifier> class <base_class> {
   ...
}
class <derived_class> : <base_class> {
   ...
}
Adding Noise to a Numeric Vector in R Programming - jitter() Function - GeeksforGeeks

19 Jun, 2020
In R programming, jittering means adding small amount of random noise to a numeric vector object. In this article, we’ll learn to use jitter() function and create a plot to visualize them.
Syntax: jitter(x, factor)
Parameters:x: represents numeric vectorfactor: represents numeric value for factor specification
Example 1:
# Define numeric vectorsx <- round(runif(1000, 1, 10))y <- x + rnorm(1000, mean = 0, sd = 5)  # output to be present as PNG file png(file="withoutJitter.png")  # Plotting without jitter functionplot(x, y, xlim = c(0, 11),     main = "Without Jitter Function")  # saving the file dev.off()  x_j <- jitter(x)  # output to be present as PNG file png(file="withJitter.png")  # Plotting with jitter functionplot(x_j, y, xlim = c(0, 11),     main = "With Jitter Function")  # saving the file dev.off()
Output:
Example 2: With large factor value
# Define numeric vectorsx <- round(runif(1000, 1, 10))y <- x + rnorm(1000, mean = 0, sd = 5)  # output to be present as PNG file png(file="withoutJitterFactor.png")  # Plotting without jitter functionplot(x, y, xlim = c(0, 11),     main = "Without Jitter Function")  # saving the file dev.off()  x_j <- jitter(x, factor = 2)  # output to be present as PNG file png(file="withJitterFactor.png")  # Plotting with jitter functionplot(x_j, y, xlim = c(0, 11),     main = "With Jitter Function and Large Factor")  # saving the file dev.off()
Output:
R Factor-Function
R Vector-Function
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
Time Series Analysis in R
Program to find the highest altitude of a point in Python

Suppose there is a biker who is going on a road trip. There are n different points in his road trip at different altitudes. The biker starts his trip from point 0 with altitude 0. If we have a sequence called gain with n elements, gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). We have to find the highest altitude of a point.
So, if the input is like gain = [-4,2,6,1,-6], then the output will be 5, because the altitudes are [0,-4,-2,4,5,-1], so the maximum is 5.
To solve this, we will follow these steps −
maximum := 0
maximum := 0
run_alt := 0
run_alt := 0
for each delta in gain, dorun_alt := run_alt + deltamaximum := max of maximum and run_alt
for each delta in gain, do
run_alt := run_alt + delta
run_alt := run_alt + delta
maximum := max of maximum and run_alt
maximum := max of maximum and run_alt
return maximum
return maximum
Let us see the following implementation to get better understanding −
 Live Demo
def solve(gain):
   maximum = 0
   run_alt = 0

   for delta in gain:
      run_alt += delta
      maximum = max(maximum, run_alt)

   return maximum

gain = [-4,2,6,1,-6]
print(solve(gain))
[-4,2,6,1,-6]
5
Program to display hostname and IP address C

In this section we will see how to see the Host name and IP address of the local system in an easier way. We will write a C program to find the host name and IP.
Some of the following functions are used. These functions have a different task. Let us see the functions and their tasks.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void check_host_name(int hostname) { //This function returns host name for local computer
   if (hostname == -1) {
      perror("gethostname");
      exit(1);
   }
}
void check_host_entry(struct hostent * hostentry) { //find host info from host name
   if (hostentry == NULL) {
      perror("gethostbyname");
      exit(1);
   }
}
void IP_formatter(char *IPbuffer) { //convert IP string to dotted decimal format
   if (NULL == IPbuffer) {
      perror("inet_ntoa");
      exit(1);
   }
}
main() {
   char host[256];
   char *IP;
   struct hostent *host_entry;
   int hostname;
   hostname = gethostname(host, sizeof(host)); //find the host name
   check_host_name(hostname);
   host_entry = gethostbyname(host); //find host information
   check_host_entry(host_entry);
   IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); //Convert into IP string
   printf("Current Host Name: %s\n", host);
   printf("Host IP: %s\n", IP);
}
Current Host Name: soumyadeep-VirtualBox
Host IP: 127.0.1.1
Rotate Matrix in Python

Suppose we have one n x n 2D matrix. We have to rotate this matrix 90 degrees clockwise. So if the matrix is like-
Then the output will be
To solve this, we will follow these steps −
Consider temp_mat = [], col := length of matrix – 1
for col in range 0 to length of matrixtemp := []for row in range length of matrix – 1 down to -1add matrix[row, col] in tempadd temp into temp_mat
temp := []
for row in range length of matrix – 1 down to -1add matrix[row, col] in temp
add matrix[row, col] in temp
add temp into temp_mat
for i in range 0 to length of matrixfor j in range 0 to length of matrixmatrix[i, j] := temp_mat[i, j]
for j in range 0 to length of matrixmatrix[i, j] := temp_mat[i, j]
matrix[i, j] := temp_mat[i, j]
Let us see the following implementation to get better understanding −
Live Demo
class Solution(object):
   def rotate(self, matrix):
      temp_matrix = []
      column = len(matrix)-1
      for column in range(len(matrix)):
         temp = []
         for row in range(len(matrix)-1,-1,-1):
            temp.append(matrix[row][column])
         temp_matrix.append(temp)
      for i in range(len(matrix)):
         for j in range(len(matrix)):
            matrix[i][j] = temp_matrix[i][j]
      return matrix

ob1 = Solution()
print(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]]))
[[1,5,7],[9,6,3],[2,1,3]]
[[2, 9, 1], [1, 6, 5], [3, 3, 7]]
Set custom Auto Increment with ZEROFILL in MySQL

Let us first create a table. Here. We have set UserId column with ZEROFILL and AUTO_INCREMENT
mysql> create table DemoTable1831
     (
     UserId int(7) zerofill auto_increment,
     PRIMARY KEY(UserId)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1831 values(101);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1831 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1831 values();
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1831 values();
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1831;
This will produce the following output. All the values have zerofill for UserId field width 7
+---------+
| UserId  |
+---------+
| 0000101 |
| 0000102 |
| 0000103 |
| 0000104 |
+---------+
4 rows in set (0.00 sec)
Differences between == and equals() method in Java

In java both == and equals() method is used to check the equality of two variables or objects.
Following are the important differences between == and equals() method.
public class JavaTester {
   public static void main(String args[]) {
      String s1 = new String("TUTORIALSPOINT");
      String s2 = new String("TUTORIALSPOINT");
      //Reference comparison
      System.out.println(s1 == s2);
      //Content comparison
      System.out.println(s1.equals(s2));
      // integer-type
      System.out.println(10 == 10);
      // char-type
      System.out.println('a' == 'a');
   }
}
false
true
true
true
Python | Get Top N elements from Records

29 Oct, 2019
Sometimes, while working with data, we can have a problem in which we have records and we require to find the highest N scores from it. This kind of application is popular in web development domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sorted() + lambdaThe combination of above functionality can be used to perform this particular task. In this, we just employ sorted function with reverse flag true, and print the top N elements using list slicing.
# Python3 code to demonstrate working of# Get Top N elements from Records# Using sorted() + lambda  # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)]  # Initializing N N = 2  # printing original listprint("The original list is : " + str(test_list))  # Get Top N elements from Records# Using sorted() + lambdares = sorted(test_list, key = lambda x: x[1], reverse = True)[:N]  # printing resultprint("The top N records are : " + str(res))
The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)]
The top N records are : [('Manjeet', 10), ('Nikhil', 8)]

 
Method #2 : Using sorted() + itemgetter()The combination of above functions can also be used to perform this particular task. In this, the task performed by lambda function is performed by itemgetter() is used to get the index in tuple which has to be included in calculations.
# Python3 code to demonstrate working of# Get Top N elements from Records# Using sorted() + itemgetter()from operator import itemgetter  # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)]  # Initializing N N = 2  # printing original listprint("The original list is : " + str(test_list))  # Get Top N elements from Records# Using sorted() + itemgetter()res = sorted(test_list, key = itemgetter(1), reverse = True)[:N]  # printing resultprint("The top N records are : " + str(res))
The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)]
The top N records are : [('Manjeet', 10), ('Nikhil', 8)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Date compareTo() method in Java with examples

07 Nov, 2019
The compareTo() method of Java Date class compares two dates and sort them for order.
Syntax:
public int compareTo(Date anotherDate)

Parameters: The function accepts a single parameter anotherDate which specifies the date to be compared .
Return Value: The function gives three return values specified below:
It returns the value 0 if the argument Date is equal to this Date.
It returns a value less than 0 if this Date is before the Date argument.
It returns a value greater than 0 if this Date is after the Date argument.
Exception: The function throws a single exception that is NullPointerException if anotherDate is null.
Program below demonstrates the above mentioned function:
// Java code to demonstrate// compareTo() function of Date class  import java.util.Date;import java.util.Calendar;public class GfG {    // main method    public static void main(String[] args)    {          // creating a Calendar object        Calendar c = Calendar.getInstance();          // set Month        // MONTH starts with 0 i.e. ( 0 - Jan)        c.set(Calendar.MONTH, 11);          // set Date        c.set(Calendar.DATE, 05);          // set Year        c.set(Calendar.YEAR, 1996);          // creating a date object with specified time.        Date dateOne = c.getTime();          System.out.println("Date 1: "                           + dateOne);          // creating a date of object        // storing the current date        Date currentDate = new Date();          System.out.println("Date 2: "                           + currentDate);          // compares        System.out.println("On Comparison: "                           + currentDate                                 .compareTo(dateOne));    }}
Date 1: Thu Dec 05 08:17:55 UTC 1996
Date 2: Wed Jan 02 08:17:55 UTC 2019
On Comparison: 1

// Java code to demonstrate// compareTo() function of Date class  import java.util.Date;  public class GfG {    // main method    public static void main(String[] args)    {          // creating a date of object        // stospecified datent date        Date currentDate = new Date();          System.out.println("Date 1: " + currentDate);          // specifiedDate is assigned to null.        Date specifiedDate = null;          System.out.println("Date 2: " + specifiedDate);          System.out.println("Passing null as parameter: ");        try {            // throws NullPointerException            System.out.println(currentDate                                   .compareTo(specifiedDate));        }        catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Date 1: Wed Jan 02 08:18:02 UTC 2019
Date 2: null
Passing null as parameter: 
Exception: java.lang.NullPointerException

ManasChhabra2
Java - util package
Java-Functions
Java-util-Date
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
HTML - <doctype> Tag

The HTML <doctype> tag is used for specifying which version of HTML the document is using. This is referred to as the document type declaration (DTD).
NOTE − The <!DOCTYPE> tag does not have an end tag!.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML doctype Tag</title>
   </head>

   <body>
      <p>doctype declaration <doctype> is mentioned at the starting of
         every HTML document.</p>
   </body>
</html>
This will produce the following result −
doctype declaration  is mentioned at the starting of every HTML document.
HTML 4.01 has 3 possible doctypes − HTML 4 Strict, HTML 4 Transitional, and HTML 4 Frameset. Every HTML document you create should have one of these three DTDs.
This document type includes all HTML elements except those that have been deprecated, and those that appear in frameset documents.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
This document type includes all HTML elements including those that have been deprecated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">;
This document type includes all HTML elements in the transitional DTD as well as those in framed document.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"
   "http://www.w3.org/TR/html4/frameset.dtd">
In HTML5 there is only one declaration i.e.