code-rag-bench/online-tutorials huggingface dataset:
Period between() method in Java with Examples

27 Nov, 2018
The between() method of Period class in Java is used to obtain a period consisting of the number of years, months, and days between two given dates (including start date and excluding end date).
This period is obtained as follows:
Remove complete months.
Now, calculate the remaining number of days.
Then, adjust to ensure that both have the same sign.
Now, split the number of months into years and months based on a 12 month year.
Consider a month, if the end day-of-month is greater than or equal to the start day-of-month (Eg.: from 2017-05-12 to 2018-07-18 is one year, two months and six days).
Note: Period obtained from above formula can be a negative, if the end is before the start. The negative sign will be the same in each of year, month and day.
Syntax:
public static Period between(LocalDate startDateInclusive,
                             LocalDate endDateExclusive)

Parameters:
startDateInclusive – The start date is inclusive and must not be null.
endDateExclusive – The end date is exclusive and must not be null.
Return Value: The between() function of period returns the period between the given start and end date.
Below is the implementation of above function:
// Java code to show the period// between given start and end dateimport java.time.LocalDate;import java.time.Period;  public class PeriodClass {      // Function to calculate period between    // start and end date    static void calculatePeriod(LocalDate startDate,                                LocalDate endDate)    {        Period period = Period.between(startDate, endDate);        System.out.println("Period between start and end "                           + "date is : " + period);    }      // Driver Code    public static void main(String[] args)    {        // Start date        LocalDate startDate = LocalDate.parse("2017-02-13");          // End date        LocalDate endDate = LocalDate.parse("2018-08-20");          calculatePeriod(startDate, endDate);    }}
Period between start and end date is : P1Y6M7D

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Period.html#between-java.time.LocalDate-java.time.LocalDate-
Java-Functions
Java-Period
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Fixed-priority pre-emptive scheduling

16 Apr, 2020
Prerequisite – CPU Scheduling in Operating SystemsFixed priority pre-emptive scheduling algorithm is mostly used in real time systems.In this scheduling algorithm the processor make sure that the highest priority task is to be performed first ignoring the other task to be executed.
The process having highest priority is served first.
Decision Mode:Pre-emptive: When a process arrives its priority is compared with the current process’s priority.If the new job have higher priority then the current process, the current process is suspended and new process is started.
Implementation:Sorted FIFO queue is used for this strategy. As the new process is identified it is placed in the queue according to it’s priority.Hence the process having higher priority is considered first as it is placed at higher position.
Example:Let us take the following example having 4 set of processes along with its arrival time and time taken to complete the process.Also the priority of all the process are mentioned.Consider all time values in millisecond and small value of priority means higher priority of process.
Gantt chart:
Initially only P0 is present and it is allowed to run.But when P1 comes, it has higher priority.So, P0 is pre-empted and P1 is allowed to run.This process repeated till all processes complete their execution.
Statistic :
Average Turnaround time:
= (22+12+2+4) / 4    
= 40 / 4
= 10 ms 
Average Waiting time:
= (12+6+0+0) / 4    
= 18 / 4
= 4.5 ms 
Advantages:Priority is considered.Critical process can get even better response.
Disadvantage:Starvation is possible for low priority process.It can be overcome by using technique called “Aging“. Aging gradually increases the priority of the process that wait in the system for long time. Context switch overhead is there.
Picked
Operating Systems
Write From Home
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File Allocation Methods
Memory Management in Operating System
Logical and Physical Address in Operating System
Segmentation in Operating System
Structures of Directory in Operating System
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
CSS | border-left-style Property - GeeksforGeeks

22 Aug, 2021
The CSS border-left-style property is used to set the style of the left border of an element.
Default Value
none
Syntax:  
border-left-style: none| hidden| dotted| dashed| solid| double |
groove| ridge| inset| outset| initial| inherit;
Properties Value: 
 
Return Value: It returns the style of left border of an element. 
Example-1: Showing Dotted Left Border.  
html
<!DOCTYPE html><html>  <head>    <style>        h1 {            border-left-style: dotted;        }                  div {            border-style: solid;            border-left-style: dotted;        }    </style></head>  <body>      <h1>Geeks for Geeks</h1>      <div>        <h3>Dotted Left Border</h3></div>  </body>  </html>
Output:  
Example-2: Showing Double Left Border  
html
<!DOCTYPE html><html>  <head>    <style>        h1 {            border-left-style: double;        }                  div {            border-style: solid;            border-left-style: double;        }    </style></head>  <body>      <h1>Geeks for Geeks</h1>      <div>        <h3>Double Left Border</h3></div>  </body>  </html>
Output:  
Example-3: Showing Solid Left Border  
html
<!DOCTYPE html><html>  <head>    <style>        h1 {            border-left-style: solid;        }                  div {            border-style: solid;            border-left-style: solid;        }    </style></head>  <body>      <h1>Geeks for Geeks</h1>      <div>        <h3>Solid Left Border</h3></div>  </body>  </html>
Output:  
Supported Browsers: The browsers supported by CSS Border Left Style Property are listed below:  
Google Chrome
Firefox
Internet Explorer
Opera
Safari
 
