code-rag-bench/online-tutorials huggingface dataset:
SQL DELETE JOIN

25 Oct, 2021
We use joins to combine data from multiple tables. To delete the same rows or related rows from the table at that time we use delete join. In this article let us see how to delete multiple data using DELETE using JOIN by using MSSQL as a server.
Syntax:
DELETE table1
FROM table1 JOIN table2 ON
table1.attribute_name = table2.attribute_name
WHERE condition
Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Step 2: To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Output:
Step 3: Now we are creating two tables. Create a table for students with 3 columns and library_books with 2 columns using the following SQL query.
Query:
CREATE TABLE student (
student_id VARCHAR(8),
student_name VARCHAR(20),
student_branch VARCHAR(20)
)
Output:
Query:
CREATE TABLE library_books(
lib_id VARCHAR(20),
book_taken INT
)
Output:
Step 4: Viewing the description of the tables.
Query:
EXEC sp_columns students
Output:
Query:
EXEC sp_columns library_books
Output:
Step 5: The query for Inserting rows into the Table. Inserting rows into students and library_books  table using the following SQL query.
Query:
INSERT INTO students
VALUES( '1001','PRADEEP','E.C.E'),
( '1002','KIRAN','E.C.E'),
( '1003','PRANAV','E.C.E'),
( '2001','PADMA','C.S.E'),
( '2002','SRUTHI','C.S.E'),
( '2003','HARSITHA','C.S.E'),
( '3001','SAI','I.T'),
( '3002','HARSH','I.T'),
( '3003','HARSHINI','I.T')
Output:
Query:
INSERT INTO library_books
VALUES( '1001',2),
( '1002',3),
( '1003',4),
( '2001',2),
( '3001',3)
Output:
Step 6: Viewing the inserted data
Query:
SELECT * FROM students
Output:
Query:
SELECT * FROM library_books
Output:
Query to delete library entry for id 1001 using join
Query:
DELETE library_books
FROM  library_books JOIN students ON
students.student_id =library_books.lib_id
WHERE lib_id= 1001 
SELECT * FROM library_books
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
LINQ | Method Syntax

21 May, 2019
In LINQ, Method Syntax is used to call the extension methods of the Enumerable or Queryable static classes. It is also known as Method Extension Syntax or Fluent. However, the compiler always converts the query syntax in method syntax at compile time. It can invoke the standard query operator like Select, Where, GroupBy, Join, Max, etc. You are allowed to call them directly without using query syntax.
Creating first LINQ Query using Method Syntax in C#
Step 1: First add System.Linq namespace in your code.using System.Linq;
using System.Linq;
Step 2: Next, create a data source on which you want to perform operations. For example:List my_list = new List(){
        "This is my Dog",
        "Name of my Dog is Robin",
        "This is my Cat",
        "Name of the cat is Mewmew"
    };

List my_list = new List(){
        "This is my Dog",
        "Name of my Dog is Robin",
        "This is my Cat",
        "Name of the cat is Mewmew"
    };

Step 3: Now create the query using the methods provided by the Enumerable or Queryable static classes. For example:    
var res = my_list.Where(a=> a.Contains("Dog"));
Here res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”).
    
var res = my_list.Where(a=> a.Contains("Dog"));

Here res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”).
Step 4: Last step is to execute the query by using a foreach loop. For example:foreach(var q in res)
{
         Console.WriteLine(q);
}

foreach(var q in res)
{
         Console.WriteLine(q);
}

Example:
// Create the first Query in C# using Method Syntaxusing System;using System.Linq;using System.Collections.Generic;  class GFG {      // Main Method    static public void Main()    {          // Data source        List<string> my_list = new List<string>() {                "This is my Dog",                "Name of my Dog is Robin",                "This is my Cat",                "Name of the cat is Mewmew"        };          // Creating LINQ Query        // Using Method syntax        var res = my_list.Where(a => a.Contains("Dog"));          // Executing LINQ Query        foreach(var q in res)        {            Console.WriteLine(q);        }    }}
This is my Dog
Name of my Dog is Robin

CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
How to find maximum between 2 numbers using C#?

Firstly, declare and initialize two numbers.
int num1 = 50;
int num2 = 90;
With that, use if-else to find the maximum number.
if (num1 > num2) {
   maxNum = num1;
} else {
   maxNum = num2;
}
Above, we have set the maximum value to the variable maxNum and printed it later on.
The following is the complete example to find maximum between 2 numbers in C#.
 Live Demo
