code-rag-bench/online-tutorials huggingface dataset:
What are covariant return types in Java?

In general, in overriding, the method in a superclass and subclass have the same name and, parameters. But, when it comes to returning type, the method in the subclass can return the subtype of the return type of the method in the superclass.
If you observe the following example super class has a method named demoMethod() and it returns a value of the type list. If we override this method the method in the subclass can return a value of the type List (which is in the superclass) or, it can also return the subtype of the List (return type of the method in the super class) such as ArrayList, Stack, Vector etc.
In this scenario the sub class method returns an ArrayList, subtype of the return type of the super class i.e. List. This sub type (ArrayList) is known as covariant type.
Live Demo
class Test{
   int data =100;
   Test demoMethod(){
      return this;
   }
}
public class Sample extends Test{
   int data = 1000;
   Sample demoMethod(){
      return this;
   }
   public static void main(String args[]){
      Sample sam = new Sample();
      System.out.println(sam.demoMethod().data);
   }
}
1000
Basic Approximations in Python - GeeksforGeeks

11 Nov, 2019
Approximation means to estimate the value of something which is not exactly but rather nearly correct. It plays a vital role in the field of science and technology. Let’s start with the most widely seen example. Have you ever used the exact value of Pi? Of course not. It is a non-terminating irrational number with a very long value. If we go on to write the exact value of Pi, probably even this article won’t be sufficient to do so:
3.14159 26535 89793 23846 26433 83279...
So here’s where approximation comes to play. We usually approximate the value of Pi as 3.14 or in terms of a rational number 22/7. When you advanced to your high school, you probably must have seen a larger application of approximations in Mathematics which uses differentials to approximate the values of quantities like (36.6)^1/2 or (0.009) ^1/3. In computer science, we can use approximation to find the value or approximate the value of something using loops.
For example: Approximating the cube root of any number. Take a look at the process below:
# Python program to approximate # the cube root of 27guess = 0.0cube = 27increment = 0.0001epsilon = 0.1  # Finding the approximate valuewhile abs(guess**3 - cube) >= epsilon:    guess+=increment  # Checking the approximate valueif abs(guess**3 - cube) >= epsilon:    print("Failed on the cube root of",cube)else:    print(guess,"is close to the cube root of",cube) 
The output of the above code is:
2.9963000000018987 is close to the cube root of 27

As we can see that 2.99 is not the exact value of (27)^1/3 but very close to the exact value 3. This is what we call approximation. Here we used a series of computations to approximate the value. First we declare a variable guess = 0.0 which we will keep on increasing in a loop until its close to the cube root of 27. Another variable epsilon is chosen as less as possible to get a more accurate value. The line while abs(guess**3 - cube) >= epsilon: takes care of this. If it exits the loop with a value greater than epsilon, it means that we already crossed the approximated value and failed on the test. Else, it will return the value of guess.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
numpy.identity() in Python - GeeksforGeeks

05 Aug, 2021
numpy.identity(n, dtype = None) : Return a identity matrix i.e. a square matrix with ones on the main diagonal. 
Parameters : 
n     : [int] Dimension n x n of output array  
dtype : [optional, float(by Default)] Data type of returned array.  
Returns : 
identity array of dimension n x n,  with its main diagonal set to one, and all other elements 0.
 Example:
Python
# Python Programming illustrating# numpy.identity method import numpy as geek # 2x2 matrix with 1's on main diagonalb = geek.identity(2, dtype = float)print("Matrix b : \n", b)  a = geek.identity(4)print("\nMatrix a : \n", a)
Output :  
Matrix b : 
 [[ 1.  0.]
 [ 0.  1.]]

Matrix a : 
 [[ 1.  0.  0.  0.]
 [ 0.  1.  0.  0.]
 [ 0.  0.  1.  0.]
 [ 0.  0.  0.  1.]]
Note : These codes won’t run on online-ID. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
anshitaagarwal
adnanirshad158
Pyhton numpy-arrayCreation
Python-numpy
Python
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
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Can I set any of the attribute value of a WebElement in Selenium?

