code-rag-bench/online-tutorials huggingface dataset:
Pafy – Getting Thumbnail

20 Jul, 2020
In this article we will see how we can get the thumbnail of the given youtube video in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Thumbnails are reduced-size versions of pictures or videos, used to help in recognizing and organizing them, serving the same role for images as a normal text index does for words.
We can get the pafy object with the help of new method, below is the command to get the pafy object for given video
video = pafy.new(url)
The video url should exist on youtube as it get the information of those videos which are present on the youtube. YouTube is an American online video-sharing platform.
In order to do this we use thumb attribute with the pafy object of video
Syntax : video.thumb
Argument : It takes no argument
Return : It returns string which is link of big thumbnail
Below is the implementation
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = vG2PNdI8axo"    # getting videovideo = pafy.new(url)   # getting thumbnail of the videovalue = video.thumb  # printing the valueprint("Thumbnail : " + value)
Output :
Thumbnail : http://i.ytimg.com/vi/vG2PNdI8axo/default.jpg

When we open this link, image given below appears
Another example
# importing pafyimport pafy     # url of video url = "https://www.youtube.com / watch?v = vVSKoLJmn8w&t = 13s"    # getting videovideo = pafy.new(url)   # getting thumbnail of the videovalue = video.thumb  # printing the valueprint("Thumbnail : " + value)
Output :
Thumbnail : http://i.ytimg.com/vi/i6rhnSoK_gc/default.jpg

Python-Pafy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Create a directory in Python
How to Use Callable Statement in Java to Call Stored Procedure?

16 Sep, 2021
The CallableStatement of JDBC API is used to call a stored procedure. A Callable statement can have output parameters, input parameters, or both. The prepareCall() method of connection interface will be used to create CallableStatement object.
Following are the steps to use Callable Statement in Java to call Stored Procedure:
1) Load MySQL driver and Create a database connection.
import java.sql.*;
public class JavaApplication1 {
   public static void main(String[] args) throws Exception
   {
       Class.forName(“com.mysql.jdbc.Driver”);
       Connection con=DriverManager.getConnection(“jdbc:mysql://localhost/root”,”geek”,”geek”);  
   }  
}
2) Create a SQL String
We need to store the SQL query in a String.
String sql_string=”insert into student values(?,?,?)”;
3) Create CallableStatement Object
The prepareCall() method of connection interface will be used to create CallableStatement object. The sql_string will be passed as an argument to the prepareCall() method.
CallableStatement cs = con.prepareCall(sql_string);
4) Set The Input Parameters
Depending upon the data type of query parameters we can set the input parameter by calling setInt() or setString() methods.
cs.setString(1,”geek1′′);
cs.setString(2,”python”);
cs.setString(3,”beginner”);
5) Call Stored Procedure
Execute stored procedure by calling execute() method of CallableStatement class.
Example of using Callable Statement in Java to call Stored Procedure
Java
// Java program  to use Callable Statement// in Java to call Stored Procedure package javaapplication1; import java.sql.*; public class JavaApplication1 {     public static void main(String[] args) throws Exception    {        Class.forName("com.mysql.jdbc.Driver");               // Getting the connection        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/root", "acm", "acm");               String sql_string = "insert into students values(?a,?,?)";               // Preparing a CallableStateement        CallableStatement cs = con.prepareCall(sql_string);               cs.setString(1, "geek1");        cs.setString(2, "python");        cs.setString(3, "beginner");        cs.execute();        System.out.print("uploaded successfully\n");    }}
Output: 
students table after running code
 
adnanirshad158
JDBC
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)

11 May, 2022
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples:
Input : s1 = ABHISHEKsinGH
      : s2 = gfhfBHkooIHnfndSHEKsiAnG
Output : Possible

Input : s1 = Hello
      : s2 = dnaKfhelddf
Output : Not Possible

Input : s1 = GeeksforGeeks
      : s2 = rteksfoGrdsskGeggehes
Output : Possible
We have existing solution for this problem please refer Make a string from another by deletion and rearrangement of characters link. We will this problem quickly in python. Approach is very simple,
Convert both string into dictionary using Counter(iterable) method, each dictionary contains characters within string as Key and their frequencies as Value.Now take intersection of two dictionaries and compare resultant output with dictionary of first string, if both are equal that means it is possible to convert string otherwise not.
Convert both string into dictionary using Counter(iterable) method, each dictionary contains characters within string as Key and their frequencies as Value.
Now take intersection of two dictionaries and compare resultant output with dictionary of first string, if both are equal that means it is possible to convert string otherwise not.
Python3
# Python code to find if we can make first string# from second by deleting some characters from# second and rearranging remaining characters.from collections import Counter def makeString(str1,str2):     # convert both strings into dictionaries    # output will be like str1="aabbcc",    # dict1={'a':2,'b':2,'c':2}    # str2 = 'abbbcc', dict2={'a':1,'b':3,'c':2}    dict1 = Counter(str1)    dict2 = Counter(str2)     # take intersection of two dictionaries    # output will be result = {'a':1,'b':2,'c':2}    result = dict1 & dict2     # compare resultant dictionary with first    # dictionary comparison first compares keys    # and then compares their corresponding values    return result == dict1 # Driver programif __name__ == "__main__":    str1 = 'ABHISHEKsinGH'    str2 = 'gfhfBHkooIHnfndSHEKsiAnG'    if (makeString(str1,str2)==True):        print("Possible")    else:        print("Not Possible")
Output:
Possible
Akanksha_Rai
surinderdawra388
Python dictionary-programs
python-dict
python-string
Python
Strings
python-dict
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Constructors

