code-rag-bench/online-tutorials huggingface dataset:
Peak Element in 2D array

An item is said to be a peak element when it is greater than or equal with all four neighbor of that element. The neighbor elements are the top, bottom, left and right elements. For this problem, we will consider some bounds. The diagonal elements are not checked as neighbor elements. More than one peak element may present in a matrix, and the peak element is not necessarily the largest element in the matrix.
Input:
A matrix of different numbers.
10  8  10  10
14 13  12  11
15  9  11  11
15  9  11  21
16 17  19  20

Output:
The peak element of the matrix.
Here the peak element is: 21
findMaxMid(rows, mid, max)
Input: Rows number of the matrix, mid row, a max element as an output argument.
Output: Update the max item and index of the max element.
Begin
   maxIndex := 0
   for all rows r in the matrix, do
      if max < matrix[i, mid], then
         max = matrix[i, mid],
         maxIndex := r
   done
   return maxIndex
End
findPeakElement(rows, columns, mid)
Input − Row and column of the matrix, and mid row place.
Output − Peak element in the matrix.
Begin
   maxMid := 0
   maxMidIndex := findMaxMid(rows, mid, maxMid)

   if mid is first or last column, then
      return maxMid

   if maxMid>= item of previous and next row for mid column, then
      return maxMid

   if maxMid is less than its left element, then
      res := findPeakElement(rows, columns, mid – mid/2)
      return res

   if maxMid is less than its right element, then
      res := findPeakElement(rows, columns, mid + mid/2)
      return res
End
#include<iostream>
#define M 4
#define N 4
using namespace std;

intarr[M][N] = {
   {10, 8, 10, 10},
   {14, 13, 12, 11},
   {15, 9, 11, 21},
   {16, 17, 19, 20}
};

intfindMaxMid(int rows, int mid, int&max) {
   intmaxIndex = 0;

   for (int i = 0; i < rows; i++) {    //find max element in the mid column
      if (max <arr[i][mid]) {
         max = arr[i][mid];
         maxIndex = i;
      }
   }
   return maxIndex;
}

intfindPeakElement(int rows, int columns, int mid) {
   intmaxMid = 0;
   intmaxMidIndex = findMaxMid(rows, mid, maxMid);

   if (mid == 0 || mid == columns-1)    //for first and last column, the maxMid is maximum
      return maxMid;
   // If maxMid is also peak
   if (maxMid>= arr[maxMidIndex][mid-1] &&maxMid>= arr[maxMidIndex][mid+1])
      return maxMid;

   if (maxMid<arr[maxMidIndex][mid-1])     // If maxMid is less than its left element
      return findPeakElement(rows, columns, mid - mid/2);
   return findPeakElement(rows, columns, mid+mid/2);
}

int main() {
   int row = 4, col = 4;
   cout<< "The peak element is: "<<findPeakElement(row, col, col/2);
}
The peak element is: 21
SQL - DROP or DELETE Table

The SQL DROP TABLE statement is used to remove a table definition and all the data, indexes, triggers, constraints and permission specifications for that table.
NOTE − You should be very careful while using this command because once a table is deleted then all the information available in that table will also be lost forever.
The basic syntax of this DROP TABLE statement is as follows −
DROP TABLE table_name;

Let us first verify the CUSTOMERS table and then we will delete it from the database as shown below −
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field   | Type          | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID      | int(11)       | NO   | PRI |         |       |
| NAME    | varchar(20)   | NO   |     |         |       |
| AGE     | int(11)       | NO   |     |         |       |
| ADDRESS | char(25)      | YES  |     | NULL    |       |
| SALARY  | decimal(18,2) | YES  |     | NULL    |       |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
This means that the CUSTOMERS table is available in the database, so let us now drop it as shown below.
SQL> DROP TABLE CUSTOMERS;
Query OK, 0 rows affected (0.01 sec)
Now, if you would try the DESC command, then you will get the following error −
SQL> DESC CUSTOMERS;
ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist
Here, TEST is the database name which we are using for our examples.

    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
How to calculate the area and perimeter of a circle in JavaScript?

To calculate the area and perimeter of a circle, you can try to run the following code −
<html>
   <head>
      <title>JavaScript Example</title>
   </head>
   <body>
      <script>
         function Calculate(r) {
            this.r = r;
            this.perimeter = function () {
               return 2*Math.PI*this.r;
            };

            this.area = function () {
               return Math.PI * this.r * this.r;
            };
         }
         
         var calc = new Calculate(5);
         
         document.write("Area of Circle = ", calc.area().toFixed(2));
         document.write("<br>Perimeter of Circle = ", calc.perimeter().toFixed(2));
      </script>
   </body>