We can set any attribute value of a webelement in Selenium. Selenium can run Javascript commands by the executeScript method. The command to be executed is passed as an argument to the method.
Next, we have to identify the element with the help of the Javascript method document.getElementsByClassname. It returns a list of elements, to point to the first element we shall add index [0]. To set the attribute we shall use the setAttribute method.
Syntax for setting the style attribute −
JavascriptExecutor j = (JavascriptExecutor) driver;
js.executeScript
("document.getElementsByClassName('heading')[0].setAttribute('style', 'background-color: red')");
Let us set the background color of webelement to red.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class SetAttributeVal{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // Javascript executor to set background color to red
      JavascriptExecutor js = (JavascriptExecutor) driver;
      js.executeScript
      js.executeScript
      ("document.getElementsByClassName('heading')[0].setAttribute('style', 'background-color: red')");
      driver.quit();
   }
}
C Program for Hexagonal Pattern

We are given with an integer ‘n’ and the task is to generate the hexagonal pattern and display the final output.
Input-: n=5
Output-:
Input-: n = 4
Output-:
Approach we are using in the given program is as follows −
Input the number ‘n’ from user
Divide the entire pattern into three parts i.e. upper part, middle part and lower part Start loop i for printing the upper part of the pattern from i to 0 and i to be less than n and keep incrementing the value of i Start loop m for printing the middle part of the pattern from m to 0 and m to be less than n-2 and keep incrementing the value of m Start loop h for printing the lower part of the pattern from h to res and h to be greater than 0 and keep decrementing the value of h Keep printing the * with spaces.
START
Step 1-> declare function to print hexagonal pattern
   void pattern(int n)
   Declare and set int len = 2 * n - 1
   Loop For int i = 0 and i < n and i++
      declare and set int temp = i + n
      Loop For int k = 0 and k < temp and k++
         IF ((k == n + i - 1) || (k == n - i - 1))
            print *
         End
         Else
            print space
         End
            Print \n
      End
      Loop For int m = 0 and m < n - 2 and m++
         Loop For int j = 0 and j < len and j++
            if (j == 0 || j == len - 1)
               Print *
            End
            Else
               print space
            End
         End
         Print \n
      End
      declare and set int res = n - 1
      Loop For int h = res and h >= 0 and h--
         declare and set int temp2 = h + n
         Loop For int k = 0 and k < temp2 and k++
            if ((k == n + h - 1) || (k == n - h - 1))
               print *
            End
            Else
               print space
            End
         End
         Print \n
      End
   End
Step 2-> In main()
   Declare variable int n = 5
   call pattern(n)
STOP
#include <stdio.h>
//program to print hexagon pattern  
void pattern(int n) {
   int len = 2 * n - 1;
   //for loop for upper part of a pattern
   for (int i = 0; i < n; i++) {
      int temp = i + n;
      for (int k = 0; k < temp; k++) {
         if ((k == n + i - 1) || (k == n - i - 1))
            printf("*");
         else
            printf(" ");
      }
      printf("\n");
   }
   //for loop for mid part of a pattern
   for (int m = 0; m < n - 2; m++) {
      for (int j = 0; j < len; j++) {
         if (j == 0 || j == len - 1)
            printf("*");
         else
            printf(" ");
      }
      printf("\n");
   }
   //for loop for lower part of a pattern
   int res = n - 1;
   for (int h = res; h >= 0; h--) {
      int temp2 = h + n;
      for (int k = 0; k < temp2; k++) {
         if ((k == n + h - 1) || (k == n - h - 1))
            printf("*");
         else
            printf(" ");
      }
      printf("\n");
   }
}
int main() {
   int n = 5;
   pattern(n);
   return 0;
}
How to exclude certain values from randomly generated array JavaScript

We have to create a function that takes in 2 arguments: an integer and an array of integers.
First argument denotes the length of array we have to return and the second argument contains
the elements that should not be present in our return array. Actually, we need an array of
random numbers between 0 to 100 but it should not include any element that’s present in the
argument array.
Note − No two numbers should be duplicate.
Let’s call our function generateRandom(). The code for this would be −
const absentArray = [44, 65, 5, 34, 87, 42, 8, 76, 21, 33];
const len = 10;
const generateRandom = (len, absentArray) => {
   const randomArray = [];
   for(let i = 0; i < len; ){
      const random = Math.floor(Math.random() * 100);
   if(!absentArray.includes(random) &&
      !randomArray.includes(random)){
         randomArray.push(random);
         i++;
      }
   };
   return randomArray;
}
console.log(generateRandom(len, absentArray));
Output in the console will be −
[
   23, 93, 29, 25, 37,
   63, 54, 11, 69, 79
]
Apache Pig - SUBSTRING()