ManasChhabra2
CSS-Properties
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
GeeksforGeeks | A computer science portal for geeks

Events at GeeksforGeeks


Courses at GeeksforGeeks


Write an Article


Java Tutorial


Python Tutorial


Data Structures Tutorial


Coding Practice


Events at GeeksforGeeks


Courses at GeeksforGeeks


Write an Article


Java Tutorial


Python Tutorial


Data Structures Tutorial


Coding Practice

Get Hired With GeeksforGeeks and Win Exciting Rewards!October 30, 2021
October 30, 2021
Master the Coding Interview – Contest Series Based On Real InterviewsOctober 5, 2021
October 5, 2021
Recently Asked Interview Questions in Product Based CompaniesMay 11, 2021
May 11, 2021
Bridge the Gap Between Engineering and Your Dream Job – Complete Interview PreparationMay 1, 2021
May 1, 2021
100 Days of Code – A Complete Guide For Beginners and ExperiencedMay 1, 2021
May 1, 2021
Guest Blogs
Must Do Coding Questions
Company-wise
Practice for cracking any coding
interview
Placements
Complete Interview Preparation With
Doubt Assistance
GATE Computer Science Notes
Machine Learning
Django Tutorial
Computer Science Projects
Amazon SDE Test Series
Company Interview Corner
The C++ Standard Template Library
(STL)
Software Design Patterns
SQL Tutorial
Advanced Data Structures
Pass long parameter to an overloaded method in Java

Method overloading in a class contains multiple methods with the same name but the parameter list of the methods should not be the same. One of these methods can have a long parameter in their parameter list.
A program that demonstrates this is given as follows −
 Live Demo
class PrintValues {
   public void print(int val) {
      System.out.println("The int value is: " + val);
   }
   public void print(long val) {
      System.out.println("The long value is: " + val);
   }
}
public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(15);
      obj.print(8L);
   }
}
The int value is: 15
The long value is: 8
Now let us understand the above program.
The PrintValues class is created with two methods print() in the implementation of method overloading. One of these takes a parameter of type int and the other takes a parameter of type long. A code snippet which demonstrates this is as follows:
class PrintValues {
   public void print(int val) {
      System.out.println("The int value is: " + val);
   }
   public void print(long val) {
      System.out.println("The long value is: " + val);
   }
}
In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters 15 and 8L respectively where the former is an int value and the latter a long value. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(15);
      obj.print(8L);
   }
}
How to increment all the rows of a particular column by 1 in a single MySQL query (ID column +1)?

To increment all the rows of a particular ID column by 1, you need to use UPDATE command and update the table. The syntax of the query is as follows. We have also used ORDER BY here
UPDATE yourTableName SET yourIdColumnName=yourIdColumnName+1 ORDER BY yourIdColumnName DESC;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table IdColumnadd1Demo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
   - > );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.12 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.18 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.17 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.08 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.13 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.25 sec)
