code-rag-bench/online-tutorials huggingface dataset:
ArrayDeque removeLast() Method in Java - GeeksforGeeks

10 Dec, 2018
The Java.util.ArrayDeque.removeLast() method is used to remove the last element of the Deque.
Syntax:
Array_Deque.removeLast()
Parameters: The method does not take any parameters.
Return Value: This method returns the last element of the Deque after removing it.
Exceptions: The method throws NoSuchElementException if the deque is empty.
Below programs illustrate the Java.util.ArrayDeque.removeLast() method:
Program 1:
// Java code to illustrate removeLast()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<String> de_que = new ArrayDeque<String>();          // Use add() method to add elements into the Deque        de_que.add("Welcome");        de_que.add("To");        de_que.add("Geeks");        de_que.add("For");        de_que.add("Geeks");          // Displaying the ArrayDeque        System.out.println("Initial ArrayDeque: " + de_que);          // Removing elements using removeLast() method        de_que.removeLast();        de_que.removeLast();        de_que.removeLast();          // Displaying the ArrayDeque after removal        System.out.println("ArrayDeque after removing "                           + "elements: " + de_que);    }}
Initial ArrayDeque: [Welcome, To, Geeks, For, Geeks]
ArrayDeque after removing elements: [Welcome, To]

Program 2:
// Java code to illustrate removeLast()import java.util.*;  public class ArrayDequeDemo {    public static void main(String args[])    {        // Creating an empty ArrayDeque        Deque<Integer> de_que = new ArrayDeque<Integer>();          // Use add() method to add elements into the Deque        de_que.add(10);        de_que.add(15);        de_que.add(30);        de_que.add(20);        de_que.add(5);          // Displaying the ArrayDeque        System.out.println("Initial ArrayDeque: " + de_que);          // Removing elements using removeLast() method        de_que.removeLast();        de_que.removeLast();          // Displaying the ArrayDeque after removal        System.out.println("ArrayDeque after removing "                           + "elements: " + de_que);    }}
Initial ArrayDeque: [10, 15, 30, 20, 5]
ArrayDeque after removing elements: [10, 15, 30]

Java - util package
Java-ArrayDeque
Java-Collections
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
How to use a variable inside a Foreach-Object Parallel?

There are two different types of the variable we can use inside foreach parallel loop. One that is declared inside and the other that is declared outside of the foreach parallel loop.
Please note − We are discussing here Foreach-Object Parallel loop, featured in PowerShell version 7. For a normal foreach loop inside and outside variables are the same.
Variable declared inside the Foreach parallel loop can be used directly with its name. For example,
$vms = "TestVm1","TestVM2","TestVm3"
$Vms | ForEach-Object -Parallel{
   $var1 = $_
   Write-Output "Testing VM: $var1"
}
Testing VM: TestVm1
Testing VM: TestVM2
Testing VM: TestVm3
In the above example, $var1 is declared inside the foreach parallel loop and we can use it directly by its name as shown. But the below example, $log variable declared outside the foreach parallel loop we can use it inside the loop with $Using keyword followed by the variable name.
$vms = "TestVm1","TestVM2","TestVm3"
$log = "Application"
$Vms | ForEach-Object -Parallel{
   $var1 = $_
   Write-Output "Checking $($using:log) on $var1"
}
Checking Application on TestVm1
Checking Application on TestVM2
Checking Application on TestVm3
In the above example, $using:log variable is used inside the foreach parallel loop is a $log variable.
Regular Expression in C# with Examples

A regular expression is a pattern that could be matched against an input text. The .Net framework provides a regular expression engine that allows such matching.
Let’s see how to split a regular expression.
To split a string using regular expression, use the Regex.split.
Let’s say our string is −
string str = "Hello\r\nWorld";
Now use Regex.split to split the string as shown below −
string[] res = Regex.Split(str, "\r\n");
The following is the complete code to split a string using Regular Expression in C# −
using System;
using System.Text.RegularExpressions;

class Demo {
   static void Main() {
      string str = "Hello\r\nWorld";

      string[] res = Regex.Split(str, "\r\n");

      foreach (string word in res) {
         Console.WriteLine(word);
      }
   }
}
Let us now see an example to remove extra whitespace.
using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   class Program {
      static void Main(string[] args) {
         string input = "Hello World ";
         string pattern = "\\s+";
         string replacement = " ";

         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);
   
         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String: {0}", result);
         Console.ReadKey();
      }
   }
}
Arduino - If â¦else statement

An if statement can be followed by an optional else statement, which executes when the expression is false.
if (expression) {
   Block of statements;
}
else {
   Block of statements;
}

/* Global variable definition */
int A = 5 ;
int B = 9 ;