This function returns a substring from the given string.
Given below is the syntax of the SUBSTRING() function. This function accepts three parameters one is the column name of the string we want. And the other two are the start and stop indexes of the required substring.
grunt> SUBSTRING(string, startIndex, stopIndex) 

Assume that there is a file named emp.txt in the HDFS directory /pig_data/ as shown below. This file contains the employee details such as id, name age and city.
emp.txt
001,Robin,22,newyork
002,Stacy,25,Bhuwaneshwar 
003,Kelly,22,Chennai

And, we have loaded this file into Pig with a relation named emp_data as shown below.
grunt> emp_data = LOAD 'hdfs://localhost:9000/pig_data/emp.txt' USING PigStorage(',')as (id:int, name:chararray, age:int, city:chararray);
Following is an example of the SUBSTRING() function. This example fetches the sub strings that starts with 0th letter and ends with 2nd letter from the employee names.
grunt> substring_data = FOREACH emp_data GENERATE (id,name), SUBSTRING (name, 0, 2);
The above statement fetches the required substrings from the names of the employees. The result of the statement will be stored in the relation named substring_data.
Verify the content of the relation substring_data, using the Dump operator as shown below.
grunt> Dump substring_data;

((1,Robin),Rob)
((2,Stacy),Sta)
((3,Kelly),Kel) 


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
C# Break and Continue

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a 
loop.
This example jumps out of the loop when i is equal to 4:
for (int i = 0; i < 10; i++) 
{
  if (i == 4) 
  {
    break;
  }
  Console.WriteLine(i);
}
 


Try it Yourself »

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
This example skips the value of 4:
for (int i = 0; i < 10; i++) 
{
  if (i == 4) 
  {
    continue;
  }
  Console.WriteLine(i);
}
 


Try it Yourself »

You can also use break and continue in while loops:
int i = 0;
while (i < 10) 
{
  Console.WriteLine(i);
  i++;
  if (i == 4) 
  {
    break;
  }
}
 


Try it Yourself »

int i = 0;
while (i < 10) 
{
  if (i == 4) 
  {
    i++;
    continue;
  }
  Console.WriteLine(i);
  i++;
}
 


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
What are generic delegates in C#?

Using generic delegates, you do not need to define the delegate statement. They are defined in the System namespace.
You can define a generic delegate with type parameters. For example −
delegate T myDelegete<T>(T n);
The following is an example showing how to create generic delegates in C# −
using System;
using System.Collections.Generic;

delegate T myDelegete<T>(T n);
namespace GenericDelegateAppl {
   class TestDelegate {
      static int num = 5;

      public static int AddNum(int p) {
         num += p;
         return num;
      }

      public static int MultNum(int q) {
         num *= q;
         return num;
      }

      public static int getNum() {
         return num;
      }

      static void Main(string[] args) {
         //create delegate instances
         NumberChanger nc1 = new NumberChanger(AddNum);
         NumberChanger nc2 = new NumberChanger(MultNum);

         //calling the methods using the delegate objects
         nc1(50);
         Console.WriteLine("Value of Num: {0}", getNum());

         nc2(10);
         Console.WriteLine("Value of Num: {0}", getNum());
         Console.ReadKey();
      }
   }
}
Indent the first line of a paragraph in CSS

Use the text-indent property to indent the first line of a paragraph. Possible values are % or a number specifying indent space.
You can try to run the following code to indent the first line:
<html>
   <head>
   </head>
   <body>
      <p style = "text-indent:2cm;">
         This text will have first line indented by 2cm and this line will remain at
         its actual position this is done by CSS text-indent property.
      </p>
   </body>
</html>
SAP Placement Questions

17 May, 2021
L: Means turn Right . R: Means turn Left. Numbers represent the distance traveled in a particular direction in meters. ( If Alice is initially facing north, and is given the instruction, 3L4L5R2L3R3R2R4R3L1L3R4R2R3R), which direction would she face and how much distance would she cover?ans : 42m,north—————————————————————————————————————-2. JavaScript syntax for is not equal? ans: operator is : !!! – not not—————————————————————————————————————-3..  
C
#include<stio.h>#define TRUE 0 void main(){   int i = 0;   while (TRUE){     printf("%d\n",i);     i++;   }   printf("%d\n",i);   i++;}
output: 0 —————————————————————————————————————–If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
SAP Labs
Interview Experiences
SAP Labs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE 1
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Amazon Interview Experience SDE-2 (3 Years Experienced)
Write It Up: Share Your Interview Experiences
TCS Ninja Interview Experience (2020 batch)
Nagarro Interview Experience | On-Campus 2021
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
Samsung RnD Coding Round Questions
Hyperplane, Subspace and Halfspace