mysql> insert into IdColumnadd1Demo values();
Query OK, 1 row affected (0.40 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from IdColumnadd1Demo;
The following is the output
+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
+----+
8 rows in set (0.00 sec)
Here is the query to adjust the MySQL ID column+1
mysql> update IdColumnadd1Demo set Id=Id+1 Order By Id DESC;
Query OK, 8 rows affected (0.18 sec)
Rows matched: 8 Changed: 8 Warnings: 0
Check the table records once again.
The query is as follows
mysql> select *from IdColumnadd1Demo;
The following is the output
+----+
| Id |
+----+
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
8 rows in set (0.00 sec)
JavaScript - Image Map

You can use JavaScript to create client-side image map. Client-side image maps are enabled by the usemap attribute for the <img /> tag and defined by special <map> and <area> extension tags.
The image that is going to form the map is inserted into the page using the <img /> element as normal, except that it carries an extra attribute called usemap. The value of the usemap attribute is the value of the name attribute on the <map> element, which you are about to meet, preceded by a pound or hash sign.
The <map> element actually creates the map for the image and usually follows directly after the <img /> element. It acts as a container for the <area /> elements that actually define the clickable hotspots. The <map> element carries only one attribute, the name attribute, which is the name that identifies the map. This is how the <img /> element knows which <map> element to use.
The <area> element specifies the shape and the coordinates that define the boundaries of each clickable hotspot.
The following code combines imagemaps and JavaScript to produce a message in a text box when the mouse is moved over different parts of an image.
<html>   
   <head>
      <title>Using JavaScript Image Map</title>
      
      <script type = "text/javascript">
         <!--
            function showTutorial(name) {
               document.myform.stage.value = name
            }
         //-->
      </script>
   </head>
   
   <body>
      <form name = "myform">
         <input type = "text" name = "stage" size = "20" />
      </form>
      
      <!-- Create  Mappings -->
      <img src = "/images/usemap.gif" alt = "HTML Map" border = "0" usemap = "#tutorials"/>
      
      <map name = "tutorials">
         <area shape="poly" 
            coords = "74,0,113,29,98,72,52,72,38,27"
            href = "/perl/index.htm" alt = "Perl Tutorial"
            target = "_self" 
            onMouseOver = "showTutorial('perl')" 
            onMouseOut = "showTutorial('')"/>
         
         <area shape = "rect" 
            coords = "22,83,126,125"
            href = "/html/index.htm" alt = "HTML Tutorial" 
            target = "_self" 
            onMouseOver = "showTutorial('html')" 
            onMouseOut = "showTutorial('')"/>
         
         <area shape = "circle" 
            coords = "73,168,32"
            href = "/php/index.htm" alt = "PHP Tutorial"
            target = "_self" 
            onMouseOver = "showTutorial('php')" 
            onMouseOut = "showTutorial('')"/>
      </map>
   </body>
</html>
You can feel the map concept by placing the mouse cursor on the image object.

    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
Change string based on a condition - JavaScript

We are required to write a JavaScript function that takes in a string. The task of our function is to change the string according to the following condition −
If the first letter in the string is a capital letter then we should change the full string to capital letters.
Otherwise, we should change the full string to small letters.
Following is the code −
const str1 = "This is a normal string";
const str2 = "thisIsACamelCasedString";
const changeStringCase = str => {
   let newStr = '';
   const isUpperCase = str[0].charCodeAt(0) >= 65 && str[0].charCodeAt(0) <= 90;
   if(isUpperCase){
      newStr = str.toUpperCase();
   }else{
      newStr = str.toLowerCase();
   };
   return newStr;
};
console.log(changeStringCase(str1));
console.log(changeStringCase(str2));
Following is the output in the console −
THIS IS A NORMAL STRING
thisisacamelcasedstring
Evine - Interactive Web Crawler in Kali Linux - GeeksforGeeks

14 Sep, 2021
Web Crawling is the technique of finding the hidden files and directories from the target server which can consist of some sensitive data about the architecture of the target domain. Manual crawling can be difficult if the scope of the target is vast. So we should approach Automated Crawling. There are various automated crawlers available on the internet. Evine is the tool or crawler developed in the Go programming language, which comes with GUI and CLI versions. Evine may be useful for a wide range of purposes such as metadata and data extraction, data mining, reconnaissance, and testing. Evine tool is available on GitHub, it’s open-source and free-to-use.
Note: Make Sure You have Golang Installed on your System, as this is a Golang-based tool. Click to check the Installation process – Golang Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/saeeddhqan/evine.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd evine
Step 3: You are in the directory of the Evine. Now you have to install the Evine using the following command.
sudo go build
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
./evine -h
Example 1: Crawling
In this example, we will give the URL and click on the tab button and go to the options section, and true all the options that we want to crawl.
We have changed the values from false to true.
We will not see results before entering “all” on the key section but after entering “all” keywords we can see that result.
Example 2: Save Output
In this example, we will save our output or results by pressing “Ctrl+S” as input through the keyboard on the response section, give the file name and exit it by “Ctrl+q“.
We have given the file name as results.txt.
We are displaying the saved results which are saved in the results.txt file.
Example 3: Filters
In this example, we will be getting the exact results by filtrating out our relevant results. We have entered PHP which will return the URLs consisting of PHP.
We have got all the URLs consisting of PHP.
Example 4: Custom Header
In this example, We will be adding our own custom header to the request.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
C++ | References | Question 1 - GeeksforGeeks

28 Jun, 2021
What is the return value of f(p, p) if the value of p is initialized to 5 before the call? Note that the first parameter is passed by reference, whereas the second parameter is passed by value.
int f(int &x, int c) {
   c  = c - 1;
   if (c == 0) return 1;
   x = x + 1;
   return f(x, c) * x;
} 
(A) 3024(B) 6561(C) 55440(D) 161051Answer: (B)Explanation: Since c is passed by value and x is passed by reference, all functions will have same copy of x, but different copies of c.
f(5, 5) = f(x, 4)*x = f(x, 3)*x*x = f(x, 2)*x*x*x = f(x, 1)*x*x*x*x = 1*x*x*x*x = x^4
Since x is incremented in every function call, it becomes 9 after f(x, 2) call. So the value of expression x^4 becomes 9^4 which is 6561.
#include <stdio.h>  int f(int &x, int c){    c  = c - 1;    if (c == 0) return 1;    x = x + 1;    return f(x, c) * x;}int main(){    int p = 5;    printf("%d", f(p, p));}
Quiz of this Question
C++-References
References
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Inheritance | Question 7
C++ | Virtual Functions | Question 12
C++ | Inheritance | Question 1
Neo4j Delete Node - GeeksforGeeks

23 Aug, 2019
In Neo4j to delete a node or relations between nodes you have to use DELETE clause. To delete any node you need DELETE clause with the MATCH statement, the MATCH statement data will find the specific node and whichever node is matched with the statement that node will be vanished. Similar to the CREATE and RETURN statement just it will replace the CREATE with MATCH and RETURN with the DELETE. Below examples will illustrate the approach.
Example: The basic way to delete a node is to find the node and delete the match node, but before you can check the node is that the node you want to delete by using RETURN statement after that you can fire below query. This query will delete the node where label is “GeeksforGeeks” Tag is “A Computer Science Portal” and the type is “Edutech”.
To delete node:$ MATCH (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) 
DELETE aOutput:Deleting multiple nodes:To delete multiple nodes use the DELETE statement and separate the nodes by “, ” coma or you can use multiple time MATCH statement Like the below query.
$ MATCH (a:GeksforGeeks { Tag : "A Computer Science Portal", Type : "Edutech" }) 
DELETE a
Output:
Deleting multiple nodes:To delete multiple nodes use the DELETE statement and separate the nodes by “, ” coma or you can use multiple time MATCH statement Like the below query.
Multiple nodes deleted:$ DELETE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), 
(b:W3School { Tag: "We are the Learner"}) 
MATCH a, bor$ MATCH (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) 
MATCH (b:W3School { Tag: "We are the Learner"}) 
DELETE a, b
Output:Delete all nodes: To delete all the nodes at once is to much short query to fire the below query will delete all the nodes at once.
$ DELETE (a:GeeksforGeeks { Tag: "A Computer Science Portal"}), 
(b:W3School { Tag: "We are the Learner"}) 
MATCH a, b
or
$ MATCH (a:GeeksforGeeks { Tag: "A Computer Science Portal"}) 
MATCH (b:W3School { Tag: "We are the Learner"}) 
DELETE a, b

