code-rag-bench/online-tutorials huggingface dataset:
MySQL LIKE IN()?

You can implement MySQL Like IN() with the help of Regular Expression (regexp) as well. The syntax is as follows −
select *from yourTableName where yourColumName regexp ‘value1|value2|value3......|valueN’;
To understand the above logic, you need to create a table. Let us first create a table −
mysql> create table INDemo
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.90 sec)
Insert some records into the table. The query is as follows −
mysql> insert into INDemo values(100,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into INDemo values(104,'Carol');
Query OK, 1 row affected (0.18 sec)
mysql> insert into INDemo values(108,'David');
Query OK, 1 row affected (0.19 sec)
mysql> insert into INDemo values(112,'Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into INDemo values(116,'Johnson');
Query OK, 1 row affected (0.17 sec)
mysql> insert into INDemo values(120,'Sam');
Query OK, 1 row affected (0.16 sec)
Now we can display all the records with the help of SELECT statement. The query is as follows −
mysql> select *from INDemo;
The following is the output −
+------+---------+
| Id   | Name    |
+------+---------+
| 100  | John    |  
| 104  | Carol   |
| 108  | David   |
| 112  | Smith   |
| 116  | Johnson |
| 120  | Sam     |
+------+---------+
6 rows in set (0.00 sec)
Use regexp that works like IN(). You can apply the above syntax which I have discussed in the beginning. The query is as follows −
mysql> select *from INDemo where Id regexp '112|116|100';
The following is the output −
+------+---------+
| Id   | Name    |
+------+---------+
| 100  | John    |
| 112  | Smith   |
| 116  | Johnson |
+------+---------+
3 rows in set (0.21 sec)
You will get the same output with IN(). Now, let us check it with the help of IN(). The query is as follows −
mysql> select *from INDemo where Id IN(112,116,100);
Here is the output
+------+---------+
| Id   | Name    |
+------+---------+
| 100  | John    |
| 112  | Smith   |
| 116  | Johnson |
+------+---------+
3 rows in set (0.00 sec)
As you can see in the above output, we are getting the same result.
Fortran - do while Loop Construct

It repeats a statement or a group of statements while a given condition is true. It tests the condition before executing the loop body.
do while (logical expr) 
   statements
end do
program factorial  
implicit none  

   ! define variables
   integer :: nfact = 1   
   integer :: n = 1 
   
   ! compute factorials   
   do while (n <= 10)       
      nfact = nfact * n 
      n = n + 1
      print*,  n, " ", nfact   
   end do 
end program factorial  
When the above code is compiled and executed, it produces the following result −
2             1
3             2
4             6
5            24
6           120
7           720
8          5040
9         40320
10        362880
11       3628800

 Print
 Add Notes
 Bookmark this page
D3.js linkHorizontal() Method - GeeksforGeeks

14 Sep, 2020
The d3.linkHorizontal() method returns a new link generator with Horizontal tangents. It is typically used when the root is on the top/bottom edge with the children going down/up.
Syntax:
var link = d3.linkHorizontal()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; });


Parameters: This function does not take any parameter.
Return Value: This method returns a new link generator.
Example:
HTML
<!DOCTYPE html><html><head>    <meta charset="utf-8">     <script src=        "https://d3js.org/d3.v5.min.js">    </script></head> <body>     <h1 style="text-align: center; color: green;">        GeeksforGeeks    </h1>     <h3 style="text-align: center;">        D3.js | linkHorizontal() Method    </h3>     <center>    <svg id="gfg" width="200" height="200"></svg>    </center>     <script>         var data = [            {source: [100,25], target: [200,175]},            {source: [100,25], target: [25,175]}];               // Horizontal link generator        var link = d3.linkHorizontal()                .source(function(d) {                    return [d.source[1], d.source[0]];                })                .target(function(d) {                    return [d.target[1], d.target[0]];                });               //Adding the link paths        d3.select("#gfg")        .selectAll("path")        .data(data)        .join("path")        .attr("d", link)        .classed("link", true);     </script></body> </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Node.js | fs.writeFileSync() Method
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
MomentJS - Is Same or After

This method checks if the moment is same or after another moment. It returns true or false.
moment().isSameOrAfter(Moment|String|Number|Date|Array);
moment().isSameOrAfter(Moment|String|Number|Date|Array, String);

var issameorafter = moment('2017-10-10').isSameOrAfter('2017-10-09');
We can use the units with isSameOrAfter() and the ones supported are year, month, week , day, hour, minute and second.
var issameorafter = moment('2017-10-10').isSameOrAfter('2017-10-09', 'year');
var issameorafter = moment('2017-10-10').isSameOrAfter('2017-10-15', 'day');
 Print
 Add Notes
 Bookmark this page