03 Jul, 2020
1. Hyperplane :Geometrically, a hyperplane is a geometric entity whose dimension is one less than that of its ambient space.
What does it mean? It means the following. For example, if you take the 3D space then hyperplane is a geometric entity that is 1 dimensionless. So it’s going to be 2 dimensions and a 2-dimensional entity in a 3D space would be a plane. Now if you take 2 dimensions, then 1 dimensionless would be a single-dimensional geometric entity, which would be a line and so on. 
The hyperplane is usually described by an equation as follows XT n + b =0
XT n + b =0
If we expand this out for n variables we will get something like this X1n1 + X2n2 + X3n3 + ........... + Xnnn + b = 0
If we expand this out for n variables we will get something like this 
X1n1 + X2n2 + X3n3 + ........... + Xnnn + b = 0
In just two dimensions we will get something like this which is nothing but an equation of a line. X1n1 + X2n2 + b = 0
In just two dimensions we will get something like this which is nothing but an equation of a line. 
X1n1 + X2n2 + b = 0
Example: 
Let us consider a 2D geometry with

Though it's a 2D geometry the value of X will be

So according to the equation of hyperplane it can be solved as

So as you can see from the solution the hyperplane is the equation of a line. 

2. Subspace :Hyper-planes, in general, are not sub-spaces. However, if we have hyper-planes of the form,
XT n =0
That is if the plane goes through the origin, then a hyperplane also becomes a subspace.
3. Half-space :Consider this 2-dimensional picture given below.
So, here we have a 2-dimensional space in X1 and X2 and as we have discussed before, an equation in two dimensions would be a line which would be a hyperplane. So, the equation to the line is written as
XT n + b =0 
So, for this two dimensions, we could write this line as we discussed previously 
X1n1 + X2n2 + b = 0
You can notice from the above graph that this whole two-dimensional space is broken into two spaces; One on this side(+ve half of plane) of a line and the other one on this side(-ve half of the plane) of a line. Now, these two spaces are called as half-spaces.
Example:
Let’s consider the same example that we have taken in hyperplane case. So by solving, we got the equation as 
x1 + 3x2 + 4 = 0
There may arise 3 cases. Let’s discuss each case with an example.
Case 1:
x1 + 3x2 + 4 = 0 : On the line
Let consider two points (-1,-1). When we put this value on the equation of line we got 0. So we can say that this point is on the hyperplane of the line. 
Case 2: Similarly, 
x1 + 3x2 + 4 > 0 : Positive half-space
Consider two points (1,-1). When we put this value on the equation of line we got 2 which is greater than 0. So we can say that this point is on the positive half space. Case 3: 
x1 + 3x2 + 4 < 0 : Negative half-space
Consider two points (1,-2). When we put this value on the equation of line we got -1 which is less than 0. So we can say that this point is on the negative half-space.  
data-science
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.path.join() method

31 May, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub-module of OS module in Python used for common pathname manipulation.os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory separator (‘/’) is put at the end. If a path component represents an absolute path, then all previous components joined are discarded and joining continues from the absolute path component. 
Syntax: os.path.join(path, *paths) Parameter: path: A path-like object representing a file system path. *path: A path-like object representing a file system path. It represents the path components to be joined. A path-like object is either a string or bytes object representing a path.Note: The special syntax *args (here *paths) in function definitions in python is used to pass a variable number of arguments to a function. Return Type: This method returns a string which represents the concatenated path components.  
Code: Use of os.path.join() method to join various path components  
Python3
# Python program to explain os.path.join() method   # importing os moduleimport os # Pathpath = "/home" # Join various path componentsprint(os.path.join(path, "User/Desktop", "file.txt"))  # Pathpath = "User/Documents" # Join various path componentsprint(os.path.join(path, "/home", "file.txt")) # In above example '/home'# represents an absolute path# so all previous components i.e User / Documents# are thrown away and joining continues# from the absolute path component i.e / home.  # Pathpath = "/User" # Join various path componentsprint(os.path.join(path, "Downloads", "file.txt", "/home")) # In above example '/User' and '/home'# both represents an absolute path# but '/home' is the last value# so all previous components before '/home'# will be discarded and joining will# continue from '/home' # Pathpath = "/home" # Join various path componentsprint(os.path.join(path, "User/Public/", "Documents", "")) # In above example the last# path component is empty# so a directory separator ('/')# will be put at the end# along with the concatenated value
/home/User/Desktop/file.txt
/home/file.txt
/home
/home/User/Public/Documents/
 