Output:
Delete all nodes: To delete all the nodes at once is to much short query to fire the below query will delete all the nodes at once.
Delete all nodes:$ MATCH (n) DELETE nOutput:Note: To delete any node or nodes that containing relationship with other nodes will display an error message.My Personal Notes
arrow_drop_upSave
$ MATCH (n) DELETE n
Output:
Note: To delete any node or nodes that containing relationship with other nodes will display an error message.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
CTE in SQL
Introduction of ER Model
SQL | Views
Introduction of DBMS (Database Management System) | Set 1
SQL Interview Questions
Third Normal Form (3NF)
SQL | GROUP BY
Second Normal Form (2NF)
Difference between DELETE, DROP and TRUNCATE
Filter sub documents by sub document in MongoDB?

For this, use aggregate() along with $unwind. Let us create a collection with documents −
> db.demo583.insert([
...    {
...       "details1" : [
...          {
...             "details2" : [
...                {
...                   "isMarried" : true,
...                   "Name" : "Chris"
...                },
...                {
...                   "isMarried" : true,
...                   "Name" : "Bob"
...                }
...             ]
...          },
...          {
...             "details2" : [
...                {
...                   "isMarried" : false,
...                   "Name" : "Chris"
...                },
...                {
...                   "isMarried" : true,
...                   "Name" : "Mike"
...                }
...             ]
...          }
...       ]
...    }
... ]);
BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 1,
   "nUpserted" : 0,
   "nMatched" : 0,
   "nModified" : 0,
   "nRemoved" : 0,
   "upserted" : [ ]
})
Display all documents from a collection with the help of find() method −
> db.demo583.find();
This will produce the following output −
{ "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"), "details1" : [
   { "details2" : [
      { "isMarried" : true, "Name" : "Chris" },
      { "isMarried" : true, "Name" : "Bob" }
   ] },
   { "details2" : [
      { "isMarried" : false, "Name" : "Chris" },
      { "isMarried" : true, "Name" : "Mike" }
   ] }
] }
Following is the query to filter sub documents by sub-document −
> var q= [
...    {
...       "$match": {
...          "details1.details2.isMarried": true,
...          "details1.details2.Name": "Chris"
...       }
...    },
...    {
...       "$unwind": "$details1"
...    },
...    {
...       "$unwind": "$details1.details2"
...    },
...    {
...       "$match": {
...          "details1.details2.isMarried": true,
...          "details1.details2.Name": "Chris"
...       }
...    }
... ];
> db.demo583.aggregate(q).pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e91d3c4fd2d90c177b5bcc1"),
   "details1" : {
      "details2" : {
         "isMarried" : true,
         "Name" : "Chris"
      }
   }
}
C++ program to find sum of digits of a number until sum becomes single digit