03 May, 2022
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor may also contain the group of instructions or a method which will execute at the time of object creation.
Constructors are used to initialize the instance variables.
In Ruby, the constructor has a different name, unlike other programming languages.
A constructor is defined using the initialize and def keyword.
It is treated as a special method in Ruby.
Constructor can be overloaded in Ruby.
Constructors can’t be inherited.
It returns the instance of that class.
Note: Whenever an object of the class is created using new method, internally it calls the initialize method on the new object. Also, all the arguments passed to new will automatically pass to method initialize. 
Syntax:
class Class_Name

   def initialize(parameter_list)

   end

end
Example: 
Ruby
# A Ruby program to demonstrate# the working of constructor #!/usr/bin/ruby   # class name class Demo       # constructor    def initialize          puts "Welcome to GeeksforGeeks!"      end   end    # Creating ObjectDemo.new
Output:
Welcome to GeeksforGeeks!
Initializing instance variable: Instance variables can be initialized using constructor. Inside the constructor, the initial value to instance variables is provided which can be used further anywhere in the program. 
Example: 
Ruby
# Ruby program to initialize instance# variable using constructor #!/usr/bin/ruby # class nameclass Geeks         # constructor    def initialize                 # instance variable initialization        @inst_1 = "GeeksforGeeks"        @inst_2 = "Sudo Placement"    end         # display method    def display        puts "Value of First instance variable is: #{@inst_1}"        puts "Value of Second instance variable is: #{@inst_2}"    endend # creating objectobj1 = Geeks.new() # calling display methodobj1.display()
Output:
Value of First instance variable is: GeeksforGeeks
Value of Second instance variable is: Sudo Placement
sweetyty
sagartomar9927
Ruby-OOP
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby For Beginners
Ruby | String capitalize() Method
How to Create Navigation Links using HTML5 ?

14 Jul, 2020
In this article, we create a navigation link by using the <nav> tag in the document. The nav element represents a section of the page whose purpose is to provide navigational links, either in the current document or to other documents. The links in the “nav” element may point to other webpages or to different sections of the same webpage. It is a semantic element. Common examples of the “nav” elements are menus, tables, contents, and indexes.
Syntax:
<nav>
    Links...
</nav>

Example:
<!DOCTYPE html><html>  <head>    <title>        How to create navigation         links using HTML5 ?    </title>      <style>        .gfg {            font-size: 40px;            color: #090;            font-weight: bold;            text-align: center;        }          .nav_tag {            text-align: center;            margin: 30px 0;            font-size: 35px;        }    </style></head>  <body>    <div class="gfg">        GeeksforGeeks    </div>      <div class="nav_tag">        How to create navigation         links using HTML5 ?    </div>          <nav>        <a href="#">C++</a> |        <a href="#">Java</a> |        <a href="#">PHP</a> |        <a href="#">Data Structure</a> |        <a href="#">Algorithm</a>    </nav></body>  </html>
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
How to select all child elements recursively using CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
How to use the SetValue(,) method of array class in C#?

The SetValue() method sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
Firstly, set the array.
Array arr = Array.CreateInstance(typeof(String), 6);
No set values to the element using the SetValue() method.
arr.SetValue("One", 0);
arr.SetValue("Two", 1);
arr.SetValue("Three", 3);
arr.SetValue("Four", 4);
arr.SetValue("Five", 5);
The following is an example showing the usage of SetValue() method in C#.
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Array arr = Array.CreateInstance(typeof(String), 6);
         arr.SetValue("One", 0);
         arr.SetValue("Two", 1);
         arr.SetValue("Three", 3);
         arr.SetValue("Four", 4);
         arr.SetValue("Five", 5);
         Console.WriteLine("Length {0}",arr.GetLength(0).ToString());
         Console.ReadLine();
      }
   }
}
Length 6
Missing Number in Python