Reference: https://docs.python.org/3/library/os.path.html 
anikakapoor
Python OS-path-module
python-os-module
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | Decimal step range in list

03 Oct, 2019
Sometimes, while working with Python list we can have a problem in which we require to populate the list in a range of decimal. Integral ranges are easier to handle using inbuilt constructs, but having a decimal value to provide to range value doesn’t work. Let’s discuss a way in which this problem can be solved.
Method : Using list comprehensionOne way to solve this problem is by using the list comprehension which can solve this problem in easier way by iterating the list and multiplying the range element to the index of element.
# Python3 code to demonstrate working of# Decimal step range in list# using list comprehension  # initializing start value strt = 5  # initializing step value step = 0.4  # using list comprehension# Decimal step range test_list = [strt + (x * step) for x in range(0, 5)]  # Printing resultprint("The list after decimal range value initialization : " + str(test_list))
 
The list after decimal range value initialization : [5.0, 5.4, 5.8, 6.2, 6.6]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to calculate multiplication and division of two numbers using JavaScript ?

31 Mar, 2021
An arithmetic operation operates on two numbers and numbers are called operands. 
Multiplication The multiplication operator (*) multiplies two or more numbers.
Example:
var a =1 5;
var b = 12;
var c = a × b;

Approach: Create the html form to take input from user to perform multiplication operation. Add javascript code inside html to perform multiplication logic. Document.getElementById(id).value property returns the value of the value attribute of a text field.
Below is the implementation of the above approach:
HTML
<!DOCTYPE html><html>  <head>  <style type="text/css">    body {      margin: 30px;    }  </style></head>  <body>  <form>    1st Number : <input type="text"     id="firstNumber" /><br>    2nd Number: <input type="text"     id="secondNumber" /><br>    <input type="button" onClick="multiplyBy()"     Value="Multiply" /><br>  </form>    <p>The Result is : <br>   <span id = "result"></span>  </p>      <script>    function multiplyBy()    {      num1 = document.getElementById(        "firstNumber").value;      num2 = document.getElementById(        "secondNumber").value;      document.getElementById(        "result").innerHTML = num1 * num2;    }  </script></body>  </html>
Output:
Multiplication of 2 numbers
Division The division operator (/) divides two or more numbers.
Example:
var a = 50;
var b = 20;
var c = a / b;

Approach: Create the html form to take input from user to perform division operation. Add JavaScript code inside html to perform division logic. Document.getElementById(id).value property returns the value of the value attribute of a text field.
Below is the implementation of the above approach:
HTML
<!DOCTYPE html><html>  <head>  <style type="text/css">    body {      margin: 30px;    }  </style></head>  <body>  <form>    1st Number : <input type="text"    id="firstNumber" /><br>    2nd Number: <input type="text"     id="secondNumber" /><br>    <input type="button" onClick="divideBy()"      Value="Divide" />  </form>    <p>The Result is : <br>    <span id = "result"></span>  </p>      <script>    function divideBy()     {       num1 = document.getElementById(        "firstNumber").value;      num2 = document.getElementById(        "secondNumber").value;      document.getElementById(        "result").innerHTML = num1 / num2;    }  </script></body>  </html>
Output:
Division of 2 numbers
javascript-operators
JavaScript-Questions
Picked
JavaScript
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
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How can I execute JavaScript at the command prompt?

Java SE 8 came with a new engine called Nashorn, which is based on JSR 292. It provides compliance with the ECMA normalized JavaScript.
You can run JavaScript programs from the command line using Nashorn. Include a command-line tool called jjs. The bin folder of a JDK installation has it, with other tools like jar.
Here’s the js file new.js −
var display = function() {
   // print “Hello World!” here
};
display();
Run it on a command prompt −
$ jjs new.js
Hello World!
$
GATE | GATE CS 1999 | Question 9