Void setup () {

}

Void loop () {
   /* check the boolean condition */
   if (A > B) /* if condition is true then execute the following statement*/ {
      A++;
   }else {
      B -= A;
   }
}

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Arduino - Temperature Sensor

The Temperature Sensor LM35 series are precision integrated-circuit temperature devices with an output voltage linearly proportional to the Centigrade temperature.
The LM35 device has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from the output to obtain convenient Centigrade scaling. The LM35 device does not require any external calibration or trimming to provide typical accuracies of ±1⁄4°C at room temperature and ±3⁄4°C over a full −55°C to 150°C temperature range.
Calibrated directly in Celsius (Centigrade)
Linear + 10-mV/°C scale factor
0.5°C ensured accuracy (at 25°C)
Rated for full −55°C to 150°C range
Suitable for remote applications
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × LM35 sensor
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New.
float temp;
int tempPin = 0;

void setup() {
   Serial.begin(9600);
}

void loop() {
   temp = analogRead(tempPin);
   // read analog volt from sensor and save to variable temp
   temp = temp * 0.48828125;
   // convert the analog volt to its temperature equivalent
   Serial.print("TEMPERATURE = ");
   Serial.print(temp); // display temperature value
   Serial.print("*C");
   Serial.println();
   delay(1000); // update sensor reading each one second
}
LM35 sensor has three terminals - Vs, Vout and GND. We will connect the sensor as follows −
Connect the +Vs to +5v on your Arduino board.
Connect Vout to Analog0 or A0 on Arduino board.
Connect GND with GND on Arduino.
The Analog to Digital Converter (ADC) converts analog values into a digital approximation based on the formula ADC Value = sample * 1024 / reference voltage (+5v). So with a +5 volt reference, the digital approximation will be equal to input voltage * 205.
You will see the temperature display on the serial port monitor which is updated every second.

    65 Lectures 
     6.5 hours 

 Amit Rana

    43 Lectures 
     3 hours 

 Amit Rana

    20 Lectures 
     2 hours 

 Ashraf Said

    19 Lectures 
     1.5 hours 

 Ashraf Said

    11 Lectures 
     47 mins

 Ashraf Said

    9 Lectures 
     41 mins

 Ashraf Said
 Print
 Add Notes
 Bookmark this page
Difference between Preprocessor Directives and Function Templates in C++ - GeeksforGeeks

05 Jan, 2021
Preprocessor Directives are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++.
Below is the program to illustrate the functionality of Function Templates:
C++
// C++ program to illustrate// preprocessor directives#include <bits/stdc++.h>  #define min(a, b) ((a < b) ? a : b)  using namespace std;  // Driver codeint main(){    int a = 2, b = 4;      // Find the minimum of a and b    cout << "Minimum of both is: "         << min(a, b);      return 0;}
Minimum of both is: 2

Function Templates are the generic function that can handle different data types without the need for any separate code.
Below is the program to illustrate the functionality of Function Templates:
C++
// C++ program to illustrate the use// of Function Templates#include <iostream>#include <stdio.h>using namespace std;  // Function Templatetemplate <class T>T Min(T x, T y){    return (x < y) ? x : y;}  // Driver Codeint main(){    int a = 4, b = 8;      // Find the minimum of a and b    cout << "Minimum of both is: " << min(a, b);      return 0;}
Minimum of both is: 4

Function templates are used to make generic functions that can work with any data type. For example, the function template used for calculating the minimum of 2 values of any type can be defined as:
template <class T>
T minimum(T a, T b)
{
   return (a < b) ? a : b;
}
But, this task can also be performed using Pre-processor directives created using preprocessor directive #define. So, the minimum of the two numbers can be defined as as:
#define minimum(a, b) ((a < b) ? a : b)
The Pre-processor directives can also be achieved by using the below statements:
minimum(30, 35);
minimum(30.5, 40.5);
In C++, most of us prefer using templates over Pre-processor directives because:
In the case of Pre-processor directives, there is no type checking. But in the case of templates, full type checking is done by the compiler.
Pre-processor directives can call an unexpected result. Consider a macro that calculates the square of any number as:
#define sqr(x) (x*x)
Now if this macro is called using the following statement, x = sqr(4 + 4); then expected output is 64 but it generates 24 because any x in macro body replaced by 4 + 4 which leads to x = 4 + 4 * 4 + 4 = 24 but in the case of templates, such unexpected results are not obtained.
Below is the tabular difference between the two:
Templates
Articles
C++
C++ Programs
Difference Between
Programming Language
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Time Complexity and Space Complexity
Docker - COPY Instruction
Time complexities of different data structures
Types of Server Virtualization in Computer Network
SQL | Date functions
Vector in C++ STL
Arrays in C/C++
Inheritance in C++
Iterators in C++ STL
Initialize a vector in C++ (6 different ways)
Depth First Search In Undirected Graphs | by Diego Castillo | Towards Data Science