using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         int num1 = 50;
         int num2 = 90;
         int maxNum;
         Console.WriteLine("Number 1: "+num1);
         Console.WriteLine("Number 2: "+num2);
         if (num1 > num2) {
            maxNum = num1;
         } else {
            maxNum = num2;
         }
         Console.WriteLine("Maximum number is: "+maxNum);
         Console.ReadKey() ;
      }
   }
}
Number 1: 50
Number 2: 90
Maximum number is: 90
Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N) in C++

We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N.
We will do this by finding solutions to the equation a3 + b3 = N. Where a is not more than cube root of N and b can be calculated as cube root of (N-a3).
Let’s understand with examples.
Input 
N=35
Output 
Count of pairs of (a,b) where a^3+b^3=N: 2
Explanation 
Pairs will be (2,3) and (3,2). 23+33=8+27=35
Input 
N=100
Output 
Count of pairs of (a,b) where a^3+b^3=N: 0
Explanation 
No such pairs possible.
We take integer N.
We take integer N.
Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n.
Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n.
Take the initial variable count as 0 for pairs.
Take the initial variable count as 0 for pairs.
Traverse using for loop to find a.
Traverse using for loop to find a.
Start from a=1 to a<=cbrt(n) which is cube root of n.
Start from a=1 to a<=cbrt(n) which is cube root of n.
Calculate cube of b as n-pow(a,3).
Calculate cube of b as n-pow(a,3).
Calculate b as cbrt(bcube)
Calculate b as cbrt(bcube)
If pow(b,3)==bcube. Increment count by 1.
If pow(b,3)==bcube. Increment count by 1.
At the end of all loops count will have a total number of such pairs.
At the end of all loops count will have a total number of such pairs.
Return the count as result.
Return the count as result.
 Live Demo
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int cubeSum(int n){
   int count = 0;
   for (int a = 1; a < cbrt(n); a++){
      int bcube=n - (pow(a,3));
      int b = cbrt(bcube);
      if(pow(b,3)==bcube)
         { count++; }
   }
   return count;
}
int main(){
   int N = 35;
   cout <<"Count of pairs of (a,b) where a^3+b^3=N: "<<cubeSum(N);
   return 0;
}
If we run the above code it will generate the following output −
Count of pairs of (a,b) where a^3+b^3=N: 2
numpy.exp2() in Python - GeeksforGeeks