Suppose we have a list of numbers from 0 to n. There is one number that is missing. We have to find the missing number in an efficient approach. So if A = [0, 1, 2, 3, 4, 5, 7, 8, 9], missing number is 6.
To solve this, we will use the binary search approach.
sort the list in ascending order
high = length of A, and low = 0
while low < high, domid = low + (high – low)/2if A[mid] > midhigh = midotherwiselow = mid + 1
mid = low + (high – low)/2
if A[mid] > midhigh = mid
high = mid
otherwiselow = mid + 1
low = mid + 1
return low
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def missingNumber(self, nums):
      """
      :type nums: List[int]
      :rtype: int
      """
      nums.sort()
      high = len(nums)
      low = 0
      while low<high:
         mid = low + (high-low)//2
         if nums[mid]>mid:
            high = mid
         else:
            low = mid+1
      return low
ob1 = Solution()
print(ob1.missingNumber([5,3,1,7,8,0,9,2,4]))
nums = [5,3,1,7,8,0,9,2,4]
6
Python OpenCV | cv2.rectangle() method

13 Aug, 2019
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rectangle() method is used to draw a rectangle on any image.
Syntax: cv2.rectangle(image, start_point, end_point, color, thickness)
Parameters:image: It is the image on which rectangle is to be drawn.start_point: It is the starting coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).end_point: It is the ending coordinates of rectangle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).color: It is the color of border line of rectangle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.thickness: It is the thickness of the rectangle border line in px. Thickness of -1 px will fill the rectangle shape by the specified color.
Return Value: It returns an image.
Image used for all the below examples:
Example #1:
# Python program to explain cv2.rectangle() method    # importing cv2 import cv2    # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'   # Reading an image in default modeimage = cv2.imread(path)   # Window name in which image is displayedwindow_name = 'Image'  # Start coordinate, here (5, 5)# represents the top left corner of rectanglestart_point = (5, 5)  # Ending coordinate, here (220, 220)# represents the bottom right corner of rectangleend_point = (220, 220)  # Blue color in BGRcolor = (255, 0, 0)  # Line thickness of 2 pxthickness = 2  # Using cv2.rectangle() method# Draw a rectangle with blue line borders of thickness of 2 pximage = cv2.rectangle(image, start_point, end_point, color, thickness)  # Displaying the image cv2.imshow(window_name, image) 
Output:
Example #2:
Using thickness of -1 px to fill the rectangle by black color.
# Python program to explain cv2.rectangle() method     # importing cv2 import cv2     # path path = r'C:\Users\Rajnish\Desktop\geeksforgeeks\geeks.png'    # Reading an image in grayscale modeimage = cv2.imread(path, 0)    # Window name in which image is displayedwindow_name = 'Image'   # Start coordinate, here (100, 50)# represents the top left corner of rectanglestart_point = (100, 50)   # Ending coordinate, here (125, 80)# represents the bottom right corner of rectangleend_point = (125, 80)   # Black color in BGRcolor = (0, 0, 0)   # Line thickness of -1 px# Thickness of -1 will fill the entire shapethickness = -1   # Using cv2.rectangle() method# Draw a rectangle of black color of thickness -1 pximage = cv2.rectangle(image, start_point, end_point, color, thickness)   # Displaying the image cv2.imshow(window_name, image) 
Output:
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spoofcheck – Domain Spoofer Checker in kali linux

21 Jul, 2021
Spoofcheck is a python based tool that is used to check whether the domain can be spoofed or not. This is the best tool for web developers who are creating websites and web applications and want to host on web servers. The script checks SPF and DMARC history of weak configurations and settings of the domain from the domain company. The tool also gives you an alert if the domain address has DMARC configuration that sends HTTP requests and HTTPS request on failed SPF/DKIM emails. This tool is based on the technique that the domains are spoofable if any of these two conditions become true Lack of SPF or DMARC record. The first condition states that check if SPF record never specifies ~all or -all on the domain address. The second condition states that check whether DMARC policy of the domain is set to p =none or p= nonexistent. The tool has the following dependencies dnspython, colorama, email protection lib, tldextract.
Step 1: Open your kali linux operating system and open the terminal of the operating system. Use the following command to install the tool.
git clone https://github.com/BishopFox/spoofcheck.git
cd spoofcheck
Step 2: The tool has been downloaded successfully in your kali Linux operating system. Now you have to install the requirements of the tool using the following command.
pip install -r requirements.txt
All the requirements had been downloaded and installed in your kali Linux operating system. Now we will see examples to use the tool.
Example: Use the spoofcheck tool to determine whether the domain can be spoofed or not.
./spoofcheck.py <domain>
You can see that we have entered the domain as google.com and after performing scanning the tool is reflecting that spoofing is not possible for google.com. This is how you can check on your own domain address or target. This tool is very helpful for web developers who are seeking domain addresses for their websites.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
UDP Server-Client implementation in C
Reduced Row Echelon Form (rref) Matrix in MATLAB