Chapter 3 and 4 of the book Algorithms by S. Dasgupta, C. H. Papadimitriou, and U. V. Vazirani focus on graphs. A graph is specified as a set of vertices V (or nodes) and edges E between selected pairs of vertices. One of the big advantages of using graphs is that graphs provide clarity when solving problems, since they are not cluttered with irrelevant information, just the mathematical object.
A graph with n=|V| vertices v1,...,vn can be represented as a matrix (an array of n x n), whose (i, j)th entry is:
1 if there is an edge from vi to vj
0 otherwise
In a matrix representation of a graph, the presence of a particular edge can be inspected in constant time, but it requires O(n^2) of memory space, which can be wasteful if the graph does not have many edges. Another representation of a graph is an adjacency list. It consists of |V| linked lists (one per vertex). Then, the linked list for vertex u holds the names of vertices which u has and outgoing edge. In contrast to the matrix representation, verifying the presence of a particular edge is now linear (by running down the corresponding linked list), but the memory required to store the graph is O(|E|).
A graph can be classified by the number of edges it has as:
A dense graph: the number of edges is close to the maximum number of edges the graph can have
A sparse graph: the number of edges is close to the minimal number of edges the graph can have
This is important since it plays a big role when selecting a proper data structure and algorithm to use when working with graphs. For instance, for storing the World Wide Web as graph (a Web page is a vertex, and it has edges to all the other Web pages it has a hyper-link to), it is more convenient to use an adjacency list because the World Wide Web graph is very sparse (the average Web page has hyper-links to only about half a dozen other pages, out of billions of possibilities).
The first algorithm the author examines in Chapter 3 is depth first search in undirected graphs. In a undirected graph, vertices that are connected together have bidirectional edges.
Depth first search is a linear time algorithm which essentially answers the following question:
What parts of the graph are reachable from a given vertex?
The following implementation of the depth first search algorithm uses an adjacency list and returns all vertices of a graph which are reachable from the specified vertex.
procedure DFS(G,v):  label v as discovered  for all edges from v to w in G.adjacentEdges(v) do    if vertex w is not labeled as discovered then      recursively call DFS(G,w)
Depth first search is an interesting algorithm, and as you might suspect, it is particularly well suited for inspecting if a graph is connected; if the tree returned by depth first search contains all vertices in the graph, it is connected, otherwise, it is not.
How to add a button to an image with CSS?

Following is the code to add a button to an image with CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
img{
   width: 100%;
}
div {
   position: relative;
   width: 100%;
   max-width: 400px;
}
div img {
   width: 100%;
   height: auto;
}
div button {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   background-color: rgb(64, 21, 133);
   color: white;
   font-size: 20px;
   padding: 24px 36px;
   width: 220px;
   border: none;
   cursor: pointer;
   border-radius: 5px;
   text-align: center;
   font-weight: bolder;
   font-family: monospace,sans-serif,serif;
}
div button:hover {
   color:yellow;
}
</style>
</head>
<body>
<h1>Button on Image Example</h1>
<div>
<img src="https://i.picsum.photos/id/354/400/400.jpg">
<button class="btn">Button</button>
</div>
</body>
</html>
The above code will produce the following output −
On hovering over the button, the button will change color as shown −
Overriding Vs Shadowing in C#

Under overriding, you can define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.
Let us see an example of abstract classes that implements Overriding −
using System;

namespace PolymorphismApplication {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }

      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }

   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(10, 7);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}
Shadowing is also known as method hiding. The method of the parent class is available to the child class without using the override keyword in shadowing. The child class has its own version of the same function.
Use the new keyword to perform shadowing and to create the own version of the base class function.
Let us see an example −
using System;
using System.Collections.Generic;

class Demo {
   public class Parent {
      public string Display() {
         return "Parent Class!";
      }
   }
   
   public class Child : Parent {
      public new string Display() {
         return "Child Class!";
      }
   }

   static void Main(String[] args) {
      Child child = new Child();
      Console.WriteLine(child.Display());
   }
}
ES6 - Array Method slice()

slice() method extracts a section of an array and returns a new array.
array.slice( begin [,end] );    

begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence.
begin − Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence.
end − Zero-based index at which to end extraction.
end − Zero-based index at which to end extraction.
Returns the extracted array based on the passed parameters.
var arr = ["orange", "mango", "banana", "sugar", "tea"]; 
console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) );
console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) );   
arr.slice( 1, 2) : mango 
arr.slice( 1, 3) : mango,banana


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
Add padding to the image with Python - Pillow - GeeksforGeeks