29 Nov, 2018
numpy.exp2(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :This mathematical function helps user to calculate 2**x for all x being the array elements.
Parameters :
array : [array_like]Input array or object whose elements, we need to test.out : [ndarray, optional]Output array with same dimensions as Input array,placed with result.**kwargs : Allows you to pass keyword variable length of argument to a function.It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universalfunctions(ufunc) at that position, False value means to leave thevalue in the output alone.
Return :
An array with 2**x(power of 2) for all x i.e. array elements 

 Code 1 : Working
# Python program explaining# exp2() functionimport numpy as np  in_array = [1, 3, 5, 4]print ("Input array : \n", in_array)  exp2_values = np.exp2(in_array)print ("\n2**x values : \n", exp2_values)
Output :
Input array : 
 [1, 3, 5, 4]

2**x values : 
 [  2.   8.  32.  16.]

 Code 2 : Graphical representation
# Python program showing# Graphical representation of # exp2() functionimport numpy as npimport matplotlib.pyplot as plt  in_array = [1, 2, 3, 4, 5 ,6]out_array = np.exp2(in_array)  print("out_array : ", out_array)  y = [1, 2, 3, 4, 5 ,6]plt.plot(in_array, y, color = 'blue', marker = "*")  # red for numpy.exp2()plt.plot(out_array, y, color = 'red', marker = "o")plt.title("numpy.exp2()")plt.xlabel("X")plt.ylabel("Y")plt.show()  
Output :out_array : [ 2. 4. 8. 16. 32. 64.]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp2.html.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Plotting a horizontal line on multiple subplots in Python using pyplot

To plot a horizontal line on multiple subplots in Python, we can use subplots to get multiple axes and axhline() method to draw a horizontal line.
Create a figure and a set of subplots. Here, we will create 3 subplots.
Create a figure and a set of subplots. Here, we will create 3 subplots.
Use axhline() method to draw horizontal lines on each axis.
Use axhline() method to draw horizontal lines on each axis.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(3)
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
ax1.axhline(y=0.5, xmin=0, xmax=3, c="black", linewidth=2, zorder=0)
ax2.axhline(y=0.5, xmin=0, xmax=3, c="red", linewidth=3, zorder=0)
ax3.axhline(y=0.5, xmin=0, xmax=3, c="yellow", linewidth=4, zorder=0)
plt.show()
How to use Measure-Object in PowerShell?

Measure-Object in PowerShell is used to measure the property of the command. There are various measurement parameters are available. For example, Average, Count, sum, maximum, minimum and more.
Get-Process | Measure-Object
PS C:\WINDOWS\system32> Get-Process | Measure-Object
Count       : 278
Average     :
Sum         :
Maximum     :
Minimum     :
Property    :
Here, in the above output, there are total 278 processes are running. If you want to check the maximum memory usage then you can use WorkingSet property with − Maximum Parameter.
Get-Process | Measure-Object -Property WorkingSet -Maximum
PS C:\WINDOWS\system32> Get-Process | Measure-Object -Property WorkingSet –
Maximum
Count       : 277
Average     :
Sum         :
Maximum     : 353447936
Minimum     :
Property    : WorkingSet
You can also use the multiple parameters together like Maximum, Minimum, Sum (To get the total memory consumed in this example) and Average (To get average of memory usage in this example).
Get-Process | Measure-Object -Property WorkingSet -Maximum -Minimum -Sum -
Average
Count       : 275
Average     : 37769618.1527273
Sum         : 10386644992
Maximum     : 347447296
Minimum     : 8192
Property    : WorkingSet
For the text file or the string, you can use measurement properties like Line, Word, character, etc.
Get-Content D:\Temp\testreadC.txt | Measure-Object
Count          : 232
Average        :
Sum            :
Maximum        :
Minimum        :
Property       :
To get the Line, Word and Character count,
Get-Content D:\Temp\testreadC.txt | Measure-Object -Line -Word -Character
Lines       Words       Characters    Property
-----       -----       ----------     --------
  229        1829            27156
You can also ignore the whitespace and count the characters.
Get-Content D:\Temp\testreadC.txt | Measure-Object -Line -Word -Character -IgnoreWhiteSpace
Lines       Words       Characters       Property
-----       -----       ----------       --------
  229        1829             7424
Erlang - whereis

It is called as whereis(Name). Returns the pid of the process that is registered with the name.
whereis(atom,pid)

atom − This is the registered name to give to the process.
atom − This is the registered name to give to the process.
The process id bound to the atom.
-module(helloworld). 
-export([start/0, call/2]). 

call(Arg1, Arg2) -> 
   io:fwrite("~p~n",[Arg1]). 

start() -> 
   Pid = spawn(?MODULE, call, ["hello", "process"]), 
   register(myprocess, Pid), 
   io:fwrite("~p~n",[whereis(myprocess)]).
When we run the above program, we will get the following result.
<0.55.0>
"hello"

 Print
 Add Notes
 Bookmark this page
Python Group elements at same indices in a multi-list

In this tutorial, we are going to write a program that combines elements of the same indices different lists into a single list. And there is one constraint here. All the lists must be of the same length. Let's see an example to understand it more clearly.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
We can solve it in different ways. Let's see how to solve with normal loops.
Initialize the list with lists.
Initialize an empty list.
Initialize a variable index to 0.
Iterate over the sub list length timesAppend an empty list to the previous listIterate lists length times.Append the **lists[current_index][index]** to the **result[index]
Append an empty list to the previous list
Iterate lists length times.Append the **lists[current_index][index]** to the **result[index]
Append the **lists[current_index][index]** to the **result[index]
Print the result.
 Live Demo
# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# empty list
result = []
# variable to 0
index = 0
# iterating over the sub_list length (3) times
for i in range(len(lists[0])):
   # appending an empty sub_list
   result.append([])
   # iterating lists length (3) times
   for j in range(len(lists)):
      # adding the element to the result
      result[index].append(lists[j][index])
# moving to the next index
index += 1
# printing the result
print(result)
If you run the above code, then you will get the following result.
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
We can solve it using the zip function without any effort. The zip function gives you all the index elements in a tuple as we want. Let's see the code.
 Live Demo
# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# using the zip and printing it
print(list(zip(*lists)))
If you run the above code, then you will get the following result.
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
We can convert the tuples into the list by iterating through the lists. It can be done differently.will use another function called map to convert all tuples into lists. It's one line code.
 Live Demo
# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# using the zip and printing it
print(list(map(list, zip(*lists))))
If you run the above code, then you will get the following result.
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
We have used map to iterate through the list and convert each tuple into the list. You can do same with loops. Try it.
If you have any doubts in the tutorial, mention them in the comment section.
Create a temporary file in Java

A temporary file can be created using the method java.io.File.createTempFile(). This method requires two parameters i.e. the prefix to define the file name and the suffix to define the file extension. It also returns the abstract path name for the temporary file created.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) throws Exception {
      File file = File.createTempFile("temp", null);
      System.out.println(file.getAbsolutePath());
      file.deleteOnExit();
   }
}
The output of the above program is as follows −
C:\Users\amit_\AppData\Local\Temp\temp6072597842246154962.tmp
Now let us understand the above program.
A temporary file is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows −
File file = File.createTempFile("temp", null);
System.out.println(file.getAbsolutePath());
file.deleteOnExit();
Javascript - Page Printing