04 Feb, 2020
Listed below are some operating system abstractions (in the left column) and the hardware components or mechanism (in the right column) that they are abstractions of. Which of the following matching of pairs is correct?
A. Thread                      1. Interrupt
B. Virtual address space       2. Memory
C. File system                 3. CPU
D. Signal                      4. Disk
(A) A-2, B-4, C-3, D-1(B) A-1, B-2, C-3, D-4(C) A-3, B-2, C-4, D-1(D) A-4, B-1, C-2, D-3Answer: (C)Explanation:
Thread is handled by CPU.Virtual address space (it is a set of virtual memory addresses that a process can use) is associated with memory management.File System is used for disk management.Interrupt is a type of signal.
Thread is handled by CPU.
Virtual address space (it is a set of virtual memory addresses that a process can use) is associated with memory management.
File System is used for disk management.
Interrupt is a type of signal.
Quiz of this Question
VeenaSreekumarNair
GATE CS 1999
GATE-GATE CS 1999
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 40
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
How to Install Java JDK11 on AWS EC2?

16 Dec, 2021
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer 
In this article, we will learn how to Java JDK11 on AWS EC2.
AWS account.EC2 Instance.User with privileges to create Instance.
AWS account.
EC2 Instance.
User with privileges to create Instance.
Follow the steps below to install Java JDK11 on AWS EC2:
Step 1: Create an AWS Elastic Cloud Compute Instance.
Step 2: Start the EC2 instance that you have created in Step 1.
Step 3: Connect to your EC2 Instance by clicking on Connect Button.
Step 4: A prompt will pop up after connecting.
Step 5: At first check, if Java JDK is already installed or not.
java --version
Step 6: If Java JDK is not installed on your virtual machine then install the Java JDK using the following command
sudo apt install openjdk-11-jdk-headless
Step 7: Wait for the process to end.
Step 8: We have successfully installed Java JDK11 on our EC2  instance, to check if JDK11 is installed or not, verify using the following command.
java --version
In this way, we can install Java JDK 11 on our EC2 instance using EC2 Instance Connect.
Let’s try to create a Java program and then execute that Java program on our EC2 instance:
Java
//java program to calculate sum of two numbersimport java.io.*;class GFG {    public static void main(String[] args)    {        int x = 10, y = 20;        int sum = x + y;        System.out.println("Sum is : " + sum);    }}
Use the following command to compile and execute our java program on AWS EC2 Instance –
To Compile - javac example1.java
To Execute - java GFG
Output
Note: if you also use a free tier account, make sure you delete all the resources you have used before logging out.  
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to use strconv.Itoa() Function in Golang?

03 May, 2020
Go language provides inbuilt support to implement conversions to and from string representations of basic data types by strconv Package. This package provides an Itoa() function which is equivalent to FormatInt(int64(x), 10). Or in other words, Itoa() function returns the string representation of x when the base is 10. To access Itoa() function you need to import strconv Package in your program with the help of import keyword.
Syntax:
 func Itoa(x int) string
Parameter: This function takes one parameter of int type, i.e., x.
Return value: This function returns a string that represents x.
Let us discuss this concept with the help of the given examples:
Example 1:
// Golang program to illustrate// strconv.Itoa() Functionpackage main  import (    "fmt"    "strconv")  func main() {      // Finding a string representation of    // the given value when the base is 10    // Using Itoa() function    fmt.Println(strconv.Itoa(23))    fmt.Println(strconv.Itoa(45))  }
Output:
23
45

Example 2:
// Golang program to illustrate// strconv.Itoa() Functionpackage main  import (    "fmt"    "strconv")  func main() {      // Finding a string representation of    // the given value when the base is 10    // Using Itoa() function    val1 := int(24)    res1 := strconv.Itoa(val1)    fmt.Printf("Result 1: %v", res1)    fmt.Printf("\nType 1: %T", res1)      val2 := int(-21)    res2 := strconv.Itoa(val2)    fmt.Printf("\nResult 2: %v", res2)    fmt.Printf("\nType 2: %T", res2)  }
Output:
Result 1: 24
Type 1: string
Result 2: -21
Type 2: string

Golang-strconv
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Time Durations in Golang
Loops in Go Language
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
turtle.xcor() function in Python

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.
This function is used to return the turtle’s x coordinate of the current position of turtle. It doesn’t require any argument.
Syntax :
turtle.xcor()