16 Mar, 2021
Prerequisites: Pillow(python library)
Padding is the space between the contents, the container, and the border. An image can be considered content to some container and extra padding can be added to it. This article depicts how this can be done.  Padding can be added by straightaway supplying the values for the side to be padded. These values can then be passed to the function to create a new image.
This module is not preloaded with Python. So to install it execute the following command in the command-line:
pip install pillow
Import module
Open image
Set values for padding
Set different dimensions for image
Pass the padding values to the image
Save new image
Input Image:
Program :
Python3
from PIL import Image  image = Image.open("input.jpg")  right = 100left = 100top = 100bottom = 100  width, height = image.size  new_width = width + right + leftnew_height = height + top + bottom  result = Image.new(image.mode, (new_width, new_height), (0, 0, 255))  result.paste(image, (left, top))  result.save('output.jpg')
Output:
The output generated is just the input image with a padding added to it. Here it appears as a border, since the values given for each side were equal. For different values non-uniform padding can be observed.
Picked
Python-pil
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Decode Ways in Python

Suppose we have a message containing letters from A to Z is being encoded to numbers using the following mapping − 'A' → 1, 'B' → 2 ... 'Z' → 26. So if we have one non-empty string, containing only digits, then we have to find, in how many ways that can be decoded. So if the string is like “12”, then that can be made from “AB”, or “L”, so there are two possible ways. So the answer will be 2.
To solve this, we will follow these steps −
We will solve this using dynamic programming.
n := length of s
dp := an array with n number of 0s
if s[0] is not ‘0’, then dp[0] := 1
for i in range 1 to n – 1x := s[i] as integer, y := substring of s from index i – 1 to i + 1 as integerif x >= 1 and y <= 9, then dp[i] := dp[i] + dp[i – 1]if y >= 10 and y <= 26if i – 2 >= 0, then dp[i] := dp[i] + dp[i – 2], otherwise increase dp[i] by 1
x := s[i] as integer, y := substring of s from index i – 1 to i + 1 as integer
if x >= 1 and y <= 9, then dp[i] := dp[i] + dp[i – 1]
if y >= 10 and y <= 26if i – 2 >= 0, then dp[i] := dp[i] + dp[i – 2], otherwise increase dp[i] by 1
if i – 2 >= 0, then dp[i] := dp[i] + dp[i – 2], otherwise increase dp[i] by 1
return last element of dp
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def numDecodings(self, s):
      n = len(s)
      dp = [0 for i in range(n)]
      if s[0]!='0':
         dp[0]=1
      for i in range(1,n):
         x = int(s[i])
         y = int(s[i-1:i+1])
         if x>=1 and x<=9:
            dp[i]+=dp[i-1]
         if y>=10 and y<=26:
            if i-2>=0:
               dp[i]+=dp[i-2]
            else:
               dp[i]+=1
      return dp[-1]
ob1 = Solution()
print(ob1.numDecodings("226"))
"226"
3
5 Advanced String Methods in Python | by Yaakov Bressler | Towards Data Science