Many times you would like to give a button at your webpage to print out the content of that web page via an actual printer.
JavaScript helps you to implement this functionality using print function of window object.
The JavaScript print function window.print() will print the current web page when executed. You can call this function directly using onclick event as follows:
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onClick="window.print()" />
</form>
</body>

This will produce following button which let you print this page. Try it by clicking:




This serves your purpose to get page printed out, but this is not a recommended way of giving printing facility. You can do one of the followings  to make a page printer friendly:
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
If you do not want to keep extra copy of a page then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in background to purge printable text and display for final printing. Our site is using same method to give print facility to our site visitors. Check Example.

If you do not want to keep extra copy of a page then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in background to purge printable text and display for final printing. Our site is using same method to give print facility to our site visitors. Check Example.
If someone is providing none of the above facilities then you can use browser's standard toolbar to get web pages printed out. Follow the link as follows:
File -->  Print --> Click OK  button.
Content available at TutorialsPoint.COM

Advertisements


    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
Sum triangle from an array in C programming

The sum triangle from an array is a triangle that is made by decreasing the number of elements of the array one by one and the new array that is formed is with integers that are the sum of adjacent integers of the existing array. This procedure continues until only one element remains in the array.
Let's take an example to explain the content better,
Array = [3,5,7,8,9]
Output
[106]
[47,59]
[20,27,32]
[8,12,15,17]
[3,5,7,8,9]
Explanation
For the first array : ( 3 + 5 = 8), ( 5 + 7 = 12), ( 7 + 8 = 15),( 8 + 9 = 17)
For the second array: 8 + 12 = 20 , 12 + 15 = 27 , 15 + 17 = 32
For the third array: 20 + 27 = 47 , 27 + 32 = 59
For the final array: 47 + 59 = 106
The code runs as it is shown in the example explanation. So for this we need a recursive function that will call itself for every array.
#include<stdio.h>
void printTriangle(int arr[] , int n) {
   if (n < 1) {
      return;
   }
   int temp[n - 1];
   for (int i = 0; i < n - 1; i++) {
      int x = arr[i] + arr[i + 1];
      temp[i] = x;
   }
   printTriangle(temp, n - 1);
   for (int i = 0; i < n ; i++) {
      if(i == n - 1)
         printf("%d ",arr[i]);
      else
         printf("%d, ",arr[i]);
   }
   printf("\n");
}
int main() {
   int arr[] = { 3,5,7,8,9};
   int n = sizeof(arr) / sizeof(arr[0]);
   printTriangle(arr, n);
}
106
47, 59
20, 27, 32
8, 12, 15, 17
3, 5, 7, 8, 9
Python 3 - Number cos() Method

The cos() method returns the cosine of x radians.
Following is the syntax for cos() method −
cos(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the cosine of the angle.
The following example shows the usage of cos() method.
#!/usr/bin/python3
import math

print ("cos(3) : ",  math.cos(3))
print ("cos(-3) : ",  math.cos(-3))
print ("cos(0) : ",  math.cos(0))
print ("cos(math.pi) : ",  math.cos(math.pi))
print ("cos(2*math.pi) : ",  math.cos(2*math.pi))
When we run the above program, it produces the following result −
cos(3) :  -0.9899924966
cos(-3) :  -0.9899924966
cos(0) :  1.0
cos(math.pi) :  -1.0
cos(2*math.pi) :  1.0


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to fetch only N rows at a time in MySQL?

To fetch only N rows at a time, you can use LIMIT operator. Following is the syntax −
select *from yourTableNameLIMIT 0,N;
Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20)
   );
Query OK, 0 rows affected (0.25 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.08 sec)