Below is the implementation of the above method with an example :
Example :
Python3
# import packageimport turtle  # check x coordinateprint(turtle.xcor())turtle.forward(100)  # check x coordinateprint(turtle.xcor())turtle.right(45)turtle.forward(100)  # check x coordinateprint(turtle.xcor())turtle.right(90)turtle.forward(100)  # check x coordinateprint(turtle.xcor())turtle.right(45)turtle.forward(100)  # check x coordinateprint(turtle.xcor())
Output :
0.0
100.0
170.710678119
100.0
0.0

Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to find day of the week for a given date

26 Jul, 2021
Write a Python program to find the day of the week for any particular date in the past or future. Let the input be in the format “dd mm yyyy”.Examples:  
Input : 03 02 1997 
Output : Monday

Input : 31 01 2019
Output : Thursday
The already discussed approach to find the day of the week for a given date is the Naive approach. Now, let’s discuss the pythonic approaches. Approach #1 : Using weekday() provided by datetime module.The weekday() function of date class in datetime module, returns an integer corresponding to the day of the week.  
Python3
# Python program to Find day of# the week for a given dateimport datetimeimport calendar def findDay(date):    born = datetime.datetime.strptime(date, '%d %m %Y').weekday()    return (calendar.day_name[born]) # Driver programdate = '03 02 2019'print(findDay(date))
Sunday
 
  Approach #2 : Using strftime() methodThe strftime() method takes one or more format codes as an argument and returns a formatted string based on it. Here we will pass the directive “%A” in the method which provides Full weekday name for the given date.  
Python3
# Python program to Find day of# the week for a given dateimport datetimefrom datetime import dateimport calendar def findDay(date):    day, month, year = (int(i) for i in date.split(' '))       born = datetime.date(year, month, day)    return born.strftime("%A") # Driver programdate = '03 02 2019'print(findDay(date))
Sunday
 
  Approach #3 : By finding day number In this approach, we find the day number using calendar module and then find the corresponding week day.  
Python3
# Python program to Find day of# the week for a given dateimport calendar def findDay(date):    day, month, year = (int(i) for i in date.split(' '))       dayNumber = calendar.weekday(year, month, day)    days =["Monday", "Tuesday", "Wednesday", "Thursday",                         "Friday", "Saturday", "Sunday"]    return (days[dayNumber]) # Driver programdate = '03 02 2019'print(findDay(date))
Sunday
 
sagar0719kumar
simranarora5sos
date-time-program
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
PyQt5 | How to set percentage indicator in middle of Progress Bar ? - GeeksforGeeks

22 Apr, 2020
In this article we will see how to set the percentage indicator inside the progress bar. When we create a progress bar the percentage indicator is by default is at right hand side of the progress bar i.e outside the progress bar.
Below is how normal percentage indicator looks like vs how it look inside it. 
In order to do this we will do the following :
1. Create a progress bar.2. Set its alignment to center
In order to change the alignment of progress bar we will use setAlignment method.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating progress bar        bar = QProgressBar(self)          # setting geometry to progress bar        bar.setGeometry(200, 150, 200, 30)          # set value to progress bar        bar.setValue(70)                  # changing the alignment of progress bar        bar.setAlignment(QtCore.Qt.AlignCenter)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
p5.js | remove() Function - GeeksforGeeks