In this article, we will be discussing a program to find the sum of digits of a number until the sum itself becomes a single digit and cannot be done summation of further.
For example, take the case of a number 14520. Adding the digits of this number we get 1 + 4 + 5 + 2 + 0 = 12. Since this is not a single digit number, we would further add the digits of the number received. Adding them we get, 1 + 2 = 3.
Now, 3 is the final answer because it is a single digit number itself and its digits cannot be added further.
To solve this, we would use the approach that the sum of digits of a number divisible by 9 is equal to 9 only. For the numbers that are not divisible by 9, we can divide them by 9 so as to get the remaining digit which would be the final sum of the given number.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
//function to check the divisibility by 9
int sum_digits(int n) {
   if (n == 0)
      return 0;
   else if (n%9 == 0)
      return 9;
   else
      return (n%9);
}
int main() {
   int x = 14520;
   cout<<sum_digits(x)<<endl;
   return 0;
}
3
Java Examples - Retrieve Contents from many Tables

How to join contents of more than one table & display?
Following example uses inner join sql command to combine data from two tables. To display the contents of the table getString() method of resultset is used.
import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception {
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection (
         "jdbc:derby://localhost:1527/testDb","username", "password");
      
      Statement stmt = con.createStatement();
      String query ="SELECT fname,lname,isbn from author inner join books on author.AUTHORID = books.AUTHORID";
      ResultSet rs = stmt.executeQuery(query);
      System.out.println("Fname  Lname   ISBN");
      
      while (rs.next()) {
         String fname = rs.getString("fname");
         String lname = rs.getString("lname");
         int isbn = rs.getInt("isbn");
         System.out.println(fname + "  " + lname+"   "+isbn);
      }
      System.out.println();
      System.out.println();
   }
}
The above code sample will produce the following result. The result may vary.
Fname  Lname   ISBN
john  grisham   123
jeffry  archer   113
jeffry  archer   112
jeffry  archer   122

 Print
 Add Notes
 Bookmark this page
How to get the entire HTML document as a string in JavaScript ?