</html>
Python - Normal Distribution

The normal distribution is a form presenting data by arranging the probability distribution of each value in the data.Most values remain around the mean value making the arrangement symmetric.

We use various functions in numpy library to mathematically calculate the values for a normal distribution. Histograms are created over which we plot the probability distribution curve. 
import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 0.5, 0.1
s = np.random.normal(mu, sigma, 1000)

# Create the bins and histogram
count, bins, ignored = plt.hist(s, 20, normed=True)

# Plot the distribution curve
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
    np.exp( - (bins - mu)**2 / (2 * sigma**2) ),       linewidth=3, color='y')
plt.show()
Its output is as follows −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
3 ways to initialize an object in Java

Consider a class Tester which has implemented Cloneable interface. Now you can initialize an object using following three ways −
1. Using new keyword.
Tester tester1 = new Tester();
2. Using Class.forName() method
Tester tester4 = (Tester)Class.forName("Tester").newInstance();
3. Using clone method.
Tester tester2 = tester1.clone();
GATE | GATE-CS-2009 | Question 19 - GeeksforGeeks

28 Jun, 2021
The coupling between different modules of a software is categorized as follows:
   I.   Content coupling
   II.  Common coupling
   III. Control coupling 
   IV.  Stamp coupling
   V.   Data coupling 
Coupling between modules can be ranked in the order of strongest (least desirable) to weakest (most desirable) as follows:(A) I-II-III-IV-V(B) V-IV-III-II-I(C) I-III-V -II-IV(D) IV-II-V-III-IAnswer: (A)Explanation: See http://en.wikipedia.org/wiki/Coupling_(computer_programming)Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2007 | Question 17
GATE | GATE CS 2019 | Question 37
GATE | GATE-CS-2014-(Set-3) | Question 65
Domain Relational Calculus in DBMS - GeeksforGeeks

25 Mar, 2020
Domain Relational Calculus is a non-procedural query language equivalent in power to Tuple Relational Calculus. Domain Relational Calculus provides only the description of the query but it does not provide the methods to solve it. In Domain Relational Calculus, a query is expressed as,
{ < x1, x2, x3, ..., xn > | P (x1, x2, x3, ..., xn ) } 
where, < x1, x2, x3, ..., xn > represents resulting domains variables and P (x1, x2, x3, ..., xn ) represents the condition or formula equivalent to the Predicate calculus.Predicate Calculus Formula:
Set of all comparison operatorsSet of connectives like and, or, notSet of quantifiers
Set of all comparison operators
Set of connectives like and, or, not
Set of quantifiers
Example:
Table-1: Customer
Table-2: Loan
Table-3: Borrower
Query-1: Find the loan number, branch, amount of loans of greater than or equal to 100 amount.
{≺l, b, a≻ | ≺l, b, a≻ ∈ loan ∧ (a ≥ 100)}
Resulting relation:
Query-2: Find the loan number for each loan of an amount greater or equal to 150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan ∧ (a ≥ 150)}
Resulting relation:
Query-3: Find the names of all customers having a loan at the “Main” branch and find the loan amount .
{≺c, a≻ | ∃ l (≺c, l≻ ∈ borrower ∧ ∃ b (≺l, b, a≻ ∈ loan ∧ (b = “Main”)))}
Resulting relation:
Note:The domain variables those will be in resulting relation must appear before | within ≺ and ≻ and all the domain variables must appear in which order they are in original relation or table.
ThomasWhitley
Sanjay Sharma 5
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction of ER Model
Introduction of B-Tree
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
SQL | Views
Layers of OSI Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
TCP/IP Model
Regular Expressions, Regular Grammar and Regular Languages
How to convert color spaces in OpenCV using C++?