mysql> insert into DemoTable(Name) values('Larry');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.08 sec)

mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(Name) values('Ramit');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name) values('Adam');
Query OK, 1 row affected (0.03 sec)

mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(Name) values('James');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable(Name) values('Jace');
Query OK, 1 row affected (0.05 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+
| Id | Name   |
+----+--------+
|  1 | John   |
|  2 | Larry  |
|  3 | Bob    |
|  4 | Sam    |
|  5 | Mike   |
|  6 | David  |
|  7 | Carol  |
|  8 | Ramit  |
|  9 | Adam   |
| 10 | Chris  |
| 11 | Robert |
| 12 | James  |
| 13 | Jace   |
+----+--------+
13 rows in set (0.00 sec)
Following is the query to fetch only N rows at a time. Here, we are fetching only 10 rows −
mysql> select *from DemoTable LIMIT 0,10;
This will produce the following output −
+----+-------+
| Id | Name  |
+----+-------+
|  1 | John  |
|  2 | Larry |
|  3 | Bob   |
|  4 | Sam   |
|  5 | Mike  |
|  6 | David |
|  7 | Carol |
|  8 | Ramit |
|  9 | Adam  |
| 10 | Chris |
+----+-------+
10 rows in set (0.00 sec)
Stream peek() Method in Java with Examples

11 Apr, 2022
In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation, as it creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. 
Syntax: 
Stream<T> peek(Consumer<? super T> action)
Here, Stream is an interface and T is the type of stream element. action is a non-interfering action to perform on the elements as they are consumed from the stream and the function returns the new stream.Now we need to understand the lifecycle of peek() method via its internal working via clean java programs listed below as follows:
Note:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
Since Java 9, if the number of elements is known in advance and unchanged in the stream, the .peek () statement will not be executed due to performance optimization. It is possible to force its operation by a command (formal) changing the number of elements eg. .filter (x -> true).
Using peek without any terminal operation does nothing.
Example 1:
Java
// Java Program to Illustrate peek() Method// of Stream class Without Terminal Operation Count // Importing required classesimport java.util.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating a list of Integers        List<Integer> list            = Arrays.asList(0, 2, 4, 6, 8, 10);         // Using peek without any terminal        // operation does nothing        list.stream().peek(System.out::println);    }}
  
Output: 
 
 
From the above output, we can perceive that this piece of code will produce no output
 
Example 2:
 
Java
// Java Program to Illustrate peek() Method// of Stream class With Terminal Operation Count // Importing required classesimport java.util.*; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating a list of Integers        List<Integer> list            = Arrays.asList(0, 2, 4, 6, 8, 10);         // Using peek with count() method,Method        // which is a terminal operation        list.stream().peek(System.out::println).count();    }}
  
Output:  
 
0
2
4
6
8
10
 
zemiak
solankimayank
germanshephered48
ghiathmakhoul
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TypeScript | String split() Method

20 Jun, 2022
The split() is an inbuilt function in TypeScript which is used to splits a String object into an array of strings by separating the string into sub-strings.
Syntax:
string.split([separator][, limit])
Parameter: This method accepts two parameter as mentioned above and described below: 
separator – This parameter is  the character to use for separating the string.
limit – This parameter is the Integer specifying a limit on the number of splits to be found.
Return Value: This method returns the new array. Below examples illustrate the String split() method in TypeScript.Example 1: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";     // use of String split() Method    var newarr = str.split(" ");     console.log(newarr);</script>
Output: 
[ 'Geeksforgeeks', '-', 'Best', 'Platform' ]
Example 2: 
JavaScript
<script>    // Original strings    var str = "Geeksforgeeks - Best Platform";     // use of String split() Method    var newarr = str.split("",14);     console.log(newarr);</script>
Output: 
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ' ' ]
surinderdawra388
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | ctype_space() Function

06 Jun, 2018
A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False.
Syntax :
ctype_space(string text)

Parameter Used:
text :- It is a mandatory parameter which specifies the string.
Return Value:Returns TRUE if every character in text contains white space, return false otherwise. the blank character this also includes tab, carriage, vertical tab, line feed, and form feed characters.
Examples:
Input  : \r   
Output : Yes
Explanation: \r is create white space


Input  : abc\r
Output : No   
Explanation: characters "abc" are not white space

Below programs illustrate the ctype_space() function.Program 1: taking a single string
<?php// PHP program to check given string is // whitespace character or not  $string = "/n/t/r";  if (ctype_space($string))    echo "Yes \n";else    echo "No \n";   ?>
No