13 Apr, 2021
Given an HTML document, the task is to get the entire document as a string using JavaScript. Here few methods are discussed:  
getElementsByTagName() Method This method returns a set of all elements in the document with the defined tag name, as a NodeList object. This object represents a collection of nodes, Which are accessed by index numbers. The index starts at 0. Syntax:  
document.getElementsByTagName(tagname)
Parameters: tagname: This parameter is required. It specifies the tagname of the elements to get.  
tagname: This parameter is required. It specifies the tagname of the elements to get.  
HTML DOM innerHTML Property This property set/return the HTML content (inner HTML) of an element. Syntax: Return the innerHTML property:  
Return the innerHTML property:  
HTMLElementObject.innerHTML
Set the innerHTML property:  
HTMLElementObject.innerHTML = text
text: It specifies the HTML content of an element.  
Example 1: This example gets the whole document as string using document.documentElement.innerHTML.  
html
<!DOCTYPE html> <html> <head>    <title>        JavaScript | Get the entire document HTML as a string.    </title></head> <body style="text-align:center;" id="body">    <h1 style="color:green;">             GeeksforGeeks         </h1>    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">    </p>     <button onclick="GFG_Fun(); ">        click here    </button>    <script>        var up = document.getElementById('GFG_UP');        up.innerHTML = 'Click on the button to convert whole document to string';         function GFG_Fun() {            var string = document.documentElement.innerHTML;            alert(string);        }    </script></body> </html>
Output:  
Before clicking the button:  
After clicking the button:  
Example 2: This example gets the whole document by first selecting the elements with tagname ‘HTML’ and selecting the first element by indexing using document.getElementsByTagName(‘html’)[0].innerHTML. 
html
<!DOCTYPE html> <html> <head>    <title>        JavaScript | Get the entire document HTML as a string.    </title></head> <body style="text-align:center;" id="body">    <h1 style="color:green;">             GeeksforGeeks         </h1>    <p id="GFG_UP" style="font-size: 15px; font-weight: bold;">    </p>     <button onclick="GFG_Fun(); ">        click here    </button>    <script>        var up = document.getElementById('GFG_UP');        up.innerHTML = 'Click on the button to convert whole document to string';         function GFG_Fun() {            var string = document.getElementsByTagName('html')[0].innerHTML;            alert(string);        }    </script></body> </html>
Output:  
Before clicking the button:  
After clicking the button:  
 
Supported Browsers:
Google Chrome
Mozilla Firefox
Internet Explorer
Safari
Opera
 
arorakashish0911
HTML-DOM
JavaScript-Misc
javascript-string
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Number of ways in which N can be represented as the sum of two positive integers

19 Mar, 2022
Given a number N, the task is to find the number of unique ways in which N can be represented as a sum of two positive integers.Examples:  
Input: N = 7 Output: 3 (1 + 6), (2 + 5) and (3 + 4).Input: N = 200 Output: 100  
 
Approach: The number of ways in which the number can be expressed as the sum of two positive integers are 1 + (N – 1), 2 + (N – 2), ..., (N – 1) + 1 and (N – 2) + 2. There are N – 1 terms in the series and they appear in identical pairs i.e. (X + Y, Y + X). So the required count will be N / 2.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the number of// distinct ways to represent n// as the sum of two integersint ways(int n){    return n / 2;} // Driver codeint main(){    int n = 2;     cout << ways(n);     return 0;}
// Java implementation of the approach class GFG{         // Function to return the number of    // distinct ways to represent n    // as the sum of two integers    static int ways(int n)    {        return n / 2;    }         // Driver code    public static void main(String args[])    {        int n = 2;             System.out.println(ways(n));    }} // This code is contributed by AnkitRai01
# Python3 implementation of the approach # Function to return the number of# distinct ways to represent n# as the sum of two integersdef ways(n):    return n // 2 # Driver coden = 2 print(ways(n)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{     // Function to return the number of// distinct ways to represent n// as the sum of two integersstatic int ways(int n){    return n / 2;} // Driver codepublic static void Main(){    int n = 2;     Console.WriteLine(ways(n));}} // This code is contributed by Nidhi_Biet
<script>  // Javascript implementation of the approach // Function to return the number of// distinct ways to represent n// as the sum of two integersfunction ways(n){    return parseInt(n / 2);} // Driver codevar n = 2;document.write(ways(n)); // This code is contributed by noob2000.</script>
1
 
Time Complexity: O(1)
Auxiliary Space: O(1)
mohit kumar 29
nidhi_biet
ankthon
noob2000
subham348
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flip all K-bits of a given number