How to change the spacing between ticks in Matplotlib?

To set ticks on a fixed position or change the spacing between ticks in matplotlib, we can take the following steps −
Create a figure and add a set of subplots.
Create a figure and add a set of subplots.
To set the ticks on a fixed position, create two lists with some values.
To set the ticks on a fixed position, create two lists with some values.
Use set_yticks and set_xticks methods to set the ticks on the axes.
Use set_yticks and set_xticks methods to set the ticks on the axes.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
xtick_loc = [0.20, 0.75, 0.30]
ytick_loc = [0.12, 0.80, 0.76]
ax.set_xticks(xtick_loc)
ax.set_yticks(ytick_loc)
plt.show()
HTTP headers | Server-Timing - GeeksforGeeks

27 Sep, 2021
The HTTP Server-Timing header is a response-type header. This header is used to communicate between two or more metrics and descriptions for a given request-response cycle from the user agent. The HTTP Server-Timing header is useful to any back-end server timing metrics like read or write in any databases, accessing files, etc. It can be used in the developer tools to keep track of the server on the PerformanceServerTiming interface. The HTTP Server-Timing helps to perform in different ways to communicate with the metrics, those are listed below: 
metrics name
metric with value
metric with description
metric with value and description
Syntax:  
Server-Timing: metricsname| metricsvalue | metricsdescription
Directives: There are no directives only need to mention the metrics name with all the details. 
Example: 
This example shows the single metrics. 
Server-Timing: cdn-cache
This example shows the single metrics with the value. 
Server-Timing: edge; dur=33
This example shows the single metrics with description. 
Server-Timing: cdn-cache; desc=HIT
This example shows the double metrics with description and value. 
Server-Timing: cdn-cache; desc=HIT, edge; dur=1
To check this Server-Timing in action go to Inspect Element -> Network check the response header for Server-Timing like below, Server-Timing is highlighted.  
Supported Browsers: The browsers compatible with HTTP headers Server-Timing are listed below: 
Google Chrome
Firefox
Safari
Opera
 
arorakashish0911
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?
How to execute PHP code using command line ?
REST API (Introduction)
Computer Networks | Set 8 - GeeksforGeeks

27 Mar, 2017
Following questions have been asked in GATE CS 2008 exam.
1) What is the maximum size of data that the application layer can pass on to the TCP layer below?(A) Any size(B) 2^16 bytes-size of TCP header(C) 2^16 bytes(D) 1500 bytes
Answer (A)Application layer can send any size of data. There is no limit defined by standards. The lower layers divides the data if needed.
2) A client process P needs to make a TCP connection to a server process S. Consider the following situation: the server process S executes a socket(), a bind() and a listen() system call in that order, following which it is preempted. Subsequently, the client process P executes a socket() system call followed by connect() system call to connect to the server process S. The server process has not executed any accept() system call. Which one of the following events could take place?(A) connect () system call returns successfully(B) connect () system call blocks(C) connect () system call returns an error(D) connect () system call results in a core dump
Answer (C)Since accept() call is not executed then connect () gets no response for a time stamp to wait & then return no response server error.
3) A computer on a 10Mbps network is regulated by a token bucket. The token bucket is filled at a rate of 2Mbps. It is initially filled to capacity with 16Megabits. What is the maximum duration for which the computer can transmit at the full 10Mbps?(A) 1.6 seconds(B) 2 seconds(C) 5 seconds(D) 8 seconds
Answer (B)
New tokens are added at the rate of r bytes/sec which is 
2Mbps in the given question. 

Capacity of the token bucket (b) = 16 Mbits
Maximum possible transmission rate (M) = 10Mbps
So the maximum burst time = b/(M-r) = 16/(10-2) = 2 seconds

In the above formula, r is subtracted from M to calculate the maximum burst time. The reason for this subtraction is, new tokens are added at the rate of r while transmission happens at maximum transmission rate M.
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above
GATE-CS-2008
Computer Networks
GATE CS
MCQ
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Caesar Cipher in Cryptography
Socket Programming in Python
UDP Server-Client implementation in C
Differences between IPv4 and IPv6
Socket Programming in Java
ACID Properties in DBMS
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Normal Forms in DBMS
Difference between Process and Thread
What is Java String literal?

Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.
You can also create a String directly as −
String greeting = "Hello world!";

A string literal should be enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.
 Live Demo
public class StringDemo {
   public static void main(String args[]) {
      String str = "Hello world!";
      System.out.println( str );
   }
}
Hello world!
What is an optimistic concurrency control in DBMS?