14 May, 2021
Reduced Row Echelon Form of a matrix is used to find the rank of a matrix and further allows to solve a system of linear equations. A matrix is in Row Echelon form if
All rows consisting of only zeroes are at the bottom.
The first nonzero element of a nonzero row is always strictly to the right of the first nonzero element of the row above it.
Example :
A matrix can have several row echelon forms. A matrix is in Reduced Row Echelon Form if
It is in row echelon form.
The first nonzero element in each nonzero row is a 1.
Each column containing a nonzero as 1 has zeros in all its other entries.
Example:
Where a1,a2,b1,b2,b3 are nonzero elements.
A matrix has a unique Reduced row echelon form. Matlab allows users to find Reduced Row Echelon Form using rref() method. Different syntax of rref() are:
R = rref(A)
[R,p] = rref(A)
Let us discuss the above syntaxes in detail:
It returns the Reduced Row Echelon Form of the matrix A using the Gauss-Jordan method.
Matlab
% creating a matrix using magic(n)% generates n*n matrix with values% from 1 to n^2 where every row sum% is equal to every column sumA = magic(4);disp("Matrix");disp(A);  % Reduced Row Echelon Form of ARA = rref(A);disp("rref :");disp(RA);
Output :
It returns Reduced Row Echelon Form R and a vector of pivots p
p is a vector of row numbers that has a nonzero element in its Reduced Row Echelon Form.
The rank of matrix A is length(p).
R(1:length(p),1:length(p)) (First length(p) rows and length(p) columns in R) is an identity matrix.
Matlab
% creating a matrix using magic(n)% generates n*n matrix with values % from 1 to n^2 where every row sum% is equal to every column sumA = magic(5);disp("Matrix");disp(A);  % Reduced Row Echelon Form of A[RA,p] = rref(A);disp("rref :");disp(RA);  % Displaying pivot vector pdisp("Pivot vector");disp(p);
Output :
The System of linear equations is 
Coefficient matrix A is 
Constant matrix B is 
Then Augmented matrix [AB] is 
Matlab
% Coefficient matrixA = [1  1  1;     1  2  3;     1  4  7];       % Constant matrixb = [6 ;14; 30];  % Augmented matrixM = [A b];disp("Augmented matrix");disp(M)  % Reduced Row echelon form of % Augmented matrixR = rref(M);disp("rref");disp(R)
Output :
Then the reduced equations are 
It has infinite solutions, one can be .
MATLAB-Maths
MATLAB-matrix
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
MRI Image Segmentation in MATLAB
How to detect duplicate values and its indices within an array in MATLAB?
How to remove space in a string in MATLAB?
Classes and Object in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
Double Integral in MATLAB
How to Normalize a Histogram in MATLAB?
Python | numpy.nanmean() function

01 Jun, 2021
numpy.nanmean() function can be used to calculate the mean of array ignoring the NaN value. If array have NaN value and we can find out the mean without effect of NaN value. 
Syntax: numpy.nanmean(a, axis=None, dtype=None, out=None, keepdims=))Parameters: a: [arr_like] input array axis: we can use axis=1 means row wise or axis=0 means column wise. out: output array dtype: data types of array overwrite_input: If True, then allow use of memory of input array a for calculations. The input array will be modified by the call to median. keepdims: If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original a.Returns: Returns the average of the array elements 
Example #1:  
Python3
# Python code to demonstrate the# use of numpy.nanmeanimport numpy as np   # create 2d array with nan value.arr = np.array([[20, 15, 37], [47, 13, np.nan]])   print("Shape of array is", arr.shape)   print("Mean of array without using nanmean function:",                                           np.mean(arr))   print("Using nanmean function:", np.nanmean(arr))
Shape of array is (2, 3)
Mean of array without using nanmean function: nan
Using nanmean function: 26.4
 
Example #2:  
Python3
# Python code to demonstrate the# use of numpy.nanmean# with axis = 0import numpy as np   # create 2d matrix with nan valuearr = np.array([[32, 20, 24],                [47, 63, np.nan],                  [17, 28, np.nan],                [10, 8, 9]])   print("Shape of array is", arr.shape)   print("Mean of array with axis = 0:",             np.mean(arr, axis = 0))   print("Using nanmedian function:",      np.nanmean(arr, axis = 0))
Shape of array is (4, 3)
Mean of array with axis = 0: [ 26.5   29.75    nan]
Using nanmedian function: [ 26.5   29.75  16.5 ]
 
Example #3:  
Python3
# Python code to demonstrate the# use of numpy.nanmedian# with axis = 1import numpy as np   # create 2d matrix with nan valuearr = np.array([[32, 20, 24],                [47, 63, np.nan],                  [17, 28, np.nan],                [10, 8, 9]])   print("Shape of array is", arr.shape)   print("Mean of array with axis = 1:",             np.mean(arr, axis = 1))   print("Using nanmedian function:",      np.nanmean(arr, axis = 1))
Shape of array is (4, 3)
Mean of array with axis = 1: [ 25.33333333          nan          nan   9.        ]
Using nanmedian function: [ 25.33333333  55.          22.5          9.        ]
 