Program: 2 Taking an array of string and checking for whitespace using ctype_space() function
<?php// PHP program to check given string is // whitespace  character or not  $strings = array('\n\y\t\x\u\o', "\ngfg\n", "\t");  // Checking above given strings //by used of ctype_space()function .foreach ($strings as $testcase) {          if (ctype_space($testcase)) {        echo "Yes \n";    } else {        echo "No \n";    }}?>
No 
No 
Yes

Program: 3Takes an example ctype_space() function how to work string in both single quotes ‘ ‘ and double quotes ” ” symbol.
<?php// PHP program to check given string is // whitespace  character or not  $strings = array('\n', "\n", '\t', "\t");  // Checking above given strings // by used of ctype_space()function .  foreach ($strings as $testcase) {          if (ctype_space($testcase)) {        echo "Yes \n";    } else {        echo "No \n";    }}?>
No 
Yes 
No 
Yes

References :http://php.net/manual/en/function.ctype-space.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java.io.BufferedReader Class in Java

03 May, 2022
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made by a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
Implementation: The content inside the file is as follows:
This is first line
this is second line
Example
Java
// Java Program to Illustrate BufferedReader Class// Via Its Methods  // Importing required classesimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;  // Classclass GFG {      // Main driver method    public static void main(String[] args)        throws IOException    {          // Creating object of FileReader and BufferedReader        // class        FileReader fr = new FileReader("file.txt");        BufferedReader br = new BufferedReader(fr);          char c[] = new char[20];          // Illustrating markSupported() method        if (br.markSupported()) {              // Print statement            System.out.println(                "mark() method is supported");              // Illustrating mark method            br.mark(100);        }          // File Contents is as follows:        // This is first line        // this is second line          // Skipping 8 characters        br.skip(8);          // Illustrating ready() method        if (br.ready()) {              // Illustrating readLine() method            System.out.println(br.readLine());              // Illustrating read(char c[],int off,int len)            br.read(c);              for (int i = 0; i < 20; i++) {                System.out.print(c[i]);            }              System.out.println();              // Illustrating reset() method            br.reset();            for (int i = 0; i < 8; i++) {                  // Illustrating read() method                System.out.print((char)br.read());            }        }    }}
Output:
mark() method is supported
first line
this is second line
This is 
This article is contributed by Nishant Sharma. 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.
solankimayank
Java-Classes
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program for Heap Sort - GeeksforGeeks

27 Mar, 2019
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.
// Java program for implementation of Heap Sortpublic class HeapSort{    public void sort(int arr[])    {        int n = arr.length;          // Build heap (rearrange array)        for (int i = n / 2 - 1; i >= 0; i--)            heapify(arr, n, i);          // One by one extract an element from heap        for (int i=n-1; i>=0; i--)        {            // Move current root to end            int temp = arr[0];            arr[0] = arr[i];            arr[i] = temp;              // call max heapify on the reduced heap            heapify(arr, i, 0);        }    }      // To heapify a subtree rooted with node i which is    // an index in arr[]. n is size of heap    void heapify(int arr[], int n, int i)    {        int largest = i;  // Initialize largest as root        int l = 2*i + 1;  // left = 2*i + 1        int r = 2*i + 2;  // right = 2*i + 2          // If left child is larger than root        if (l < n && arr[l] > arr[largest])            largest = l;          // If right child is larger than largest so far        if (r < n && arr[r] > arr[largest])            largest = r;          // If largest is not root        if (largest != i)        {            int swap = arr[i];            arr[i] = arr[largest];            arr[largest] = swap;              // Recursively heapify the affected sub-tree            heapify(arr, n, largest);        }    }      /* A utility function to print array of size n */    static void printArray(int arr[])    {        int n = arr.length;        for (int i=0; i<n; ++i)            System.out.print(arr[i]+" ");        System.out.println();    }      // Driver program    public static void main(String args[])    {        int arr[] = {12, 11, 13, 5, 6, 7};        int n = arr.length;          HeapSort ob = new HeapSort();        ob.sort(arr);          System.out.println("Sorted array is");        printArray(arr);    }}
Please refer complete article on Heap Sort for more details!
Heap Sort
Heap
Java Programs
Sorting
Sorting
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Building Heap from Array
Sliding Window Maximum (Maximum of all subarrays of size k)
Insertion and Deletion in Heaps
Max Heap in Java
Merge k sorted arrays | Set 1
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Preventing an image from being draggable or selectable in HTML without using JS