04 May, 2021
Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits.
Examples:
Input:N = 1, K = 32Output: 4294967294Explanation:1 in K(= 32) bit representation is (00000000000000000000000000000001)2.Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10.
Input: N = 0, K = 32Output: 4294967295
Approach: Follow the steps below to solve the problem:
Find the value of (1 << (K – 1)) – 1, say X.
Finally, print the value of (X – N).
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Function to flip all K-bits// of an unsigned number Nvoid flippingBits(unsigned long N,                  unsigned long K){     // Stores (2 ^ K) - 1    unsigned long X = (1 << (K - 1)) - 1;     // Update N    N = X - N;     // Print the answer    cout << N;} // Driver Codeint main(){    unsigned long N = 1, K = 8;    flippingBits(N, K);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to flip all K-bits// of an unsigned number Nstatic void flippingBits(long N,                         long K){         // Stores (2 ^ K) - 1    long X = (1 << (K - 1)) - 1;         // Update N    N = X - N;         // Print the answer    System.out.print(N);} // Driver Codepublic static void main(String[] args){    long N = 1, K = 8;         flippingBits(N, K);}} // This code is contributed by shikhasingrajput
# Python3 Program for the above approach # Function to flip all K-bits# of an unsigned number Ndef flippingBits(N, K):     # Stores (2 ^ K) - 1    X = (1 << (K - 1)) - 1     # Update N    N = X - N     # Print the answer    print(N) # Driver Codeif __name__ == '__main__':    N, K = 1, 8    flippingBits(N, K)     # This code is contribute by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function to flip all K-bits// of an unsigned number Nstatic void flippingBits(int N, int K){         // Stores (2 ^ K) - 1    int X = (1 << (K - 1)) - 1;     // Update N    N = X - N;     // Print the answer    Console.Write(N);} // Driver Codepublic static void Main(string[] args){    int N = 1, K = 8;         flippingBits(N, K);}} // This code is contributed by chitranayal
<script> // Javascript program of the above approach // Function to flip all K-bits// of an unsigned number Nfunction flippingBits(N, K){          // Stores (2 ^ K) - 1    let X = (1 << (K - 1)) - 1;          // Update N    N = X - N;          // Print the answer    document.write(N);}     // Driver Code       let N = 1, K = 8;          flippingBits(N, K);  </script>
126
 
Time Complexity: O(1)Auxiliary Space: O(1)
mohit kumar 29
ukasp
shikhasingrajput
target_2
Technical Scripter 2020
Bit Magic
Mathematical
Technical Scripter
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – Multi line label

06 May, 2020
In this article we will see how we can create a multi-line label, when we create a label and set text to it and if the text length is greater then the length of the label extra text did not show, multi-line label make that extra text go into the other line. Below is the representation of how normal and multi-line label looks like
 
In order to do this we will use setWordWrap method.
Syntax : label.setWordWrap(True)
Argument : It takes bool as argument
Return : None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating label        label1 = QLabel("Normal label With out multi line", self)          # setting geometry to the label        label1.setGeometry(200, 150, 100, 50)          # adding border to the label        label1.setStyleSheet("border : 2px solid black;")          # creating label        label2 = QLabel("Multi label i.e With multi line", self)          # setting geometry to the label        label2.setGeometry(200, 250, 100, 50)          # adding border to the label        label2.setStyleSheet("border : 2px solid black;")          # making it multi line        label2.setWordWrap(True)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  window.show()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-Label
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Vectors in Octave GNU

18 Aug, 2020
Vector in Octave is similar to the array in every aspect except the vector size is dynamic, which means its size can be increased however array does not allow such type of increment in its size.
Types of Vectors
Row Vector
Column Vector
Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements.
% using space as the delimiterRowVector1 = [1 2 3 4 5];disp(RowVector1);  % using comma as the delimiterRowVector2 = [1, 2, 3, 4, 5];disp(RowVector2);
Output :
   1   2   3   4   5
   1   2   3   4   5

Column vectors are created by enclosing the set of elements in square brackets, using a semicolon to delimit the elements.
ColumnVector = [1; 2; 3; 4; 5];disp(ColumnVector);
Output :
   1
   2
   3
   4
   5

Accessing Elements in a Vector in Octave GNU : A vector element is accessed using the index of that element. The indexing starts from 1(not from 0). Language like C++, Java uses index from 0 to size-1, whereas in OCTAVE GNU index starts from 1 and ends at size; Also C++, java uses [] (Square Bracket) to access elements using index but in OCTAVE GNU parenthesis are used to access elements using the index.
Vector = [10 20 30 40 50];for i = 1 : 5    printf("Element at Vector(%d) is %d\n", i, Vector(i));endfor
Output :
Element at Vector(1) is 10
Element at Vector(2) is 20
Element at Vector(3) is 30
Element at Vector(4) is 40
Element at Vector(5) is 50

Octave-GNU
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Data Types
Decorators with parameters in Python
Difference between Shallow and Deep copy of a class
Shallow Copy and Deep Copy in C++
Top 10 Programming Languages to Learn in 2022
Kotlin Array
Advantages and Disadvantages of OOP
Difference between while and do-while loop in C, C++, Java
Top 10 Fastest Programming Languages
Which Programming Language Should I Choose as a Beginner?
Python | numpy.putmask() method