Formatting strings are a basic yet essential part of programming. F-Strings (introduced in Python3.6) improve the simplicity and intuitiveness of formatting rich strings.
F-String notation (formatted strings) require an f at the start of a string (ex. f”hello”). There are many advanced methods available for formatting beautiful strings, 5 such methods are discussed below.
Insert/replace a variable in place.
name = "Alexander Hamilton"print(f"hello {name}")# hello Alexander Hamilton
Format a variable such as an integer in place.
x = 2*10**5print(f"You have ${x:,} in your bank account")# You have $200,000 in your bank account
pi = 3.1415926535897932384 print(f"The first 5 digits of pi are {pi:.5f}")# The first 5 digits of pi are 3.14159
Perhaps you want to format a string based on several conditions. F-string notation allows for in place boolean arguments, just as you would expect from lambdas.
new_user = Falseuser_name = "Alexander Hamilton"print(f"{'Congrats on making your account' if new_user else 'Welcome back'} {user_name}!")# Welcome back Alexander Hamilton!
As of python 3.8, f-string notation allows printing of variable names with their values — an especially useful tool for debugging:
max_price = 20000min_price = 4000print(f"{max_price=:,}  |  {min_price=:,})# max_price=20,000  |  min_price=4,000
String formatting allows replacement of variables in pre-populated strings.
This is especially useful for allowing external users to format an email message which the program will fill in.
my_message = "Welcome to our platform {FNAME}! Your favorite ice cream flavor is {FLAVOR}."FNAME = "Alexander"FLAVOR = "Mint Chocolate Chip"my_message_formatted = my_message.format(**{"FNAME":FNAME, "FLAVOR":FLAVOR})print(my_message_formatted)# Welcome to our platform Alexander! Your favorite ice cream flavor is Mint Chocolate Chip.
Here’s one instance where f string notation falls short (simply because it’s intended to be used in code...)
my_message = "Welcome to our platform {FNAME}! Your favorite ice cream flavor is {FLAVOR}."FNAME = "Alexander"FLAVOR = "Mint Chocolate Chip"my_message_formatted = eval(f”f’{my_message}’”)print(my_message_formatted)# Welcome to our platform Alexander! Your favorite ice cream flavor is Mint Chocolate Chip.
F-string notation is a simple way to format beautiful strings. Demonstrated above are 5 advanced methods for formatting strings in python3.8.
Consider implementing these methods into your python code.
If you have additional noteworthy string methods, please share them in the comments!
What is lexical this in JavaScript?

Fat arrow function solves the issue of lexical binding “this”. It gets the context of “this “and you can fulfill the same purpose since fast arrow does not have its own this. Fat arrow function as the name suggests helps in decreasing line of code. The syntax => shows fat arrow.
$('.button1').click(function () {
   setTimeout(function () {
      $(this).text('demo');
   } ,400);
});
The above gives an error since the function() defines this as a global object. Let’s see how to solve it using fat arrow function and the context of “this” −
$('.button1').click(function () {
   setTimeout( () => {
      $(this).text(‘demo’) }
  ,400);
});
VBA - IsDate Function

A Function, which returns a Boolean value whether or not the given input is a date.
IsDate(expression)

Add a button and add the following function.
Private Sub Constant_demo_Click()
   msgbox("Line 1 : " & IsDate("Nov 03, 1950"))
   msgbox("Line 2 : " & IsDate(#01/31/20#))
   msgbox("Line 3 : " & IsDate(#05/31/20 10:30 PM#))
End Sub
When you execute the above function, it produces the following output.
Line 1 : True
Line 2 : True
Line 3 : True 


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Print BST keys in the given range in C++

In this problem, we are given two nodes of a binary search tree. And we have to print all the values in the range of k1 to k2 that occur in the tree. That is we have to print all the values that are greater than k1 and smaller than k2. And we have to print all these keys in increasing order of their values.
Binary Search Tree is a tree which follows these 3 properties −
The left subtree has nodes with values lesser than the node’s value.
The left subtree has nodes with values lesser than the node’s value.
The right subtree has a node with values greater than the node’s value.
The right subtree has a node with values greater than the node’s value.
A subtree’s taken should also be a binary search tree. No duplicate nodes are allowed in the tree.
A subtree’s taken should also be a binary search tree. No duplicate nodes are allowed in the tree.
Example,
Let’s take an example to understand the topic better,
Input : k1 = 12 and k2 = 25.
Output : 15, 20, 24
Tree -
Explanation − On traversing the tree, all elements will be traversed and the elements that lie between the range 12 to 25 i.e. for a node x, 12 ≤ x ≥ 25 will be printed.
Here, we will use the properties of BST to find our solution. i.e. all elements in the left subtree are smaller than root and all elements in the right subtree are greater than the root node. And we will use in order traversal of the BST to solve this problem. Now, let's create an algorithm to solve this problem.
Step 1 : Compare the root node with the k1 and k2.
Step 2 : If root is greater than k1. Call left subtree for the search recursively.
Step 3 : If root is smaller than k2. Call right subtree for the search recursively.
Step 4 : If the root of the tree is in the range. Then print the root’s value.
Now, based on this algorithm, let’s create a program to solve the problem.
#include<bits/stdc++.h>
using namespace std;
class node{
   public:
      int data;
      node *left;
      node *right;
};
void nodesInRange(node *root, int k1, int k2){
   if ( NULL == root )
      return;
   if ( k1 < root->data )
      nodesInRange(root->left, k1, k2);
   if ( k1 <= root->data && k2 >= root->data )
      cout<<root->data<<"\t";
   if ( k2 > root->data )
      nodesInRange(root->right, k1, k2);
}
node* insert(int data){
   node *temp = new node();
   temp->data = data;
   temp->left = NULL;
   temp->right = NULL;
   return temp;
}
int main(){
   node *root = new node();
   int k1 = 12, k2 = 25;
   root = insert(20);
   root->left = insert(10);
   root->right = insert(24);
   root->left->left = insert(8);
   root->left->right = insert(15);
   root->right->right = insert(32);
   cout<<”The values of node within the range are\t”;
   nodesInRange(root, k1, k2);
   return 0;
}
The values of node within the range are 15 20 24.
Tryit Editor v3.6 - Show Python

f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
​
#open and read the file after the appending:
f = open("demofile3.txt", "r")
numpy.correlate() function - Python - GeeksforGeeks

11 Jun, 2020
numpy.correlate() function defines the cross-correlation of two 1-dimensional sequences. This function computes the correlation as generally defined in signal processing texts: c_{av}[k] = sum_n a[n+k] * conj(v[n])
Syntax : numpy.correlate(a, v, mode = ‘valid’)
Parameters :a, v : [array_like] Input sequences.mode : [{‘valid’, ‘same’, ‘full’}, optional] Refer to the convolve docstring. Default is ‘valid’.
Return : [ndarray] Discrete cross-correlation of a and v.
Code #1 :
# Python program explaining# numpy.correlate() function       # importing numpy as geek import numpy as geek    a = [2, 5, 7]v = [0, 1, 0.5]   gfg = geek.correlate(a, v)   print (gfg)
Output :
[8.5]

 Code #2 :
# Python program explaining# numpy.correlate() function       # importing numpy as geek import numpy as geek    a = [2, 5, 7]v = [0, 1, 0.5]   gfg = geek.correlate(a, v, "same")   print (gfg)
Output :
[4.5 8.5 7. ]

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()
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
How to find the status of an element in a page in Selenium with python?

We can find the status of an element in a page with the help of Selenium. We can get the information if an element is enabled or disabled. Also, we can verify if an element is visible on screen for the user interaction or not.
On a web page, there may be numerous checkboxes or radio buttons. Selenium provides a method to check if these UI elements are in a selected state or not.
There are multiple methods to verify the status of an element. They are listed below −
is_selected()This method verifies whether an element (checkbox, radio button) is in selected condition or not. A Boolean value of either TRUE or FALSE is returned.
is_selected()
This method verifies whether an element (checkbox, radio button) is in selected condition or not. A Boolean value of either TRUE or FALSE is returned.
Syntax −
driver.find_element_by_class_name("prom").is_selected()
is_dispayed()This method verifies whether an element is visible for users or not. A Boolean value of either TRUE or FALSE is returned.
is_dispayed()
This method verifies whether an element is visible for users or not. A Boolean value of either TRUE or FALSE is returned.
Syntax −
driver.find_element_by_class_name("prom").is_displayed()
is_enabled()This method verifies whether an element is in enabled status or not. A Boolean value of either TRUE or FALSE is returned.
is_enabled()
This method verifies whether an element is in enabled status or not. A Boolean value of either TRUE or FALSE is returned.
Syntax −
driver.find_element_by_class_name("prom-user").is_enabled()
Code Implementation with the above methods.
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
# identifying the checkbox with xpath
chk =driver.find_element_by_xpath("//*[@value='Automation Tester']")
# printing the status in console
print(chk.is_selected())
# identifying the edit box with xpath
edt =driver.find_element_by_xpath("//*[@name='firstname']")
# printing the display status in console
print(edt.is_displayed())
# identifying the edit box with xpath
edtsts =driver.find_element_by_xpath("//*[@name='lastname']")
# printing the enabled status in console
print(edtsts.is_enabled())
#to close the browser
driver.close()
MySQL AND, OR, NOT Operators

The WHERE clause can be combined with 
AND, OR, and 
NOT operators.
The AND and OR operators are used to filter records based on more than one 
condition:
The AND operator displays a record if all the conditions separated by 
  AND 
  are TRUE.
The OR operator displays a record if any of the conditions separated by 
  OR is TRUE.
The NOT operator displays a record if the condition(s) is NOT TRUE.
The table below shows the complete "Customers" table from the Northwind sample database:
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city is "Berlin":
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "Stuttgart":
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
You can also combine the AND, 
OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city must be "Berlin" 
OR "Stuttgart" (use parenthesis to form complex expressions):
The following SQL statement selects all fields from "Customers" where country is 
NOT "Germany" and NOT "USA":
Select all records where the City column has the value 'Berlin' and the PostalCode column has the value 12209.
 * FROM Customers
 City = 'Berlin'
  = 12209;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to run Flask App on Google Colab? - GeeksforGeeks

01 Feb, 2021
Flask is a web framework in python language. This means flask provides you with tools, libraries and technologies that allow you to build a web application. This web application can be some web pages, a blog, a wiki or go as big as a web-based calendar application or a machine learning webapp.
Google Colab provides a VM(virtual machine) so we cannot access the localhost(all it does it route it to our local machine’s localhost) as we do on our local machine when running a local web server. What we can do is expose it to a public URL using ngrok. Here comes the Python library flask-ngrok.
To create google colab file go to this link:
https://colab.research.google.com/notebooks/intro.ipynb#recent=true
1) Create new notebook in google colab
2) Install library in google colab
!pip install flask-ngrok
Flask is already install on google colab so you don’t need to install it again.
3) After that lets create a simple flask app
Python3
from flask import Flaskfrom flask_ngrok import run_with_ngrokapp = Flask(__name__)run_with_ngrok(app)     @app.route("/")def home():    return "<h1>GFG is great platform to learn</h1>"    app.run()
4) To run the code on google colab press shift+enter.
Output:
Click on this link to get the output:
Python Flask
Python Framework
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Intuition of Adam Optimizer
ML | Logistic Regression using Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Program to find Nth Fibonacci Number in Python

Suppose we have a number n, we have to find the nth Fibonacci term. As we know the ith Fibonacci term f(i) = f(i-1) + f(i-2), the first two terms are 0, 1.
So, if the input is like 15, then the output will be 610
To solve this, we will follow these steps −
first := 0, second := 1
for i in range 2 to n, dotemp := first + secondfirst := secondsecond := temp
temp := first + second
first := second
second := temp
return second
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, n):
      first = 0
      second = 1
      for _ in range(2, n+1):
         temp = first + second
         first = second
         second = temp
      return second