All data items are updated at the end of the transaction, at the end, if any data item is found inconsistent with respect to the value in, then the transaction is rolled back.
Check for conflicts at the end of the transaction. No checking while the transaction is executing. Checks are all made at once, so low transaction execution overhead. Updates are not applied until end-transaction. They are applied to local copies in a transaction space.
The optimistic concurrency control has three phases, which are explained below −
Various data items are read and stored in temporary variables (local copies). All operations are performed in these variables without updating the database.
All concurrent data items are checked to ensure serializability will not be validated if the transaction updates are actually applied to the database. Any changes in the value cause the transaction rollback. The transaction timestamps are used and the write-sets and read-sets are maintained.
To check that transaction A does not interfere with transaction B the following must hold −
TransB completes its write phase before TransA starts the read phase.
TransB completes its write phase before TransA starts the read phase.
TransA starts its write phase after TransB completes its write phase, and the read set of TransA has no items in common with the write set of TransB.
TransA starts its write phase after TransB completes its write phase, and the read set of TransA has no items in common with the write set of TransB.
Both the read set and write set of TransA have no items in common with the write set of TransB and TransB completes its read before TransA completes its read Phase.
Both the read set and write set of TransA have no items in common with the write set of TransB and TransB completes its read before TransA completes its read Phase.
The transaction updates applied to the database if the validation is successful. Otherwise, updates are discarded and transactions are aborted and restarted. It does not use any locks hence deadlock free, however starvation problems of data items may occur.
S: W1(X), r2(Y), r1(Y), r2(X).
T1 -3
T2 – 4
Check whether timestamp ordering protocols allow schedule S.
Initially for a data-item X, RTS(X)=0, WTS(X)=0
Initially for a data-item Y, RTS(Y)=0, WTS(Y)=0
For W1(X) : TS(Ti)<RTS(X) i.e.
   TS(T1)<RTS(X)
TS(T1)<WTS(X)
3<0 (FALSE)
=>goto else and perform write operation w1(X) and WTS(X)=3
For r2(Y): TS(T2)<WTS(Y)
   4<0 (FALSE)
=>goto else and perform read operation r2(Y) and RTS(Y)=4
For r1(Y) :TS(T1)<WTS(Y)
   3<0 (FALSE)
=>goto else and perform read operation r1(Y).
For r2(X) : TS(T2)<WTS(X)
   4<3 (FALSE)
=>goto else and perform read operation r2(X) and RTS(X)=4
Bootstrap .btn-sm class

To create a small button in Bootstrap, use the .btn-sm class.
You can try to run the following code to implement the btn-sm class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <meta name = "viewport" content = "width=device-width, initial-scale = 1">
      <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <button type = "button" class = "btn btn-default btn-sm">
         Small button
      </button>
      <button type = "button" class = "btn btn-default btn-sm">
         Result
      </button>
   </body>
</html>
Normal Equation of Linear Regression | by Aerin Kim | Towards Data Science

Kyle is interviewing Cartman for a data scientist position. Cartman is a graduate student studying CS at Stanford.
Kyle: Ok, let’s start with an easy question. Derive the linear regression from scratch. We have about 30 data points of housing price (y) and the size of houses (x).
Cartman: Sure!
Kyle: Good. Now, how will you solve this?
Cartman: I’ll use the gradient descent.
Kyle: Hmmm... Why?
Cartman: That’s how we solve the optimization problem.
Kyle: Can you think of other reasons why we would use G.D.?
Cartman: ......
You don’t have to use the gradient descent in this case because there is a closed-form solution for Linear Regression, aka the Normal Equation. I think some people automatically go for Gradient Descent to solve Linear Regression because when we first learn about GD, our first implementation to practice is always linear regression. :-) However, Gradient Descent is definitely an overkill for Linear Regression when the sample size is relatively small.
Kyle: Can you derive the normal equation?
Kyle: Wrong!
Cartman: 😱
Kyle: Above derivation is just a shortcut, not a legit answer to the question. Let’s derive it thoroughly using the definition of Linear Regression — minimizing squared error between the prediction and the truth label.
The reason why we might use Gradient Descent in Linear Regression is because it might be computationally cheaper to find optima. Though in this case of sample size 30, Cartman could just have derived the closed form on the whiteboard.
Why is Gradient Descent computationally cheaper, compared to the normal equation?
Take a look at the normal equation that we just derived. It has the matrix inversion in it and inverting a matrix is an expensive operation. The design matrix X has k+1 columns where k is the number of predictors (x1, x2, x3,...) and m rows of samples (in our case 30). In real life, k is easily greater than 1,000 and the sample size will be greater than 100k. Since the matrix inversion is (O(n3)), inverting X′X (1,000 by 1,000 matrix) could take a while to calculate.
Win extra points: When we use the Gradient Descent, we need to scale the data. When we use the Normal Equation, we don’t need to. 👍
Python code for implementation addicts:
def normalEqn(X,y):    """     Computes the closed-form solution to linear regression    """    theta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)    return theta
How to create a progress bar in HTML?