03 Oct, 2019
With the help of numpy.putmask() method, we can change the elements in an array with the help of condition and given value by using numpy.putmask() method.
Syntax : numpy.putmask(array, condition, value)Return : Return the array having new elements according to value.
Example #1 :In this example we can see that by using numpy.putmask() method, we are able to get the new array with the help of a given condition and value.
# import numpyimport numpy as np  # using numpy.putmask() methodarr = np.array([1, 2, 3, 4, 5, 6])np.putmask(arr, arr % 2 == 0, 0)  print(arr)
Output :
array([1, 0, 3, 0, 5, 0])
Example #2 :
# import numpyimport numpy as np  # using numpy.putmask() methodarr = np.array([[1, 2, 3],                [3, 2, 1],                [1, 2, 3]])  np.putmask(arr, arr>2, 4)  print(arr)
Output :
[[1 2 4][4 2 1][1 2 4]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Get the Hour from timestamp in Pandas

24 Jul, 2020
Let’s see how to extract the hour from a timestamp in Pandas, with the help of multiple examples.
Example 1 : pandas.timestamp.now() takes timezone as input and returns current timestamp object of that timezone.
# importing the moduleimport pandas as pd  # input current timestampdate = pd.Timestamp.now()print("currentTimestamp: ", date)  # extract the Hours from the timestampframe = date.hourprint("Hour: ", frame)
Output:
Example 2 : pandas.timestamp() is used for DateTimeIndex of a specific timezone. It takes year, month, day, time and timezone as input and returns DateTimeIndex of that timezone.
# importing the moduleimport pandas as pd     # input the timestampdate = pd.Timestamp(year = 2020, month = 7, day = 21,                     hour = 6, minute = 30, second = 44,                     tz = 'Asia / Kolkata')  print("Timestamp: ", date)  # extract the Hours from the timestampprint("Hour: ", date.hour)
Output :
Example 3 : Take input as range of timestamps using pandas.dt_range() and use pandas.series() to convert into an array of timestamps.
# importing the moduleimport pandas as pd   # take input Dates in a rangedates = pd.Series(pd.date_range('2019-8-5 10:23:05', periods = 6, freq ='H'))  # convert in a dict containerframe = pd.DataFrame(dict(givenDate = dates))  # extract Hours from Timestampframe['hourOfTimestamp'] = frame['givenDate'].dt.hourprint(frame)
Output :
Solution 4 : Use object.hour attribute to return the hour of the datetime within data of the given Series object.
# importing the moduleimport pandas as pd   # take inputsdates = pd.Series(['2015-01-11 09:20', '2019-4-8 11:31', '2018-12-22 10:10',                    '2011-4-2 04:25', '2017-1-6 03:51'])    # give a Name to the seriesseriesName = ['T1', 'T2', 'T3', 'T4', 'T5']    # give index to each timestampdates.index = seriesName  dates = pd.to_datetime(dates)  # extract Hours from Timestamp rs = dates.dt.hour  print(rs)
Output :
Solution 5 : Read timestamp data from a csv file and get Hours from each timestamp.
# importing the moduleimport pandas as pd  # read the date from xyz.csv fileframe = pd.read_csv(r'xyz.csv')print("Values in xyz.csv: ")print(frame.head())  frame['dateTime'] = frame['dateTime'].astype('datetime64[ns]')  # extract Hours from Timestamp  print("Hours: ")print(frame.dateTime.dt.hour.head())
Output :
Picked
Python Pandas-exercise
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove duplicate values inside a list in MongoDB?

You can use aggregate framework along with $setUnion operator. Let us first create a collection with documents −
> db.removeDuplicatesDemo.insertOne({"InstructorName":"Chris","InstructorAge":34,"InstructorSubject":
   ["Java","C","Java","C++","MongoDB","MySQL","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9d96c895c4fd159f80807")
}
Following is the query to display all documents from the collection with the help of find() method −
> db.removeDuplicatesDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cb9d96c895c4fd159f80807"),
   "InstructorName" : "Chris",
   "InstructorAge" : 34,
   "InstructorSubject" : [
      "Java",
      "C",
      "Java",
      "C++",
      "MongoDB",
      "MySQL",
      "MongoDB"
   ]
}
Following is the query to remove duplicate values inside a list in MongoDB −
> db.removeDuplicatesDemo.aggregate([
...    { "$project": {
...       "InstructorName":1,
...       "InstructorAge" :1,
...       "InstructorSubject" :{ "$setUnion": [ "$InstructorSubject", [] ] }
...    }}
... ]).pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cb9d96c895c4fd159f80807"),
   "InstructorName" : "Chris",
   "InstructorAge" : 34,
   "InstructorSubject" : [
      "C",
      "C++",
      "Java",
      "MongoDB",
      "MySQL"
   ]
}