ob = Solution()
print(ob.solve(15))
15
610
Any & All in Python?

Python provides two built-ins functions for “AND” and “OR” operations are All and Any functions.
The any() function returns True if any item in an iterable are true, otherwise it returns False. However, if the iterable object is empty, the any () function will return False.
any(iterable)
The iterable object can be a list, tuple or dictionary.
>>> mylst = [ False, True, False]
>>> x = any(mylst)
>>> x
True
Output
Output is True because the second item is True.
Tuple – check if any item is True
>>> #Tuple - check if any item is True
>>> mytuple = (0, 1, 0, False)
>>> x = any(mytuple)
>>> print(x)
True
Set – Check if any item is True
>>> myset = {0, 1, 0 }
>>> x = any(myset)
>>> print(x)
True
Dictionary – check if any item is true in dictionary
>>> mydict = { 0 : "Apple", 1: "Banana"}
>>> x = any(mydict)
>>> print(x)
True
any() returns:
True – if atleast one item of the iterable is True.
True – if atleast one item of the iterable is True.
False – if all the items are False or if an iterable is empty.
False – if all the items are False or if an iterable is empty.
The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function all returns True.
all(iterable)
The iterable object can be list, tuple or dictionary.
Example1 List- Check if all items are True
>>> mylst = [True, True, False]
>>> x = all(mylst)
>>> print(x)
False
Above result shows False, as one of the item in the list is False.
Example 2 Tuple – Check if all items are True in tuple
>>> mytuple = (0, True, False)
>>> x = all(mytuple)
>>> print(x)
False
Example 3: Set – check if all items are True in Set.
>>> myset = {True, 1, 1}
>>> x = all(myset)
>>> print(x)
True
Example 4: Dictionary – check if all item are true in dictionary
>>> mydict = {0: "Apple", 1:"Banana"}
>>> x = all(mydict)
>>> print(x)
False
The all() method returns
True – if all elements in an iterable are true
True – if all elements in an iterable are true
False – if any element in an iterable is false
False – if any element in an iterable is false
SQL - SELF JOINS