Use the <progress> tag to create a progress bar in HTML. The HTML <progress> tag specifies a completion progress of a task. It is displayed as a progress bar. The value of progress bar can be manipulated by JavaScript.
The following are the attributes −
You can try to run the following code to learn how to create a progress bar in a web page −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Progress Tag</title>
   </head>
   <body>
      <h1>Loading</h1>
      <progress value = "65" max = "100"/>
   </body>
</html>
Groovy - for-in statement

The for-in statement is used to iterate through a set of values. The for-in statement is generally used in the following way.
for(variable in range) { 
   statement #1 
   statement #2 
   ... 
}

The following diagram shows the diagrammatic explanation of this loop.
Following is an example of a for-in statement −
class Example { 
   static void main(String[] args) { 
      int[] array = [0,1,2,3]; 
		
      for(int i in array) { 
         println(i); 
      } 
   } 
}
In the above example, we are first initializing an array of integers with 4 values of 0,1,2 and 3. We are then using our for loop statement to first define a variable i which then iterates through all of the integers in the array and prints the values accordingly. The output of the above code would be −
0 
1 
2 
3

The for-in statement can also be used to loop through ranges. The following example shows how this can be accomplished.
class Example {
   static void main(String[] args) {
	
      for(int i in 1..5) {
         println(i);
      }
		
   } 
} 
In the above example, we are actually looping through a range which is defined from 1 to 5 and printing the each value in the range. The output of the above code would be −
1 
2 
3 
4 
5 

The for-in statement can also be used to loop through Map’s. The following example shows how this can be accomplished.
class Example {
   static void main(String[] args) {
      def employee = ["Ken" : 21, "John" : 25, "Sally" : 22];
		
      for(emp in employee) {
         println(emp);
      }
   }
}
In the above example, we are actually looping through a map which has a defined set of key value entries. The output of the above code would be −
Ken = 21 
John = 25 
Sally = 22 


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
How can we change the resolution of a video in OpenCV using C++?

We used 'set()' class of OpenCV. Using 'set()' class, we can set the height and width of the frames. The following lines are setting the height and width of the video in our program.
set(CAP_PROP_FRAME_WIDTH, 320);
set(CAP_PROP_FRAME_HEIGHT, 240);
The first line is setting the width of the frames into 320 pixel and the second line is setting the height of the frames to 240 pixels. These two lines together is forming a 320 x 240 resolution video stream. This is how we can simply change the resolution of video using OpenCV.
The following program changes the resolution of the video stream taken from default camera −
#include<opencv2/opencv.hpp>//OpenCV header to use VideoCapture class//
#include<iostream>
using namespace std;
using namespace cv;
int main() {
   Mat myImage;//Declaring a matrix to load the frames//
   namedWindow("Video Player");//Declaring the video to show the video//
   VideoCapture cap(0);//Declaring an object to capture stream of frames from default camera//
   cap.set(CAP_PROP_FRAME_WIDTH, 320);//Setting the width of the video
   cap.set(CAP_PROP_FRAME_HEIGHT, 240);//Setting the height of the video//
   if (!cap.isOpened()){ //This section prompt an error message if no video stream is found//
      cout << "No video stream detected" << endl;
      system("pause");
      return-1;
   }
   while (true){ //Taking an everlasting loop to show the video//
      cap >> myImage;
      if (myImage.empty()){ //Breaking the loop if no video frame is detected//
         break;
      }
      imshow("Video Player", myImage);//Showing the video//
      char c = (char)waitKey(25);//Allowing 25 milliseconds frame processing time and initiating break condition//
      if (c == 27){ //If 'Esc' is entered break the loop//
         break;
      }
   }
   cap.release();//Releasing the buffer memory//
   return 0;
}
This program will play the video at 320 x 240 resolution.
norm() function in C++ with Examples