Add the following code snippet to image properties, and prevent images from being dragged and selected.
img {  
   user-drag: none;  
   user-select: none;
   -moz-user-select: none;
   -webkit-user-drag: none;
   -webkit-user-select: none;
   -ms-user-select: none;
}
On double click on a text or image, it is highlighted (selected). The user select property can be used to prevent this. By setting this property to none, we can prevent our image from being selected (highlighted).
You can try to run the following code to prevent the image from being selected −
<!DOCTYPE html>
<html>
   <head>
      <style>
         img {
            -drag: none;
            user-select: none;
            -moz-user-select: none;
            -webkit-user-drag: none;
            -webkit-user-select: none;
            -ms-user-select: none;
         }
      </style>
   </head>
   <body>
      <img src = "https://www.tutorialspoint.com/images/python3.png" alt = "Python" width = "62" height = "62">
   </body>
</html>
Recursive sum all the digits of a number JavaScript

Let’s say, we are required to create a function that takes in a number and finds the sum of its
digits recursively until the sum is a one-digit number.
For example −
findSum(12345) = 1+2+3+4+5 = 15 = 1+5 = 6
So, the output should be 6.
Let’s write the code for this function findSum() −
// using recursion
const findSum = (num) => {
   if(num < 10){
      return num;
   }
   const lastDigit = num % 10;
   const remainingNum = Math.floor(num / 10);
   return findSum(lastDigit + findSum(remainingNum));
}
console.log(findSum(2568));
We check if the number is less than 10, it’s already minified and we should return it and from the
function otherwise we should return the call to the function that recursively takes the last digit
from the number adds to it until it becomes less than 10.
So, the output for this code will be −
3
How to change the color code of corrplot in R?

To change the color code of corrplot, we can use colorRampPalette function inside corrplot function. We can provide different colors in colorRampPalette that we want to display in the corrplot.
Check out the below given example to understand how it can be done.
Following snippet creates a sample data frame −
x<-rpois(20,2)
y<-rpois(20,5)
z<-rpois(20,5)
a<-rpois(20,1)
b<-rpois(20,2)
df<-data.frame(x,y,z,a,b)
df
The following dataframe is created −
   x  y  z  a b
1  0  2  5  2 1
2  1  7  4  1 3
3  1  2  6  0 5
4  0  6  1  1 3
5  3  4  5  0 4
6  1  3  4  1 2
7  0  8 10  0 3
8  1  3  2  1 1
9  0  6  6  3 2
10 1  4  7  2 1
11 2  3  4  1 2
12 0  7 12  1 2
13 2  7  7  0 2
14 2  6  7  1 1
15 2  6  4  2 3
16 1  8  7  1 3
17 3  3 13  1 4
18 0  4  6  3 1
19 2  5  3  1 3
20 2  8  4  0 0
To find the correlation matrix, add the following code to the above snippet −
x<-rpois(20,2)
y<-rpois(20,5)
z<-rpois(20,5)
a<-rpois(20,1)
b<-rpois(20,2)
df<-data.frame(x,y,z,a,b)
Corr_M<-cor(df)
Corr_M
If you execute all the above given snippets as a single program, it generates the following output −
         x          y        z           a          b
x  1.00000000 -0.1124089  0.02748119 -0.42486657  0.2408651
y -0.11240888  1.0000000  0.15417565 -0.20276944 -0.1140731
z  0.02748119  0.1541756  1.00000000 -0.07005503  0.1766658
a -0.42486657 -0.2027694 -0.07005503  1.00000000 -0.3479217
b  0.24086512 -0.1140731  0.17666576 -0.34792175  1.0000000
To load corrplot package and create a correlation matrix plot, add the following code to the above snippet −
library(corrplot)
corrplot(abs(Corr_M),method="color",cl.lim=c(0,1))
If you execute all the above given snippets as a single program, it generates the following output −
To create a correlation matrix plot with different colors, add the following code to the above snippet −
corrplot(abs(Corr_M),method="color",col=colorRampPalette(c("white","lightblue","red"))(100),cl.lim=c(0,1))

If you execute all the above given snippets as a single program, it generates the following output −
PyQtGraph – Setting Background of Plot Window

24 Sep, 2020
In this article we will see how we can set the background of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. By default PyQtGraph plot window color is black although we can change this any time, it background is set to the None it become transparent.
We can create a plot window with the help of command given below
# creating a pyqtgraph plot window
window = pg.plot()