The SQL SELF JOIN is used to join a table to itself as if the table were two tables; temporarily renaming at least one table in the SQL statement.
The basic syntax of SELF JOIN is as follows −
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;

Here, the WHERE clause could be any given expression based on your requirement.
Consider the following table.
CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows −
SQL> SELECT  a.ID, b.NAME, a.SALARY
   FROM CUSTOMERS a, CUSTOMERS b
   WHERE a.SALARY < b.SALARY;
This would produce the following result −
+----+----------+---------+
| ID | NAME     | SALARY  |
+----+----------+---------+
|  2 | Ramesh   | 1500.00 |
|  2 | kaushik  | 1500.00 |
|  1 | Chaitali | 2000.00 |
|  2 | Chaitali | 1500.00 |
|  3 | Chaitali | 2000.00 |
|  6 | Chaitali | 4500.00 |
|  1 | Hardik   | 2000.00 |
|  2 | Hardik   | 1500.00 |
|  3 | Hardik   | 2000.00 |
|  4 | Hardik   | 6500.00 |
|  6 | Hardik   | 4500.00 |
|  1 | Komal    | 2000.00 |
|  2 | Komal    | 1500.00 |
|  3 | Komal    | 2000.00 |
|  1 | Muffy    | 2000.00 |
|  2 | Muffy    | 1500.00 |
|  3 | Muffy    | 2000.00 |
|  4 | Muffy    | 6500.00 |
|  5 | Muffy    | 8500.00 |
|  6 | Muffy    | 4500.00 |
+----+----------+---------+


    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Node.js MySQL Count() Function - GeeksforGeeks