In this article we will be discussing the working, syntax and examples of norm() function in C++ STL.
norm() function is an inbuilt function in C++ STL, which is defined in <complex> header file. norm() function is used to get the norm value of a complex number.
Norm value of a complex number is the squared magnitude of a number. So in simple words the function finds the squared magnitude of a complex number, including its imaginary and real number.
double norm(ArithmeticType num);
The function accepts following parameter(s) −
num − The complex value which we want to work on.
This function returns a norm value of num.
complex<double> comp_num(6.9, 2.6);
norm(comp_num);
The value of norm of (6.9,2.6) is 54.37
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main (){
   complex<double> comp_num(6.9, 2.6);
   cout<<"The value of norm of " << comp_num<< " is ";
   cout << norm(comp_num) << endl;
   return 0;
}
The value of norm of (6.9,2.6) is 54.37
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main (){
   complex<double> comp_num(2.4, 1.9);
   cout<<"The value of norm of " << comp_num<< " is ";
   cout << norm(comp_num) << endl;
   return 0;
}
The value of norm of (2.4,1.9) is 9.37
Find sum of all elements in a matrix except the elements in row and-or column of given cell in Python

Suppose we have a 2D matrix and a set of cell indexes. Cell indices are represented as (i, j) where i is row and j is column, now, for every given cell index (i, j), we have to find the sums of all matrix elements excluding the elements present in ith row and/or jth column.
So, if the input is like
cell indices = [(0, 0), (1, 1), (0, 1)], then the output will be [19, 14, 20]
To solve this, we will follow these steps −
n := size of ind_arr
n := size of ind_arr
ans := a new list
ans := a new list
for i in range 0 to n, doSum := 0row := ind_arr[i, 0]col := ind_arr[i, 1]for j in range 0 to row count of mat, dofor k in range 0 to column count of map, doif j is not same as row and k is not same as col, thenSum := Sum + mat[j, k]insert Sum at the end of ans
for i in range 0 to n, do
Sum := 0
Sum := 0
row := ind_arr[i, 0]
row := ind_arr[i, 0]
col := ind_arr[i, 1]
col := ind_arr[i, 1]
for j in range 0 to row count of mat, dofor k in range 0 to column count of map, doif j is not same as row and k is not same as col, thenSum := Sum + mat[j, k]
for j in range 0 to row count of mat, do
for k in range 0 to column count of map, doif j is not same as row and k is not same as col, thenSum := Sum + mat[j, k]
for k in range 0 to column count of map, do
if j is not same as row and k is not same as col, thenSum := Sum + mat[j, k]
if j is not same as row and k is not same as col, then
Sum := Sum + mat[j, k]
Sum := Sum + mat[j, k]
insert Sum at the end of ans
insert Sum at the end of ans
return ans
return ans
Let us see the following implementation to get better understanding −
 Live Demo
def show_sums(mat, ind_arr):
   n = len(ind_arr)
   ans = []
   for i in range(0, n):
      Sum = 0
      row = ind_arr[i][0]
      col = ind_arr[i][1]
      for j in range(0, len(mat)):
         for k in range(0, len(mat[0])):
            if j != row and k != col:
               Sum += mat[j][k]
      ans.append(Sum)
   return ans
mat = [[2, 2, 3], [4, 5, 7], [6, 4, 3]]
ind_arr = [(0, 0),(1, 1),(0, 1)]
print(show_sums(mat, ind_arr))
mat = [[2, 2, 3], [4, 5, 7], [6, 4, 3]] ind_arr = [(0, 0),(1, 1),(0, 1)
[19, 14, 20]
SQL Tryit Editor v1.6

CREATE TABLE Persons (
    ID int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255) NOT NULL,
    Age int
);
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Difference between Tree Set and Hash Set in Java

Hash set and tree set both belong to the collection framework. HashSet is the implementation of the Set interface whereas Tree set implements sorted set. Tree set is backed by TreeMap while HashSet is backed by a hashmap.
class TreeSetExmaple {
   public static void main(String[] args){
      TreeSet<String> treeset = new TreeSet<String>();
      treeset.add("Good");
      treeset.add("For");
      treeset.add("Health");
      //Add Duplicate Element
      treeset.add("Good");
      System.out.println("TreeSet : ");
      for (String temp : treeset) {
         System.out.println(temp);
      }
   }
}
TreeSet:
   For
   Good
   Health
class HashSetExample {
   public static void main(String[] args){
      HashSet<String> hashSet = new HashSet<String>();
      hashSet.add("Good");
      hashSet.add("For");
      hashSet.add("Health");
      //Add Duplicate Element
      hashSet.add("Good");
      System.out.println("HashSet: ");
      for (String temp : hashSet) {
         System.out.println(temp);
      }
   }
}
HashSet:
   Health
   For
   Good
Recursion in array to find odd numbers and push to new variable JavaScript