Color space is the model of representing colors. There are different ways of describing colors. For example, RGB, CYMK, HSV, Grayscale etc.
Here, we used a new header named 'imgproc.hpp'. This 'imgproc.hpp' is the abbreviation of Image Processing. To convert color spaces, we need to use 'cvtColor()' function of OpenCV. This function is defined in 'imgproc' header file. That's why we have included 'imgproc.hpp'.
Firstly, we declared two matrices and two windows. These are for loading and showing the images. Then we loaded our image named 'cat.jpg' into 'myImage' matrix.  After that we used 'cvtColor(myImage, myImage_Converted, COLOR_RGB2GRAY)'. This line converts the RGB color space of 'myImage' to Grayscale and stores it in 'myImage_Converted' matrix.
The raw form of the 'cvtColor() function is −
cvtColor(Source Matrix, Destination Matrix, Color Space Conversion Code)
In this program, the source matrix is 'myImage', destination matrix is 'myImage_Converted', and color space conversion code is COLOR_RGB2GRAY. 
The following program converts RGB images to Grayscale images in OpenCV.
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc, const char** argv) {
   Mat myImage;//declaring a matrix to load the image//
   Mat myImage_Converted;//declaring a matrix to store the converted image//  
   namedWindow("Actual_Image");//declaring window to show actual image//
   namedWindow("Converted_Image");//declaring window to show converted image//
   myImage = imread("cat.jpg");//loading the image in myImage matrix//
   cvtColor(myImage,myImage_Converted, COLOR_RGB2GRAY);//converting RGB to Grayscale//
   imshow("Actual_Image",myImage);//showing Actual Image//
   imshow("Converted_Image",myImage_Converted);//showing Converted Image//  
   waitKey(0);//wait for key stroke
   destroyAllWindows();//closing all windows
   return 0;
}
Aptitude | Arithmetic Aptitude 3 | Question 3 - GeeksforGeeks

28 Jun, 2021
At present, the ratio between ages of Ram and Shyam is 6:5 respectively. After 7 years, Shyam’s age will be 32 years. What is the present age of Ram?(A) 32(B) 40(C) 30(D) 36Answer: (C)Explanation:
Let the present age of Ram and Shyam be 6x years and 5x years respectively.

Then 5x + 7 = 32
∴      5x = 25
∴        x = 5
∴ Present age of Ram = 6x = 30 years
Quiz of this Question
Aptitude
Aptitude-Arithmetic Aptitude 3
Arithmetic Aptitude 3
Aptitude
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Puzzle | How much money did the man have before entering the bank?
Order and Ranking Questions & Answers
C | C Quiz - 113 | Question 1
Program to find Surface Area and Volume of Octagonal Prism
Aptitude | Syllogism | Question 3
Seating Arrangement | Aptitude
Aptitude | Series | Question 4
Aptitude | Arithmetic Aptitude 3 | Question 1
Aptitude | GATE CS 1998 | Question 77
Aptitude | Data Sufficiency | Question 8
UGC NET CS 2015 Jun - III - GeeksforGeeks

25 Oct, 2021
RST 7  CALL 0038 H 
RST 6  CALL 0030 H
RST 4  CALL 0028 H
RST 3  CALL 0020 H
RST 2  CALL 0018 H
RST 1  CALL 0010 H
RST 0  CALL 0008 H 

Lossless preserving decomposition into 3NF is always possible. True
Lossless preserving decomposition into BCNF is always possible. False Not always possible.
Any Relation with two attributes is in BCNF. True
BCNF is stronger than 3NF. TrueFor more information on Normal form Refer:Database Normalization | Normal Forms
Option (B) is correct.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
How to Replace Values in a List in Python?
Spring - REST Controller
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
How to Compare Two Columns in Pandas?
Nested Structure in C with Examples
Implement $match and $project in MongoDB aggregate