adnanirshad158
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2016 (Set 1) | Question 64

14 Feb, 2018
For a host machine that uses the token bucket algorithm for congestion control, the token bucket has a capacity of 1 megabyte and the maximum output rate is 20 megabytes per second. Tokens arrive at a rate to sustain output at a rate of 10 megabytes per second. The token bucket is currently full and the machine needs to send 12 megabytes of data. The minimum time required to transmit the data is _________________ seconds.(A) 1.1(B) 0.1(C) 2.1(D) 2.0Answer: (A)Explanation: Token bucket is a congestion control algorithm for data transfer. It takes tokens to synchronize between the rate of incoming and outgoing data.
According to the token bucket algorithm, the minimum time required 
to send 1 MB of data or the maximum rate of data transmission is 
given by:

   S = C / (M - P)

Where, 
M = Maximum burst rate,
P = Rate of arrival of a token,
C = capacity of the bucket



Using the above formula for the given question we can say that:
M = 20 MB
P = 10 MB
C = 1 MB
S = 1 / (20- 10) = 0.1 sec 
Since, the bucket is initially full, it already has 1 MB to transmit so it will be transmitted instantly. So, we are left with only (12 – 1), i.e. 11 MB of data to be transmitted.
Time required to send the 11 MB will be 11 * 0.1 = 1.1 sec
This explanation is contributed by Namita Singh.Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 63
GATE | GATE IT 2006 | Question 20
Can C++ reference member be declared without being initialized with declaration?

26 Apr, 2021
To many readers, this might sound the same thing, i.e.  
class_type *var = NULL;
*var = &some_work;

is same as

class_type *var = &some_work;
But in actual, it is not. When the declaration and initialization are done at the same step, the compiler calls the copy constructor whereas if done in another step, the compiler calls the default constructor.To understand this, let’s consider an example:Example 1: When initialization is not done at the same step of the declaration  
CPP
#include <iostream>using namespace std; class A {    int& p;     // Note:basically it is    // supposed to be an error    // because this reference    // member p is not initialized    // with some variable at the same    // step of its declaration. But it    // will run in this case. For us,    // this is the declaration but    // not for compiler public:     // this line    // means int &p=w, so p and w    // both are same. Compiler considers    // this step as declaration and    // initialization is done at    // same step.    A(int w): p(w)    {        cout << p;    }};int main(){    A obj(10);    return 0;}
Output:  
10
Example 2: When initialization is done with the declaration  
CPP
#include <iostream>using namespace std; class A {    int& p; public:     // In this step,    // compiler will see only    // declaration not initialization.    // Therefore this code will    // give an error.    A(int w)    {        p = w;        cout << p;    }};int main(){    A obj(10);    return 0;}
Compile Errors:  
prog.cpp: In constructor 'A::A(int)':
prog.cpp:8:5: error: uninitialized reference member in 'int&' [-fpermissive]
     A(int w)
     ^
prog.cpp:5:10: note: 'int& A::p' should be initialized
     int& p;
          ^
Note: In this code, as soon as an object is created compiler will allocate memory to p by running the constructor of class A. Now as we know reference variable needs to be initialized at the same step so it will pop up an error message called “reference member is not initialized” . As we have seen in code 1, initialization is not done at the same step of the declaration, but still, our code runs. But in general, it is a rule that “reference member should be initialized and declared at the same step.”So the answer to the above question is both yes and no. 
sweetyty
cpp-references
Technical Scripter 2018
C++
GFacts
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Return values of printf() and scanf() in C/C++
What are the Operators that Can be and Cannot be Overloaded in C++?
How are variables scoped in C - Static or Dynamic?
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Difference between YOLO and SSD
How to use TextField Component in ReactJS ?

10 Feb, 2021
TextField component is a complete form control including a label, input, and help text. Material UI for React has this component available for us and it is very easy to integrate. We can use TextField Component in ReactJS using the following approach:
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from "react";import TextField from "@material-ui/core/TextField";  const App = () => {  const [name, setName] = useState("");    return (    <div      style={{        marginLeft: "40%",      }}    >      <h2>How to use TextField Component in ReactJS?</h2>      <TextField        value={name}        label="Enter your name"        onChange={(e) => {          setName(e.target.value);        }}      />      <h3>Your Enter Value is: {name} </h3>    </div>  );};  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
C# Program to Sort a List of String Names Using the LINQ OrderBy() Method

06 Dec, 2021
Given a list of string names, now our task is to sort the names given in the list using the OrderBy() method of LINQ. This method is used to sort the elements in the collection in ascending order. While using this method in the LINQ query you don’t need to add an extra condition to sort the list in ascending order.
Example: 
Input    : [ "Raj", "Amisha", "Mohan", "Mohit", "Bhuvan" ]
Output : [ "Amisha", "Bhuvan", "Mohan", "Mohit", "Raj" ]