We are required to write a recursive function, say pushRecursively(), which takes in an array of
numbers and returns an object containing odd and even properties where odd is an array of odd
numbers from input array and even an array of even numbers from input array. This has to be
done using recursion and no type of loop method should be used.
const arr = [12,4365,76,43,76,98,5,31,4];
const pushRecursively = (arr, len = 0, odd = [], even = []) => {
   if(len < arr.length){
      arr[len] % 2 === 0 ? even.push(arr[len]) : odd.push(arr[len]);
      return pushRecursively(arr, ++len, odd, even);
   };
   return {
      odd,
      even
   }
};
console.log(pushRecursively(arr));
While the len variable reaches the end of array, we keep calling the function recursively, each
time pushing the odd values to odd array and the evens to even array and once the len variable
equals the length of array, we exit out of the function returning the object.
The output of this code in the console will be −
{ odd: [ 4365, 43, 5, 31 ], even: [ 12, 76, 76, 98, 4 ] }
How to declare boolean variables in JavaScript?

A boolean variable in JavaScript has two values True or False.
You can try to run the following code to learn how to work with Boolean variables −
<!DOCTYPE html>
<html>
   <body>
      <p>35 > 20</p>
      <button onclick="myValue()">Click for result</button>
      <p id="test"></p>
      <script>
         function myValue() {
            document.getElementById("test").innerHTML = Boolean(35 > 20);
         }
      </script>
   </body>
</html>
How to add a method to a JavaScript object?

Adding a method to a javascript object is easier than adding a method to an object constructor. We need to assign the method to the existing property to ensure task completion.
In the following example, initially, the object type is created and later on, the properties of the object were created. Once the creation of properties is done, a method is assigned to each of the objects and the properties were accessed using the method as our requirement.
Live Demo
<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
   }
   var person1 = new Business("Trump", "$28.05billion", "73", "President");
   var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
   person1.det = function() {
      return this.Name + " "+" has a property of net worth "+ "" + this.prop;
   };
   person2.det = function() {
      return this.Name + " "+" has a property of net worth "+ "" + this.prop;
   };
   document.write(person2.det() +" and "+person1.det());
</script>
</body>
</html>
Jackma has a property of net worth $35.6 billion and Trump has a property of net worth $28.05billion
How can we show/hide the table header of a JTable in Java?