In order to do this we use setBackground method with the plot window object
Syntax : window.setBackground(background)
Argument : It takes string as argument
Return : It returns None
Below is the implementation
# importing pyqtgraph as pgimport pyqtgraph as pg  # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui  # importing numpy as npimport numpy as np  import time  # creating a pyqtgraph plot windowwindow = pg.plot()  # titletitle = "GeeksforGeeks PyQtGraph"      # setting window titlewindow.setWindowTitle(title)  # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2]  # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph1 = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g')  # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph1)    # setting plot window background color to yellowwindow.setBackground('y')      # main methodif __name__ == '__main__':          # importing system    import sys          # Start Qt event loop unless running in interactive mode or using     if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):        QtGui.QApplication.instance().exec_()         
Output :
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HackingTool – ALL IN ONE Hacking Tool For Hackers

22 Nov, 2021
HackingTool is a free and open-source tool available on GitHub.  HackingTool is used as an information-gathering tool. HackingTool  is used to scan websites for information gathering and find vulnerabilities in websites and webapps. HackingTool is one of the easiest and useful tool for performing reconnaissance on websites and web apps. The HackingTool tool is also available for Linux, window, and android phones ( termux ) that is coded in both bash and python language. HackingTool interface is very similar to Metasploit 1 and Metasploit. HackingTool provides command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). We can target any domain using Fsociety. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python language. You must have Python language installed in your kali Linux to use this tool. HackingTool is Penetration Testing Framework. HackingTool is a complete framework of tools of hacking. This is very useful when you get all the tools in a single framework.
Step 1: Use the following command to install the tool from GitHub. Use the second command to move into the directory of the tool.
git clone https://github.com/Z4nzu/hackingtool.git chmod -R 755 hackingtool && cd hackingtool
Step 2: Now you are in the directory of the tool. Use the following command to install dependencies of the tool.
sudo pip3 install -r requirement.txt
Step 3: All the dependencies of the tool have been installed. Now use the following command to run the tool.
sudo hackingtool
The framework has been installed successfully. Now we will see how to install a tool from the framework.
choose option 1
1
Now choose any tool from this framework. Select IP for scanning
2
The tool is running successfully. Similarly, you can use any tool from framework.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL | SHA1( ) Function

17 Feb, 2021
The MySQL SHA1() function is used for encrypting a string using the SHA-1 technique. The SHA1 stands for secure hash algorithm and it produces a 160-bit checksum for a user inputted string. 
The MySQL SHA1() function returns NULL if the string passed as an argument is a NULL string. The SHA1() function accepts one parameter which is the string to be encrypted. 
Syntax:  
SHA1(string)
Parameters Used: 
string – It is used to specify the plain text string that is to be encrypted. 
Return Value: The SHA1() function in MySQL returns the encrypted string or NULL if the string passed is an empty string. 
Supported Versions of MySQL: 
 
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing SHA1() function on a string.  
SELECT  
SHA1('geeksforgeeks'); 
Output:  
69c9a5c19c5c27e43cb0efc4c8644ed6d03a110b 
Example-2: Implementing SHA1() function on a string which has a combination of characters and integers.  
SELECT 
SHA1('geeksforgeeks123'); 
Output:  
53ce00666cbef425ab8d06ed652095bea20a1616 
Example-3: Implementing SHA1() function on a NULL string and returning the length of the string after compression.  
SELECT  
SHA1(NULL); 
Output:  
NULL 
 
simranarora5sos
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

Tryit: Use CSS and JavaScript to show an element on click
How to update NPM ?

31 May, 2020
NPM (Node Package Manager) is the default package manager for Node.js and is written entirely in JavaScript. It manages all the packages and modules for Node.js and consists of command-line client npm. It gets installed into the system with the installation of Node.js. The required packages and modules in the Node project are installed using NPM.
The update of the NPM means the update node package manager to the latest version. The update of NPM updates the Node.js and modules to the latest version.
Syntax:
npm update [-g] [<pkg>...]
Here, -g refers to global and pkg refers to package.
Method 1: Using npm update command to update the node package manager.
npm update -g
Method 2: Using npm@latest command to update the node package manager.
npm install npm@latest -g
Method 3: Using PPA repository (only for Linux).
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs npm
Method 4: Using cache cleaning & stable installing (only for Linux).
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
Method 5: Using npm@next to update the node package manager.
npm install -g npm@next
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.