Input   : [ "Amu", "Amisha", "Sumita", "Gita" ]
Output : [ "Amisha", "Amu", "Gita", "Sumita" ]
Approach:
1. Create and initialize a list of string types. For example arr.
2. Sorting the list(named arr) using OrderBy() method.
var finalres = arr.OrderBy(n => n);
3. Display the result using the foreach loop.
Example:
C#
// C# program to sort a list of string type// Using OrderBy() methodusing System;using System.Linq;using System.Collections.Generic;  class GFG{      static void Main(string[] args){          // Creating and initializing list of string type    List<string> arr = new List<string>(){ "Raju", "Avinash",                                            "Sandeep", "Vineeth",                                           "Naveen" };                                                 // Using order by method we sort the list    var finalres = arr.OrderBy(n => n);          // Display the list    Console.WriteLine("Sorted names are:");    foreach (string data in finalres)    {        Console.Write(data + " ");    }}}
Output:
Sorted names are:
Avinash Naveen Raju Sandeep Vineeth 
CSharp LINQ
Picked
C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find Duplicates in MS SQL Server

08 Sep, 2020
We could use the following methods to find duplicate values in a table.
GROUP BY clause.
ROW_NUMBER() function.
1. Using the GROUP BY clause to find the duplicate values :
Syntax :
SELECT col1, col2, ...COUNT(*)
FROM table_name
GROUP BY col1, col2, ...
HAVING COUNT(*) > 1;
Example –Let us create a table named Geek that contains three columns ID, A, and B.
CREATE TABLE Geek (
ID INT IDENTITY(1, 1),
A INT,
B INT,
PRIMARY KEY(id));
Let us add some values to the table Geek –
INSERT INTO Geek (A, B)
VALUES (1, 1),(1, 2), (1, 3), (2, 1),
(1, 2), (1, 3), (2, 1), (2, 2);
We know that Geek table contains the following duplicate rows –
(1, 2) (2, 1) (1, 3) 
MS SQL Server query to find the duplicate rows using GROUP BY clause in the Geek table :
SELECT A, B, COUNT(*) AS num
FROM Geek
GROUP BY A, B
HAVING COUNT(*) > 1;
Output –
Table – Geek
To find the full row details for each duplicate row, JOIN the output of the above query with the Geek table using CTE :
WITH CTE AS ( 
SELECT A, B, COUNT(*) AS num
FROM Geek
GROUP BY A, B
HAVING COUNT(*) > 1
)
SELECT Geek.ID, Geek.A, Geek.B
FROM Geek
INNER JOIN CTE ON
CTE.A = Geek.A AND CTE.B = Geek.B
ORDER BY Geek.A, Geek.B;
Output –
Table – Geek
2. Using ROW_NUMBER() function to find duplicate values :
Syntax :
WITH cte AS (
SELECT col,ROW_NUMBER() OVER (
PARTITION BY col
ORDER BY col) AS row_num
FROM table_name
)  
SELECT * 
FROM cte  
WHERE row_num > 1;
MS SQL Server query to find the duplicate rows using ROW_NUMBER() function in the Geek table :
WITH CTE AS (
SELECT A, B,
ROW_NUMBER() OVER (
PARTITION BY A, B
ORDER BY A, B
) AS rownum
FROM Geek
)
SELECT *
FROM CTE
WHERE rownum > 1;
Output –
Table – Geek
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
SQL | Sub queries in From Clause
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
SQL Query to Compare Two Dates
SQL Query to Convert Rows to Columns in SQL Server
How to change PowerShell ISE font Size using command?

To change the font size of the PowerShell ISE editor using the command, we need to use the cmdlet $PSISE which is only loaded inside the PowerShell ISE console. You won’t find it in the main PowerShell console.
Once you run this command, there are various properties available. For example,
PS C:\> $psISE
CurrentPowerShellTab          :
Microsoft.PowerShell.Host.ISE.PowerShellTab
CurrentFile                   :
 Microsoft.PowerShell.Host.ISE.ISEFile
CurrentVisibleHorizontalTool  :
CurrentVisibleVerticalTool    :
Options : Microsoft.PowerShell.Host.ISE.ISEOptions
PowerShellTabs                :  {PowerShell 1}
You need to select the Options Property and then need to set its FontSize attribute as shown below.
$psISE.Options.FontSize = 12
The above command will immediately change the font size of the ISE console.
Python program to get the nth weekday after a given date