A JTable is a subclass of JComponent class for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. The DefaultTableModel class is a subclass of AbstractTableModel and it can be used to add the rows and columns to a JTable dynamically. The DefaultTableCellRenderer class can extend JLabel class and it can be used to add images, colored text and etc. inside the JTable cell. We can hide the table header of a JTable by unchecking the JCheckBox and show the table header of a JTable by clicking the JCheckBox.
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public final class JTableHeaderHideTest extends JPanel {
   private final String[] columnNames = {"String", "Integer", "Boolean"};
   private final Object[][] data = {{"Tutorials Point", 100, true}, {"Tutorix", 200, false},          {"Tutorials Point", 300, true}, {"Tutorix", 400, false}};
   private final TableModel model = new DefaultTableModel(data, columnNames) {
      @Override
      public Class getColumnClass(int column) {
         return getValueAt(0, column).getClass();
      }
   };
   private final JTable table = new JTable(model);
   private final JScrollPane scrollPane = new JScrollPane(table);
   public JTableHeaderHideTest() {
      super(new BorderLayout());
      add(scrollPane);
      JCheckBox check = new JCheckBox("JTableHeader visible: ", true);
      check.addActionListener(ae -> {
         JCheckBox cb = (JCheckBox) ae.getSource();
         scrollPane.getColumnHeader().setVisible(cb.isSelected());
         scrollPane.revalidate();
      });
      add(check, BorderLayout.NORTH);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("JTableHeaderHide Test");
      frame.setSize(375, 250);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new JTableHeaderHideTest());
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
Removing minimize/maximize buttons in Tkinter

When we run our tkinter application, it initially displays a window that has an interface to display all the widgets. Eventually, we can remove the maximizing and minimizing property of the displayed window by using the resizable(boolean) method. It takes two Boolean values that refer to the status of width and height of the window. We generally disable the max and min resizing property by assigning zero to both values of width and height.
#Import the required library
from tkinter import*
#Create an instance of tkinter frame
win= Tk()
#Set the geometry
win.geometry("750x250")
#Disable the resizable Property
win.resizable(False, False)
#Create an Label Widget
Label(win, text= "This Window can't be resized", font= ('Helvetica 15
underline')).pack(pady=20)
win.mainloop()
Running the above code will display a non-resizable window.
How to  join two strings to convert to a single string in Python?

To join 2 strings in Python, we can use the concatenation operator, '+'. For example:
str1 = "Hello"
str2 = "World"
str3 = str1 + str2
print str3
This will give us the output:
HelloWorld
We can also use str.join(seq) to join multiple strings together. For example:
s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
This will give us the output:
a-b-c
Note that the str we give is used as the seperator when joining the strings together.
Creating Classes in Python

The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows −
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data attributes and functions.
Following is the example of a simple Python class −
class Employee:
   'Common base class for all employees'
   empCount = 0
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   def displayCount(self):
      print "Total Employee %d" % Employee.empCount
   def displayEmployee(self):
      print "Name : ", self.name, ", Salary: ", self.salary
The variable empCount is a class variable whose value is shared among all instances of a this class. This can be accessed as Employee.empCount from inside the class or outside the class.
The first method __init__ is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.
You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.
CakePHP - File upload

To work on file upload we are going to use the form helper. Here, is an example for file upload.
Make Changes in the config/routes.php file, as shown in the following program.
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('fileupload',['controller'=>'Files','action'=>'index']);
   $builder->fallbacks();
});
Create a FilesController.php file at src/Controller/FilesController.php. Copy the following code in the controller file. Ignore, if already created.
Create uploads/ directory in src/. The files uploaded will be saved in uploads/ folder.
<?php
   namespace App\Controller;
   use App\Controller\AppController;
   use Cake\View\Helper\FormHelper;
   class FilesController extends AppController {
      public function index(){
         if ($this->request->is('post')) {
            $fileobject = $this->request->getData('submittedfile');
            $uploadPath = '../uploads/';
            $destination = $uploadPath.$fileobject->getClientFilename();
            // Existing files with the same name will be replaced.
            $fileobject->moveTo($destination);
         }
      }
   }
?>
Create a directory Files at src/Template and under that directory create a View file called index.php. Copy the following code in that file.
<?php
   echo $this->Form->create(NULL, ['type' => 'file']);
   echo $this->l;Form->file('submittedfile');
   echo $this->Form->button('Submit');
   echo $this->Form->end();
   $uploadPath ='../uploads/';
   $files = scandir($uploadPath, 0);
   echo "Files uploaded in uploads/ are:<br/>";
   for($i = 2; $i < count($files); $i++)
      echo "File is - ".$files[$i]."<br>";
?>
The files saved in uploads/ folder is listed for the user. Execute the above example by visiting the following URL −
http://localhost/cakephp4/fileupload −
When you execute the above code, you should see the following output −
 Print
 Add Notes
 Bookmark this page
Node Jimp | rotate - GeeksforGeeks

19 Feb, 2021
Introduction The rotate() function is an inbuilt function in Nodejs | Jimp which rotates the image clockwise and the dimensions of the image remain same.Syntax:  
rotate(r, mode, cb)
Parameter:  
r – This parameter stores the rotation angle for the image.
mode – This is optional parameter which stores the scaling method.
cb – This is optional parameter which is invoked when compilation is complete.
Input Images:  
 
npm init -y
npm install jimp --save
Example 1: 
javascript
// npm install --save jimp// import jimp library to the environmentvar Jimp = require('jimp'); // User-Defined Function to read the imagesasync function main() {  const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png'); // rotate Function having a rotation as 55  image.rotate(55)  .write('rotate1.png');} main();  console.log("Image Processing Completed");
Output:  
Example 2: With mode and cb (optional parameters) 
javascript
// npm install --save jimp// import jimp library to the environmentvar Jimp = require('jimp'); // User-Defined Function to read the imagesasync function main() {    const image = await Jimp.read('https://media.geeksforgeeks.org/wp-content/uploads/20190328185333/gfg111.png'); // rotate Function having rotation angle as 99, mode and callback function    image.rotate(99, Jimp.RESIZE_BEZIER, function(err){        if (err) throw err;    })        .write('rotate2.png');} main();  console.log("Image Processing Completed");
Output:  
Reference: https://www.npmjs.com/package/jimp 
mridulmanochagfg
Image-Processing
Node-Jimp
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python - Smallest K values in Dictionary - GeeksforGeeks

17 Dec, 2019
Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Let’s discuss several ways in which this task can be performed.
Method #1 : itemgetter() + items() + sorted()The combination of above method is used to perform this particular task. In this, we just sort the dictionary values expressed using itemgetter() and accessed using items().
# Python3 code to demonstrate working of# Smallest K values in Dictionary# Using sorted() + itemgetter() + items()from operator import itemgetter  # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'geeks' : 3 }  # Initialize K K = 2  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Smallest K values in Dictionary# Using sorted() + itemgetter() + items()res = dict(sorted(test_dict.items(), key = itemgetter(1))[:K])  # printing resultprint("The minimum K value pairs are " + str(res))
The original dictionary is : {'geeks': 3, 'is': 4, 'for': 7, 'best': 6, 'gfg': 1}
The minimum K value pairs are {'geeks': 3, 'gfg': 1}

 
Method #2 : Using nsmallest()This task can be performed using the nsmallest function. This is inbuilt function in heapq library which internally performs this task and can be used to do it externally. Has the drawback of printing just keys not values.
# Python3 code to demonstrate working of# Smallest K values in Dictionary# Using nsmallestfrom heapq import nsmallest  # Initialize dictionarytest_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'geeks' : 3 }  # Initialize KK = 2  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Smallest K values in Dictionary# Using nsmallestres = nsmallest(K, test_dict, key = test_dict.get)  # printing resultprint("The minimum K value pairs are " + str(res))
The original dictionary is : {'geeks': 3, 'best': 6, 'is': 4, 'gfg': 1, 'for': 7}
The minimum K value pairs are ['gfg', 'geeks']

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
D3.js | d3.entries() Function - GeeksforGeeks

03 May, 2021
Disclaimer: in version 6 of D3.js function d3.entries got deprecated. Object.entries should be used instead.
The d3.entries function in D3.js is used to return an array containing the property names and property values of the specified object.Syntax:  
d3.entries(object)
Parameters: the function accepts a single parameter — a JavaScript object.Return Value: It returns an array containing the property names and values of the specified object.The programs below illustrate the d3.entries function in D3.js:Example 1:  
javascript
<!DOCTYPE html><html>     <head>    <title> d3.entries() function</title>             <script src='https://d3js.org/d3.v4.min.js'></script></head><body>     <script>           // Initialising an object     var month = {"January": 1, "February": 2, "March": 3};                // Calling the d3.entries() function     A = d3.entries(month);            // Getting the key and value in pairs     console.log(A);  </script></body></html>
Output:  
[{"key":"January","value":1},{"key":"February","value":2},
                                       {"key":"March","value":3}]
Example 2:  
javascript
<!DOCTYPE html><html>     <head>    <title> d3.entries function</title>             <script src='https://d3js.org/d3.v4.min.js'></script></head><body>  <script>           // Initialising an object     var month = {"GeeksforGeeks": 0, "Geeks": 2,                                     "Geek": 3, "gfg": 4};                // Calling the d3.entries function     A = d3.entries(month);            // Getting the key and value in pairs.     console.log(A);  </script></body></html>
Output:  
[{"key":"GeeksforGeeks","value":0},{"key":"Geeks","value":2},
                     {"key":"Geek","value":3},{"key":"gfg","value":4}]
Reference: https://devdocs.io/d3~5/d3-collection#entries 
anfauglit
D3.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
How to fetch data from an API in ReactJS ?
What is REST API in Node.js ?
Node.js fs.readFileSync() Method
How to remove underline for anchors tag using CSS?
How to set the default value for an HTML <select> element ?
Node.js | fs.writeFileSync() Method
How to randomly select rows of an array in Python with NumPy ? - GeeksforGeeks

25 Feb, 2021
 In this article, we will see two different methods on how to randomly select rows of an array in Python with NumPy. Let’s see different methods by which we can select random rows of an array:
Method 1: We will be using the function shuffle(). The shuffle() function shuffles the rows of an array randomly and then we will display a random row of the 2D array.
Python3
# import modulesimport randomimport numpy as np  # create 2D arraydata = np.arange(50).reshape((5, 10))  # display original arrayprint("Array:")print(data)  # row manipulationnp.random.shuffle(data)  # display random rowsprint("\nRandom row:")rows = data[:1, :]print(rows)
Output:
Method 2: First create an array, then apply the sample() method to it and display a single row.
Python3
# import modulesimport randomimport numpy as np  # create 2D arraydata = np.arange(50).reshape((5, 10))  # display original arrayprint("Array:")print(data)  # row manipulationrows_id = random.sample(range(0,                               data.shape[1]-1), 1)  # display random rowsprint("\nRandom row:")row = data[rows_id, :]print(row)
Output:
Method 3: We will be using the function choice(). The choices() method returns multiple random elements from the list with replacement. 
Now lets, select rows from the list of random integers that we have created.
Python3
# import modulesimport randomimport numpy as np  # create 2D arraydata = np.arange(50).reshape((5, 10))  # display original arrayprint("Array:")print(data)  # row manipulationnumber_of_rows = data.shape[0]random_indices = np.random.choice(number_of_rows,                                   size=1,                                   replace=False)  # display random rowsprint("\nRandom row:")row = data[random_indices, :]print(row)
Output:
Picked
Python numpy-program
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()