The $match filters the documents to pass only the documents that match the specified condition to the next pipeline stage.
The $project passes along the documents with the requested fields to the next stage in the pipeline.
Let us see an example and create a collection with documents −
> db.demo545.insert({Name:"Chris",details:{SubjectScore1:56,SubjectScore2:56}})
WriteResult({ "nInserted" : 1 })
> db.demo545.insert({Name:"David",details:{SubjectScore1:78,SubjectScore2:78}})
WriteResult({ "nInserted" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo545.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e246e9e5f92834d7f05d5"), "Name" : "Chris", "details" : { "SubjectScore1" : 56, "SubjectScore2" : 56 } }
{ "_id" : ObjectId("5e8e24709e5f92834d7f05d6"), "Name" : "David", "details" : { "SubjectScore1" : 78, "SubjectScore2" : 78 } }
Following is the query to implement $match and $project −
>db.demo545.aggregate([{$match:{}},{$project:{"_id":0,"details.SubjectScore1":1,out:"$details
.SubjectScore2"}},{$group:{_id:"$out"}}])
This will produce the following output −
{ "_id" : 78 }
{ "_id" : 56 }
GATE | GATE-CS-2015 (Set 3) | Question 37 - GeeksforGeeks

28 Jun, 2021
Assume that a mergesort algorithm in the worst case takes 30 seconds for an input of size 64. Which of the following most closely approximates the maximum input size of a problem that can be solved in 6 minutes?(A) 256(B) 512(C) 1024(D) 2048Answer: (B)Explanation:
Time complexity of merge sort is Θ(nLogn)

c*64Log64 is 30
c*64*6 is 30
c is 5/64

For time 6 minutes

5/64*nLogn = 6*60

nLogn = 72*64 = 512 * 9

n = 512. 
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2003 | Question 90
How to get title of a webpage using Selenium in Python? - GeeksforGeeks

04 Jan, 2021
The title method is used to retrieve the title of the webpage the user is currently working on. It gives the title of the current webpage loaded by the driver in selenium, if webpage has no title a null string will be returned.
Webpage title :A page title, also known as a title tag, is a short description of a webpage and appears at the top of a browser window and in SERPs. It is an important element of an optimized SEO page. A page title should include a page’s keyword in the title tag.
Syntax :
driver.title

Argument :
It takes no argument.
Return value :
It return the title of webpage in string format.
# importing webdriver from seleniumfrom selenium import webdriver  # Here Chrome  will be useddriver = webdriver.Chrome()    # URL of websiteurl = "https://www.geeksforgeeks.org/"  # Opening the websitedriver.get(url)  # Getting current URL source codeget_title = driver.title  # Printing the title of this URLprint(get_title)
Output :
GeeksforGeeks | A computer science portal for geeks
Code 2:
# importing webdriver from seleniumfrom selenium import webdriver  # Here Chrome  will be useddriver = webdriver.Chrome()    # URL of websiteurl = "https://www.google.com/"  # Getting current URL source codeget_title = driver.title  # Printing the title of this URL# Here it is null stringprint(get_title, " ", len(get_title))  # Opening the websitedriver.get(url)  # Getting current URL source codeget_title = driver.title  # Printing the title of this URLprint(get_title, "  ", len(get_title))
Output :
Google

Python Selenium-Exercises
Python-selenium
Python
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Java program to find the circumference of a circle

The circumference of a circle is double the product of its radius and the value of PI. Therefore, to calculate the circumference of a circle
Get the radius of the circle form the user.
Calculate the product
Print the final result.
import java.util.Scanner;
public class CircumfrenceOfCircle {
   public static void main(String args[]){
      int radius;
      double circumference;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the radius of the circle ::");
      radius = sc.nextInt();
      circumference = Math.PI*2*radius;
      System.out.println("Circumference of the circle is ::"+circumference);
   }
}
Enter the radius of the circle::
55
The circumference of the circle is::345.57519189487726
BigDecimal movePointRight() Method in Java - GeeksforGeeks

04 Dec, 2018
Prerequisite : BigDecimal Basics
The java.math.BigDecimal.movePointRight(int n) method is used to move the decimal point of the current BigDecimal by n places to the right.
If n is non-negative, the call merely subtracts n from the scale.
If n is negative, the call is equivalent to movePointLeft(-n).
The BigDecimal returned by this method has value (this × 10n) and scale max(this.scale()-n, 0).
Syntax:
public BigDecimal movePointRight(int n)
Parameter: The method takes one parameter n of integer type which refers to the number of places by which the decimal point is required to be moved towards the right.
Return Value: The method returns the same BigDecimal value with the decimal point moved n places to the right.
Exception: The method throws an ArithmeticException if the scale overflows.
Examples:
Input: value = 2300.9856, rightshift = 3
Output: 2300985.6
Explanation:
After shifting the decimal point of 2300.9856 by 3 places to right,
2300985.6 is obtained.
Alternate way: 2300.9856*10^(3)=2300985.6

Input: value = 35001, rightshift = 2
Output: 3500100

Below program illustrate the movePointRight() method of BigDecimal:
// Program to demonstrate movePointRight() method of BigDecimal   import java.math.*;  public class GFG {      public static void main(String[] args)    {        // Create BigDecimal object        BigDecimal bigdecimal = new BigDecimal("2300.9856");          // Create a int i for decimal right move distance        int i = 3;          // Call movePointRight() method on BigDecimal by shift i        BigDecimal changedvalue = bigdecimal.movePointRight(i);          String result = "After applying decimal move right        by move Distance " + i + " on " + bigdecimal +         " New Value is " + changedvalue;          // Print result        System.out.println(result);    }}
After applying decimal move right by move Distance 3 on 2300.9856 New Value is 2300985.6

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#movePointRight(int)
Java-BigDecimal
Java-Functions
java-math
Java-math-package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
How to remove an element from ArrayList in Java?
Binary Search functions in C++ STL

Binary search is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the sorted array. The time complexity of binary search is O(1). This is a C++ program in which we implement various. Binary Search functions in C++ STL
Begin
   Initialize the vector of integer values.
   The functions are used here:
   binary_search(start_pointer, end_pointer, value) = Returns true if the value present in array otherwise    false.

   lower_bound(start_pointer, end_pointer, value) = Returns pointer to “position of value” if container 
      contains 1 occurrence of value. Returns pointer to “first position of value” if container contains 
      multiple occurrence of value. Returns pointer to “position of next higher number than value” if container does not contain occurrence of value.

   upper_bound(start_pointer, end_pointer, value) = Returns pointer to “position of next higher valuethan 
      value” if container contains 1 occurrence of value. Returns pointer to “first position of next higher 
      number than last occurrence of value” if container contains multiple occurrence of value. Returns 
      pointer to “position of next higher number than value” if container does not contain occurrence of value.
   Print the results.
End.
#include<bits/stdc++.h>
using namespace std;
int main() {
   vector<int> a = {6,7,10,14,16,20};
   if (binary_search(a.begin(), a.end(), 50))
      cout << "50 exists in vector";
   else
      cout << "50 does not exist";
   cout << endl;
   if (binary_search(a.begin(), a.end(), 7))
      cout << "7 exists in the vector";
   else
      cout << "7 does not exist";
   cout << endl;
   cout << "The position of 7 using lower_bound ";
   cout << lower_bound(a.begin(), a.end(), 7) - a.begin();
   cout << endl;
   cout << "The position of 7 using upper_bound ";
   cout << upper_bound(a.begin(), a.end(), 7) - a.begin();
   cout << endl;
}
50 does not exist
7 exists in the vector
The position of 7 using lower_bound 1
The position of 7 using upper_bound 2
Creating auto-resize text area using JavaScript

Following is the code for creating auto resize text area using JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h1>Creating auto-resize text area</h1>
<textarea class="resizeArea"></textarea>
<script>
   let BtnEle = document.querySelector(".Btn");
   let addrEle = document.querySelectorAll(".addr");
   let resizeEle = document.querySelector(".resizeArea");
   resizeEle.addEventListener("input", resizeTextArea, false);
   function resizeTextArea() {
      this.style.height = "auto";
      this.style.height = this.scrollHeight + "px";
   }
</script>
</body>
</html>
On pasting text in the text area, the area will expand as follows −
What is a standard for commenting a function in JavaScript?

To comment a function in JavaScript, you can use the following standard −
/**
* Adds two numbers
* @param {Number} num1
* @param {Number} um
* @return {Number} sum
*/
function sum(num1,num2) {
   return num1 + num2;
}
How to connect to SSH using PowerShell?

It is possible to connect the non-windows target machines with the PowerShell using the SSH command in PowerShell. For that, you need to use the below format.
ssh username@servername
The below example shows how we can connect the non-windows target machine.
PS C:\> ssh ansible@192.168.0.104
Once you run this command the first time for any new server the setting will be added to the path .ssh/known_hosts in the user profile.
Best way to null check in Kotlin

In any programming paradigm, it is mandatory to check "null safety" in order
to prevent runtime errors. In this article, we will see different ways to check "null safety" in Kotlin.
In most of the programming languages, we have the "if" keyword to check
conditions. In Kotlin too, we can use the "if-else" clause to check the null safety of a variable.
fun main() {
   val name="TutorialsPoint.com"
   //null check
   if (name != null) {
      println(name)
   }
   else{
      println("Please enter a value")
   }
}
In the above program, the compiler will check the value of the variable "name". If the value is NULL, then it will print "Please enter a value", otherwise it will print "TutorialsPoint.com".
For the given example, the output will be "TutorialsPoint.com".
TutorialsPoint.com

You can use the "?.let" operator in Kotlin to check if the value of a variable is NULL. It can only be used when we are sure that we are refereeing to a non-NULL able value. The following example demonstrates how this operator
works. This is the best approach when we are using the 'var' variable.
fun main() {
   var name="TutorialsPoint.com"
   // NULL check
   name ?.let{
      println(name)
   }
}
The above expression is equivalent to −
if(name!=null){
   println(name)
}
In this example, let() will execute only when the variable 'name' is not equal to 'null'.
TutorialsPoint.com

When we have some default value to return in case there is a NULL reference,
then it is better to use the Elvis operator. Elvis operator is very common in
many programming languages. This is a binary expression that returns the first
operand when the expression value is True and it returns the second operand
when the expression value is False.
In the following example, we will see how to use this Elvis operator in Kotlin.
fun main(args: Array<String>) {
   val x: String? = null
   val y: String = x ?: "TutorialsPoint.com"
   // it will check whether the value of x is NULL or not.
   // If NULL, then it will return "y", else "x"
   println(x ?: y)
}
TutorialsPoint.com
GOCC14: Google’s Online Coding Challenge – New Grad (India)

25 Aug, 2020
The Google online challenge 2020 for new graduate 2021 was held on August 22. It was a 60-minute online test having 2 questions to code.
The exam was conducted on HackerEarth. But first, your resume should be shortlisted for the exam then they will send you link & passkey with the time span of 5 hr
i.e(mine scheduled between 3 p.m to 8 p.m) but the duration of the exam was 1 Hour only
First Question: Size of the smallest subset with maximum Bitwise XOR in a 2-D matrix & return the smallest subset
a[1,1]^a[1,2]
a[2,1]^a[2,2]
a[1,1]^a[1,2] a[2,1]^a[2,2];
In Case of multi answer return the smallest subset
Time complexity O(n^2);
Second Question: Given an unsorted array, you have to delete an element such that after deletion every subset of the array having min & max element in increasing order(a similar approach like window sliding )
Time complexity O(n^2)
Eg:
arr[]={2,3,4,5,1,6,7};
delete(1)
after deletion 
(2,3) 
(2,3,4)
(2,3,4,5)
and so on..
In this, Some corner case must be kept in mind while solving the question 
Google
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Grids in Matplotlib

22 Apr, 2020
Grids are made up of intersecting straight (vertical, horizontal and angular) or curved lines used to structure our content. Matplotlib helps us to draw plain graphs but it sometimes necessary to use grids for better understanding and get a reference for our data points. Thus, Matplotlib provides a grid() for easy creation of gridlines with tonnes of customization.
Syntax: matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, **kwargs)
Parameters:b: bool value to specify whether to show grid-lines. Default is Truewhich: The grid lines to apply changes. Values: {‘major’, ‘minor’, ‘both’}axis: The axis to apply changes on. Values: {‘both’, ‘x’, ‘y’}**kwargs: Optional line properties
Returns: This function doesn’t return anything.
The grid() sets the visibility of grids by specifying a boolean value (True/False). We can also choose to display minor or major ticks or both. Also, color, linewidth and linestyle can be changed as additional parameters. Let’s look at some examples:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  # dummy datax1 = np.linspace(0.0, 5.0)y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)  # creates two subplotsfig, (ax1, ax2) = plt.subplots(1, 2, figsize = (12, 5))  # Plot without gridax1.plot(x1, y1)ax1.set_title('Plot without grid')  # plot with gridax2.plot(x1, y1)ax2.set_title("Plot with grid")  # draw gridlinesax2.grid(True)  plt.show()
Output:
Example #2:Now let’s draw gridlines using extra line properties such as color, linestyle and linewidth.
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np  # dummy datax = np.linspace(0, 2 * np.pi, 400)y = np.sin(x ** 2)  # set graph colorplt.plot(x, y, 'green')  # to set titleplt.title("Plot with linewidth and linestyle")  # draws gridlines of grey color using given # linewidth and linestyleplt.grid(True, color = "grey", linewidth = "1.4", linestyle = "-.")  plt.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
turtle.clearstamp() method in Python - GeeksforGeeks

21 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
The turtle.clearstamp() method is used to delete all or first/last n of turtle’s stamps. This method requires an argument of an integer. So, the stamp made with an id is cleared by it.
Syntax : turtle.clearstamp(stampid)
Parameter: 
stampid – an integer, must be return value of previous stamp() call.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle    # set turtle speed to slowest# for better understandingsturtle.speed(1)  # motion with stamps# and their idsturtle.forward(50)id1 = turtle.stamp()  turtle.forward(50)id2 = turtle.stamp()  turtle.forward(50)id3 = turtle.stamp()  # hide the turtle to# clarify stampsturtle.ht()  # clear the stamps# of id : id1 and id3turtle.clearstamp(id1)turtle.clearstamp(id3)
Output :
Example 2 :
Python3
# import packageimport turtle   # list to store idsids = []  # loop to create motion# with stampsfor i in range(12):          # motion    turtle.forward(50)          # stampid    id = turtle.stamp()    lst.append(id)    turtle.right(30)  # hide the turtle for # better understandingsturtle.ht()  # loop for clear stamps with # their ids using clearstamp# half stamps are clearedfor i in range(len(lst)//2):    turtle.clearstamp(lst[i])
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
Arduino - Blinking LED

LEDs are small, powerful lights that are used in many different applications. To start, we will work on blinking an LED, the Hello World of microcontrollers. It is as simple as turning a light on and off. Establishing this important baseline will give you a solid foundation as we work towards experiments that are more complex.
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × LED
1 × 330Ω Resistor
2 × Jumper
Follow the circuit diagram and hook up the components on the breadboard as shown in the image given below.
Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards the flat edge of the bulb indicates the negative terminal.
Components like resistors need to have their terminals bent into 90° angles in order to fit the breadboard sockets properly. You can also cut the terminals shorter.
Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open the new sketch File by clicking New.
/*
   Blink
   Turns on an LED on for one second, then off for one second, repeatedly.
*/

// the setup function runs once when you press reset or power the board

void setup() {  // initialize digital pin 13 as an output.
   pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
   digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
   delay(1000); // wait for a second
   digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
   delay(1000); // wait for a second
}
pinMode(2, OUTPUT) − Before you can use one of Arduino’s pins, you need to tell Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode() to do this.
digitalWrite(2, HIGH) − When you are using a pin as an OUTPUT, you can command it to be HIGH (output 5 volts), or LOW (output 0 volts).
You should see your LED turn on and off. If the required output is not seen, make sure you have assembled the circuit correctly, and verified and uploaded the code to your board.

    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
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider the basic COCOMO model where E is the effort applied in person-months, D is the development time in chronological months, KLOC is the estimated number of delivered lines of code (in thousands) and ab, bb, cb, db have their usual meanings. The basic COCOMO equations are of the form.(A) E = ab(KLOC) exp(bb), D = cb(E) exp(db)(B) D = ab(KLOC) exp(bb), E = cb(D) exp(db)(C) E = ab exp(bb), D = cb(KLOC) exp(db)(D) E = ab exp(db), D = cb(KLOC) exp(bb)Answer: (A)Explanation: In Basic COCOMO, following are true.

Effort Applied (E) = ab(KLOC)bb [ person-months ]Development Time (D) = cb(Effort Applied)db [months]People required (P) = Effort Applied / Development Time [count] 
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2012 | Question 40
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2014-(Set-3) | Question 65
How to get a specific column record from SELECT query in MySQL?

Let us first create a table −
mysql> create table DemoTable1837
     (
     StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
     StudentName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1837(StudentName) values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1837(StudentName) values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1837(StudentName) values('Bob');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1837(StudentName) values('Mike');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1837;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | David       |
|         3 | Bob         |
|         4 | Mike        |
+-----------+-------------+
4 rows in set (0.00 sec)
Here is the query to get a specific column records:
mysql> select StudentName from DemoTable1837;
This will produce the following output −
+-------------+
| StudentName |
+-------------+
| Chris       |
| David       |
| Bob         |
| Mike        |
+-------------+
4 rows in set (0.00 sec)
Divide each row by a vector element using NumPy - GeeksforGeeks

11 Oct, 2020
Prerequisite: Numpy module
The following article depicts how the rows of a Numpy array can be divided by a vector element. The vector element can be a single element, multiple element, or an array. Division operator ( / ) is employed to produce the required functionality.  We can divide rows of 1-D, 2-D, or even more types of arrays with vector element and the following examples will help you understand better:
Example 1: 
Python3
# Importing Numpy module import numpy as np  # Creating 1-D Numpy arrayn_arr = np.array([20, 30, 40])print("Given 1-D Array:")print(n_arr)  # Vector element vec = np.array([12])print("\nVector element:")print(vec)  # Dividing rows of 1-D array with vector elementprint("\nResultant Array")print(n_arr / vec[:,None])
Output:
In the above example, we divide the rows of 1-D Numpy array with vector element i.e [15]
Example 2:
Python3
# Importing Numpy module import numpy as np  # Creating 2-D Numpy arrayn_arr = np.array([[20, 35, 40],                [10, 51, 25]])  print("Given 2-D Array:")print(n_arr)  # Vector element vec = np.array([2.5])print("\nVector element:")print(vec)  # Dividing rows of 2-D array with vector elementprint("\nResultant Array")print(n_arr / vec[:,None])
Output:
In the above example, we divide the rows of 2-D Numpy array with vector element i.e [2.5]
Example 3:
Python3
# Importing Numpy module import numpy as np  # Creating 3-D Numpy arrayn_arr = np.array([[[10, 25], [30, 45]],                   [[50, 65], [70, 85]]])  print("Given 3-D Array:")print(n_arr)  # Vector element vec = np.array([3, 3])print("\nVector element:")print(vec)  # Dividing rows of 3-D array with vector elementprint("\nResultant Array")print(n_arr / vec[:,None])
Output:
In the above example, we divide the rows of 3-D Numpy array with vector element i.e [3, 3]
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Determine the Weekday on a Specific Date in R Programming - weekdays() Function - GeeksforGeeks

24 Jun, 2020
weekdays() function in R Language is used to determine the weekday on a specific date passed to it as argument.
Syntax: weekdays(date, abbreviate)
Parameters:date: Date to be checkedabbreviate: Boolean value to abbreviate weekday
Example 1:
# R program to find the weekday # on a specific date  # Specifying the datedate <- as.POSIXlt("2020-06-23")date  # Calling weekdays() functionweekdays(date)
Output:
[1] "2020-06-23 UTC"
[1] "Tuesday"

Example 2:
# R program to find the weekday # on a specific date  # Specifying the datedate <- as.POSIXlt("1994-06-17")date  # Calling weekdays() functionweekdays(date, abbreviate = TRUE)
Output:
[1] "1994-06-17 UTC"
[1] "Fri"

R Date-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
Control Statements in R Programming
How to import an Excel File into R ?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to Fix: ‘numpy.ndarray’ object has no attribute ‘index’ - GeeksforGeeks

28 Nov, 2021
‘numpy.ndarray’ object has no attribute ‘index’ is an attribute error which indicates that there is no index method or attribute available to use in Numpy array.
This error occurs when we try to find the index of a particular element in a Numpy array using the index method. Below code is an example when that ‘numpy.ndarray’ object has no attribute ‘index’ error can be thrown
Example:
Python3
# import necessary packagesimport numpy as np  # Create a Numpy arraynumbers = np.array([0, 1, 2, 9, 8, 0])  # finding the index value of 9 in # numbers arraynumbers.index(9)
Output
 As there is no method called index in Numpy it throws an attribute error.
To fix this error instead of using index method to find the index of an element use where method which returns an array consists of indexes of a specified element.
Syntax
Numpy.where(arrayName==value_to_find_index)
Example 1:
Specify an element in where method which exist in a Numpy array
Python3
# import necessary packagesimport numpy as np  # Create a Numpy arraynumbers = np.array([0, 1, 2, 9, 8, 0])  # finding the index value of 9 in # numbers arraynp.where(numbers == 9)
Output
(array([3], dtype=int64),)
 As Indexes in array starts from 0, Here in the numbers array 0th index consists of value 0, 1st index has value 1, 2nd index has value 2 and 3rd index has value 9 which is specified so it returned an array which contains a value 3.
Example 2:
Specify an element in where method such that the element we specified is occurred more than once in an array.
Python3
# import necessary packagesimport numpy as np  # Create a Numpy arraynumbers = np.array([0, 1, 2, 9, 8, 0])  # finding the index values of 0 in# numbers arraynp.where(numbers == 0)
Output:
(array([0, 5], dtype=int64),)
 As element 0 occurred 2 times in numbers array at 0th & 5th index so it return an array consists of 2 index values of element 0.
Example 3:
Pass an element to where method which is actually not in an array.
Python3
# import necessary packagesimport numpy as np  # Create a Numpy arraynumbers = np.array([0, 1, 2, 9, 8, 0])  # finding the index value of a number # which is not in numbers arraynp.where(numbers == 7)
Output
(array([], dtype=int64),)
If we pass an element to where method which is not in an array then it returns an empty array because there is no specified element at any index of an array. Here 7 is not present in numbers array so it returned an empty array. 
Picked
Python How-to-fix
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
What happens when more restrictive access is given to a derived class method in C++?

18 May, 2021
We have discussed a similar topic in Java here. Unlike Java, C++ allows to give more restrictive access to derived class methods. For example the following program compiles fine. 
C++
#include<iostream>using namespace std; class Base {public:    virtual int fun(int i) { }}; class Derived: public Base {private:    int fun(int x)   {  }}; int main(){  }
In the above program, if we change main() to following, will get compiler error because fun() is private in derived class. 
C++
int main(){    Derived d;    d.fun(1);    return 0;}
What about the below program? 
C++
#include<iostream>using namespace std; class Base {public:    virtual int fun(int i) { cout << "Base::fun(int i) called"; }}; class Derived: public Base {private:    int fun(int x)   { cout << "Derived::fun(int x) called"; }}; int main(){    Base *ptr = new Derived;    ptr->fun(10);    return 0;}
Output: 
 Derived::fun(int x) called 
In the above program, private function “Derived::fun(int )” is being called through a base class pointer, the program works fine because fun() is public in base class. Access specifiers are checked at compile time and fun() is public in base class. At run time, only the function corresponding to the pointed object is called and access specifier is not checked. So a private function of derived class is being called through a pointer of base class. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
simmytarika5
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++