07 Oct, 2021
We use the COUNT() function in MySQL to count a number of rows in a column satisfying the WHERE clause.
Syntax:
COUNT([column_name])
Parameters: COUNT() function accepts a single parameter as mentioned above and described below.
column_name: Column’s name from which we have to return the count value.
Module Installation: Install the mysql module using the following command:
npm install mysql
Database: Our SQL publishers table preview with sample data is shown below:
Example 1: Count publishers having id greater than 5
index.js
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // Here is the query    let query = "SELECT COUNT(id) AS id_count FROM publishers WHERE id > 5";      db_con.query(query, (err, rows) => {        if(err) throw err;          console.log(rows);    });});
Run the index.js file using the following command:
node index.js
Output:
Example 2:
index.js
const mysql = require("mysql");  let db_con  = mysql.createConnection({    host: "localhost",    user: "root",    password: '',    database: 'gfg_db'});  db_con.connect((err) => {    if (err) {      console.log("Database Connection Failed !!!", err);      return;    }      console.log("We are connected to gfg_db database");      // Here is the query    let query = "SELECT COUNT(salary) AS salary_count FROM                  publishers WHERE salary BETWEEN 5000 AND 10000";      db_con.query(query, (err, rows) => {        if(err) throw err;          console.log(rows);    });});
Run the index.js file using the following command:
node index.js
Output:
NodeJS-MySQL
Technical Scripter 2020
Node.js
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
How to build a basic CRUD app with Node.js and ReactJS ?
Difference between npm i and npm ci in Node.js
How to connect Node.js with React.js ?
Mongoose find() Function
Node.js Export Module
Node.js fs.createReadStream() Method
Difference Between Array and Pointer

In this post, we will understand the difference between arrays and pointers.
It stores value of a variable that has a homogeneous data type.
It stores value of a variable that has a homogeneous data type.
It can generate an array of pointers.
It can generate an array of pointers.
It supports the array concept.
It supports the array concept.
An array of pointers can be generated.
An array of pointers can be generated.
It refers to a collection that consists of elements of homogenous/same data type.
It refers to a collection that consists of elements of homogenous/same data type.
It uses subscripts/ ‘[ ]’ (square brackets) to access the elements.
It uses subscripts/ ‘[ ]’ (square brackets) to access the elements.
It is a pointer that points to the first element of the collection.
It is a pointer that points to the first element of the collection.
The array objects can’t be instantiated.
The array objects can’t be instantiated.
The size of array is fixed based on the number of elements in the array.
The size of array is fixed based on the number of elements in the array.
This size is the product of number of elements and size of every element.
This size is the product of number of elements and size of every element.
Bit field is not possible in an array.
Bit field is not possible in an array.
It is considered as a primitive data type.
It is considered as a primitive data type.
Traversing through and searching for elements in an array is quick and easy.
Traversing through and searching for elements in an array is quick and easy.
It can be declared using the ‘[ ]’.
It can be declared using the ‘[ ]’.
Array size is fixed and is basically the number of elements multiplied by the size of an element.
Array size is fixed and is basically the number of elements multiplied by the size of an element.
It is stored in contiguous memory locations.
It is stored in contiguous memory locations.
In C++, it can be declared as follows −
type var_name[size];
In Java, it can be declared as follows −
type var-name[ ];
var_name = new type[size];
It stores address of variables.
It stores address of variables.
It can only store address of one variable at a point in time.
It can only store address of one variable at a point in time.
A pointer to an array can be generated.
A pointer to an array can be generated.
It can be initialized to any value.
It can be initialized to any value.
It can be initialized any time after its declaration.
It can be initialized any time after its declaration.
It can be assigned to point to a NULL value.
It can be assigned to point to a NULL value.
It can be dereferenced using the ‘*’ operator.
It can be dereferenced using the ‘*’ operator.
It can be changed to point to a different variable of the same type only.
It can be changed to point to a different variable of the same type only.
int val = 5;
//code//
int *p = &val;
How to set minimum size limit for a JFrame in Java

Use the setMinimumSize() method to set the minimum size limit for a JFrame −
JFrame frame = new JFrame();
frame.setMinimumSize(new Dimension(500, 300));
The following is an example to set minimum size limit for a JFrame −
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JButton button = new JButton("Close!");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(button);
      button.addActionListener(e -> {
         frame.dispose();
      });
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setMinimumSize(new Dimension(500, 300));
      frame.getContentPane().setBackground(Color.ORANGE);
      frame.pack();
      frame.setVisible(true);
   }
}