20 Aug, 2019
The remove() function is an inbuilt function which is used to remove the element and deregister all listeners.
This function requires p5.dom library. So add the following line in the head section of the index.html file.
<script language="javascript"    type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:
remove()
Parameters: This function does not accepts any parameters.
Below examples illustrate the remove() function in p5.js:
Example 1: This example creates an element.
function setup() {           // Create Canvas of given size     var cvs = createCanvas(600, 250);}  function draw() {      // Set the background color  background('green');       // Use createDiv() function to  // create a div element  var myDiv = createDiv('Welcome to GeeksforGeeks');      // Set the position of div element  myDiv.position(150, 100);        // Set the font-size of text  myDiv.style('font-size', '24px');      // Set the font color  myDiv.style('color', 'white');      // Comment the remove() function   // myDiv.remove();}
Output:
Example 2: This example uses remove() function to remove the element.
function setup() {           // Create Canvas of given size     var cvs = createCanvas(600, 250);}  function draw() {      // Set the background color  background('green');       // Use createDiv() function to  // create a div element  var myDiv = createDiv('Welcome to GeeksforGeeks');      // Set the position of div element  myDiv.position(150, 100);        // Set the font-size of text  myDiv.style('font-size', '24px');      // Set the font color  myDiv.style('color', 'white');      // Use remove() function to remove div element  myDiv.remove();}
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
File uploading in React.js
Top 10 Front End Developer Skills That You Need 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?
JavaScript Function Call - GeeksforGeeks

15 Nov, 2021
The Function call is a predefined javascript method, which is used to write methods for different objects. It calls the method, taking the owner object as an argument. The keyword this refers to the “owner” of the function or the object it belongs to. All the functions in javascript are considered as object methods. A function will be the global object if the function is not considered as a method of a JavaScript object.
Syntax:
call()
Return Value: It calls and returns a method with the owner object being the argument.
Example 1: This example describes the use of the call() method to call the employee as the argument. 
HTML
<!DOCTYPE html><html>  <head>    <title>JavaScript Function Call</title></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>JavaScript Function Call</h2>    <p> It calls the employee details of emp2 </p>      <p id="GFG"></p>            <!-- Script to use call() method and display        the emp2 details -->    <script>    var employee = {        details: function() {            return this.name + " " + this.id;        }    }    var emp1 = {        name: "Geeks",        id: "234412",    }    var emp2 = {        name: "G4G",        id: "434556",    }    var x = employee.details.call(emp2);    document.getElementById("GFG").innerHTML = x;    </script></body>  </html>
Output:
Function Call() Method
Example 2: This example describes the use of function call with arguments.
HTML
<!DOCTYPE html><html>  <head>    <title> The call() Method with Arguments </title></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>JavaScript Function Call</h2>    <p> It calls the employee details of emp2 </p>      <p id="GFG"></p>            <script>    var employee = {        details: function(designation, experience) {            return this.name             + " "             + this.id + "<br>"             + designation             + "<br>"             + experience;        }    }    var emp1 = {        name: "A",        id: "123",    }    var emp2 = {        name: "B",        id: "456",    }    var x = employee.details.call(emp2, "Manager", "4 years");    document.getElementById("GFG").innerHTML = x;    </script></body>  </html>
Output:
Function Call() Method with an argument
Supported Browser:
Google Chrome 1.0
Firefox 1.0
Microsoft Edge 12.0
Internet Explorer 5.5
Opera 4.0
Safari 1.0
bhaskargeeksforgeeks
javascript-functions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need 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?
Python Program for Efficient program to print all prime factors of a given number

30 Nov, 2018
Given a number n, write an efficient function to print all prime factors of n. For example, if the input number is 12, then output should be “2 2 3”. And if the input number is 315, then output should be “3 3 5 7”.Following are the steps to find all prime factors.1) While n is divisible by 2, print 2 and divide n by 2.2) After step 1, n must be odd. Now start a loop from i = 3 to square root of n. While i divides n, print i and divide n by i, increment i by 2 and continue.3) If n is a prime number and is greater than 2, then n will not become 1 by above two steps. So print n if it is greater than 2.
# Python program to print prime factors  import math  # A function to print all prime factors of # a given number ndef primeFactors(n):          # Print the number of two\'s that divide n    while n % 2 == 0:        print 2,        n = n / 2              # n must be odd at this point    # so a skip of 2 ( i = i + 2) can be used    for i in range(3,int(math.sqrt(n))+1,2):                  # while i divides n , print i ad divide n        while n % i== 0:            print i,            n = n / i                  # Condition if n is a prime    # number greater than 2    if n > 2:        print n          # Driver Program to test above function  n = 315primeFactors(n)  # This code is contributed by Harshit Agrawal
Output:
3 3 5 7
How does this work?The steps 1 and 2 take care of composite numbers and step 3 takes care of prime numbers. To prove that the complete algorithm works, we need to prove that steps 1 and 2 actually take care of composite numbers. This is clear that step 1 takes care of even numbers. And after step 1, all remaining prime factor must be odd (difference of two prime factors must be at least 2), this explains why i is incremented by 2.Now the main part is, the loop runs till square root of n not till. To prove that this optimization works, let us consider the following property of composite numbers.Every composite number has at least one prime factor less than or equal to square root of itself.This property can be proved using counter statement. Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”.
In step 2 of the above algorithm, we run a loop and do following in loopa) Find the least prime factor i (must be less than √n,)b) Remove all occurrences i from n by repeatedly dividing n by i.c) Repeat steps a and b for divided n and i = i + 2. The steps a and b are repeated till n becomes either 1 or a prime number.
Please refer complete article on Efficient program to print all prime factors of a given number for more details!
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.