27 Dec, 2021
Given a date and weekday index, the task is to write a Python program to get the date for the given day of the week occurring after the given date. The weekday index is based on the below table:
Examples:
Input : test_date = datetime.datetime(2017, 3, 14), weekday_idx = 4
Output : 2017-03-17 
Explanation : 14 March is Tuesday, i.e 1 weekday, 4th weekday is a Friday, i.e 17 March.
Input : test_date = datetime.datetime(2017, 3, 12), weekday_idx = 5
Output : 2017-03-18
Explanation : 12 March is Sunday, i.e 6th weekday, 5th weekday in next week is a Saturday, i.e 18 March.
Method #1 : Using timedelta() + weekday()
In this, we subtract the date weekday from the weekday index and then check for required index extracted, then the required day, if negative is summed with 7 and then the resultant number is added to current date using timedelta().
Python3
# Python3 code to demonstrate working of# Next weekday from Date# Using timedelta() + weekday()import datetime # initializing datestest_date = datetime.datetime(2017, 3, 14) # printing original dateprint("The original date is : " + str(test_date)[:10]) # initializing weekday indexweekday_idx = 4 # computing delta daysdays_delta = weekday_idx - test_date.weekday()if days_delta <= 0:    days_delta += 7 # adding days to required resultres = test_date + datetime.timedelta(days_delta) # printing resultprint("Next date of required weekday : " + str(res)[:10])
Output:
The original date is : 2017-03-14
Next date of required weekday : 2017-03-17
Method #2 : Using lambda function
Using the lambda function provides a shorthand and compact solution to the question. 
Python3
# Python3 code to demonstrate working of# Next weekday from Date# Using lambda functionimport datetime # initializing datestest_date = datetime.datetime(2017, 3, 14) # printing original dateprint("The original date is : " + str(test_date)[:10]) # initializing weekday indexweekday_idx = 4 # lambda function provides one liner shorthanddef lfnc(test_date, weekday_idx): return test_date + \    datetime.timedelta(days=(weekday_idx - test_date.weekday() + 7) % 7)  res = lfnc(test_date, weekday_idx) # printing resultprint("Next date of required weekday : " + str(res)[:10])
Output:
The original date is : 2017-03-14
Next date of required weekday : 2017-03-17
nnr223442
as5853535
Python datetime-program
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 ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Get Yesterday’s date using Python

02 Sep, 2021
Prerequisite: datetime moduleIn Python, date and time are not a data type of its own, but a module named datetime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally. 
To work with date, datetime module provides the date class and timedelta class is used to calculate differences in date. Let’s have a look at them.
Date class: When an object of this class is instantiated, it represents a date in the format YYYY-MM-DD. To return the current local date today() function of date class is used. today() function comes with several attributes (year, month and day). These can be printed individually.Syntax: 
date.today()
Timedelta class: Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.Syntax: 
datetime.timedelta(days=0, seconds=0, microseconds=0,
                milliseconds=0, minutes=0, hours=0, weeks=0)

Returns: Date
Below is the implementation 
Python3
# Python program to get# Yesterday's date  # Import date and timedelta class# from datetime modulefrom datetime import datefrom datetime import timedelta # Get today's datetoday = date.today()print("Today is: ", today) # Yesterday dateyesterday = today - timedelta(days = 1)print("Yesterday was: ", yesterday)
Output: 
Today is:  2019-12-11
Yesterday was:  2019-12-10
You just have to subtract no. of days using ‘timedelta’ that you want to get back in order to get the date from the past.
For example, on subtracting two we will get the date of the day before yesterday. 
Python3
# Python program to get# Yesterday's date  # Import date and timedelta class# from datetime modulefrom datetime import datefrom datetime import timedelta  # Get today's datetoday = date.today()print("Today is: ", today) # Get 2 days earlieryesterday = today - timedelta(days = 2)print("Day before yesterday was: ", yesterday)
Output:
Today is:  2019-12-11
Day before yesterday was:  2019-12-09
 
simmytarika5
Python datetime-program
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
How to write Regex for numbers only in C#?

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.
A pattern consists of one or more character literals, operators, or constructs.
Here are basic pattern metacharacters used by RegEx −
* = zero or more
? = zero or one
^ = not
[] = range
The ^ symbol is used to specify not condition.
the [] brackets if we are to give range values such as 0 - 9 or a-z or A-Z
class Program{
   public static void Main(){
      string num = "123dh";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}
False
class Program{
   public static void Main(){
      string num = "123";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}
True
class Program{
   public static void Main(){
      string num = "123.67";
      Regex regex = new Regex(@"^-?[0-9][0-9,\.]+$");
      var res = regex.IsMatch(num);
      System.Console.WriteLine(res);
   }
}
True
Break a list into chunks of size N in Python

Here we shall have a given user input list and a given break size. And our task is to break the list as per the given size.
Here we are applying yield keyword it enables a function where it left off then again it is called, this is the main difference with regular function.
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
   p=int(input("Size="))
   A.append(int(p))
   print (A)
deflist_chunks(l, n):
   for i in range(0, len(l), n):
      yield l[i:i + n]
n=int(input("Enter Chunk Size"))
my_list = list(list_chunks(A, n))
print ("List of Chunks",my_list)
Enter the size of the List 6
Enter the number
Size= 12
[12]
Size= 33
[12, 33]
Size= 11
[12, 33, 11]
Size= 56
[12, 33, 11, 56]
Size= 44
[12, 33, 11, 56, 44]
Size= 89
[12, 33, 11, 56, 44, 89]
Enter Chunk Size 3
List of Chunks [[12, 33, 11], [56, 44, 89]]

Using List comprehension we can solve this problem in one line.
A=list()
n=int(input("Enter the size of the List"))
print("Enter the number")
for i in range(int(n)):
   p=int(input("Size="))
   A.append(int(p))
   print (A)
n=int(input("Enter Chunk Size"))
my_final = [A[i * n:(i + 1) * n] for i in range((len(A) + n - 1) // n )]
print ("List of chunks:",my_final)
Enter the size of the List 6
Enter the number
Size= 23
[23]
Size= 34
[23, 34]
Size= 12
[23, 34, 12]
Size= 56
[23, 34, 12, 56]
Size= 33
[23, 34, 12, 56, 33]
Size= 22
[23, 34, 12, 56, 33, 22]
Enter Chunk Size 3
List of chunks: [[23, 34, 12], [56, 33, 22]]
numpy.tan() in Python

09 Aug, 2021
numpy.tan(array[, out]) = ufunc ‘tan’) : This mathematical function helps user to calculate trigonometric tangent for all x(being the array elements). Parameters : 
array    : [array_like]elements are in radians.
out      : [optional]shape same as array.  
2pi Radians = 360 degrees
tan(x) = sin(x) / cos(x)
Return : 
An array with trigonometric sine
of x for all x i.e. array elements 
Code #1 : Working 
Python
# Python program explaining# tan() function import numpy as npimport math in_array = [0, math.pi / 4, 3*np.pi / 2, math.pi/6]print ("Input array : \n", in_array) tan_Values = np.tan(in_array)print ("\nTan values : \n", tan_Values)
Output : 
Input array : 
 [0, 0.7853981633974483, 4.71238898038469, 0.5235987755982988]

Tan values : 
 [  0.00000000e+00   1.00000000e+00   5.44374645e+15   5.77350269e-01]
Code #2 : Graphical representation 
Python
# Python program showing# Graphical representation of# tan() function import numpy as npimport matplotlib.pyplot as plt in_array = np.linspace(0, np.pi, 12)out_array = np.tan(in_array) print("in_array : ", in_array)print("\nout_array : ", out_array) # red for numpy.tan()plt.plot(in_array, out_array, color = 'red', marker = "o")plt.title("numpy.tan()")plt.xlabel("X")plt.ylabel("Y")plt.show()
Output : 
in_array :  [ 0.          0.28559933  0.57119866  0.856798    1.14239733  1.42799666
  1.71359599  1.99919533  2.28479466  2.57039399  2.85599332  3.14159265]

out_array :  [  0.00000000e+00   2.93626493e-01   6.42660977e-01   1.15406152e+00
   2.18969456e+00   6.95515277e+00  -6.95515277e+00  -2.18969456e+00
  -1.15406152e+00  -6.42660977e-01  -2.93626493e-01  -1.22464680e-16]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.tan.html#numpy.tan . 
akshaysingh98088
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP headers | Accept-Encoding

23 Oct, 2019
The HTTP headers Accepts-Encoding is usually a comparison algorithm of request header. All the HTTP client used to tell the server which encoding or encoding it supports. Then the server will respond in any of the supporting encoding formats. The server selects any one of the proposals, uses it and informs the client of its choice with the Content-Encoding response header.
Syntax:
Accept-Encoding: gzip | compress | deflate | br| identity| *
Note: Multiple algorithm are also can be applicable.
Directives:
gzip: It is a compression format using the Lempel-Ziv coding (LZ77), with a 32-bit CRC.
compress: It is a compression format using the Lempel-Ziv-Welch (LZW) algorithm.
deflate: It is a compression format using the zlib structure, with the deflate compression algorithm.
br: It is a compression format using the Brotli algorithm.
identity: This directive Indicates the identity function which is always acceptable.
*: This directive matches any content encoding which can be listed in the header or not. It is the default value.
You can check how good your Accept-Encoding and Content-Encoding is working on this site.Example:
Accept-Encoding: gzip, deflate, br
Accept-Encoding: br;q=1.0, gzip;q=0.6, *;q=0.1
To check this Accept-Encoding in action go to Inspect Element -> Network check the request header for Accept-Encoding like below, Accept-Encoding is highlighted you can see.
Supported Browsers: The browsers compatible with HTTP headers Accept-Encoding are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.