code-rag-bench/online-tutorials huggingface dataset:
jsoup - Working with URLs

Following example will showcase methods which can provide relative as well as absolute URLs present in the html page.
String url = "http://www.tutorialspoint.com/";
Document document = Jsoup.connect(url).get();
Element link = document.select("a").first();         

System.out.println("Relative Link: " + link.attr("href"));
System.out.println("Absolute Link: " + link.attr("abs:href"));
System.out.println("Absolute Link: " + link.absUrl("href"));

Where
document − document object represents the HTML DOM.
document − document object represents the HTML DOM.
Jsoup − main class to connect to a url and get the html content.
Jsoup − main class to connect to a url and get the html content.
link − Element object represent the html node element representing anchor tag.
link − Element object represent the html node element representing anchor tag.
link.attr("href") − provides the value of href present in anchor tag. It may be relative or absolute.
link.attr("href") − provides the value of href present in anchor tag. It may be relative or absolute.
link.attr("abs:href") − provides the absolute url after resolving against the document's base URI.
link.attr("abs:href") − provides the absolute url after resolving against the document's base URI.
link.absUrl("href") − provides the absolute url after resolving against the document's base URI.
link.absUrl("href") − provides the absolute url after resolving against the document's base URI.
Element object represent a dom elment and provides methods to get relative as well as absolute URLs present in the html page.
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class JsoupTester {
   public static void main(String[] args) throws IOException {
   
      String url = "http://www.tutorialspoint.com/";
      Document document = Jsoup.connect(url).get();

      Element link = document.select("a").first();
      System.out.println("Relative Link: " + link.attr("href"));
      System.out.println("Absolute Link: " + link.attr("abs:href"));
      System.out.println("Absolute Link: " + link.absUrl("href"));
   }
}
Compile the class using javac compiler as follows:
C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.
C:\jsoup>java JsoupTester

See the result.
Relative Link: index.htm
Absolute Link: https://www.tutorialspoint.com/index.htm
Absolute Link: https://www.tutorialspoint.com/index.htm

 Print
 Add Notes
 Bookmark this page
HTML | <textarea> name Attribute - GeeksforGeeks

27 May, 2019
The HTML <textarea> name Attribute is used to specify a name of the <Textarea> Element. It is used to reference the form-data after submitting the form or to reference the element in a JavaScript.
Syntax:
<Textarea name="text"> 
Attribute Values: It contains the value i.e name which specify the name for the <Textarea> element.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML Textarea name Attribute    </title></head>  <body>  <center>    <h1 style="color: green;">             GeeksforGeeks         </h1>      <h2>             HTML Textarea name Attribute         </h2>      <textarea id="GFG" name="GFG_text">        A computer science portal for geeks.    </textarea>      <br>  </center></body>  </html>
Output:
Supported Browsers:
Google Chrome
Firefox
Edge
Opera
Apple Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Multilevel inheritance in Java

Multilevel inheritance - A class inherits properties from a class which again has inherits properties.
 Live Demo
class Shape {
   public void display() {
      System.out.println("Inside display");
   }
}
class Rectangle extends Shape {
   public void area() {
      System.out.println("Inside area");
   }
}
class Cube extends Rectangle {
   public void volume() {
      System.out.println("Inside volume");
   }
}
public class Tester {
   public static void main(String[] arguments) {
      Cube cube = new Cube();
      cube.display();
      cube.area();
      cube.volume();
   }
}
Inside display
Inside area
Inside volume
Difference between PX, EM and Percent

The px unit defines a measurement in screen pixels. The following is an example −
div {
   padding: 40px;
}
The em unit is a relative measurement for the height of a font in em spaces. Because an em unit is equivalent to the size of a given font, if you assign a font to 12pt, each "em" unit would be 12pt; thus, 2em would be 24pt.
The following is an example −
p {
   letter-spacing: 4em;
}
The % unit defines a measurement as a percentage relative to another value, typically an enclosing element.
p {
   font-size: 14pt;
   line-height: 80%;
}
Add new field to every document in a MongoDB collection?

To add new field to every document in a MongoDB collection, you can use $set operator. The syntax is as follows:
db.yourCollectionName.update({}, { $set: {"yourFieldName": yourValue} }, false, true);
To understand the above syntax, let us create a collection with some documents. The query to create a collection with documents is as follows:
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"John","StudentAddress":"US
"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6efc0b6fd07954a48906ae")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"David","StudentAddress":"U
K"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6efc0b6fd07954a48906af")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"Carol","StudentAddress":"U
K"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6efc0b6fd07954a48906b0")
}
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"Bob","StudentAddress":"US"
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6efc0b6fd07954a48906b1")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.addNewFieldToEveryDocument.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906ae"),
   "StudentName" : "John",
   "StudentAddress" : "US"
}
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906af"),
   "StudentName" : "David",
   "StudentAddress" : "UK"
}
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906b0"),
   "StudentName" : "Carol",
   "StudentAddress" : "UK"
}
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906b1"),
   "StudentName" : "Bob",
   "StudentAddress" : "US"
}
The following is the query to add a new field to every document:
> db.addNewFieldToEveryDocument.update({}, { $set: {"StudentAge": 24} }, false, true);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
Above, we have added a new field “StudentAge”:24 in every document. Let us check the field “StudentAge”:24 is successfully added to every document or not. The query is as follows:
> db.addNewFieldToEveryDocument.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906ae"),
   "StudentName" : "John",
   "StudentAddress" : "US",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906af"),
   "StudentName" : "David",
   "StudentAddress" : "UK",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906b0"),
   "StudentName" : "Carol",
   "StudentAddress" : "UK",
   "StudentAge" : 24
}
{
   "_id" : ObjectId("5c6efc0b6fd07954a48906b1"),
   "StudentName" : "Bob",
   "StudentAddress" : "US",
   "StudentAge" : 24
}
Python Program for Comb Sort - GeeksforGeeks

27 Jan, 2022
Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more than one inversion counts with one swap and performs better than Bubble Sort.The shrink factor has been empirically found to be 1.3 (by testing Combsort on over 200,000 random lists) [Source: Wiki]Although, it works better than Bubble Sort on average, worst case remains O(n2).  
Python
# Python program for implementation of CombSort # To find next gap from currentdef getNextGap(gap):     # Shrink gap by Shrink factor    gap = (gap * 10)/13    if gap < 1:        return 1    return gap # Function to sort arr[] using Comb Sortdef combSort(arr):    n = len(arr)     # Initialize gap    gap = n     # Initialize swapped as true to make sure that    # loop runs    swapped = True     # Keep running while gap is more than 1 and last    # iteration caused a swap    while gap !=1 or swapped == 1:         # Find next gap        gap = getNextGap(gap)         # Initialize swapped as false so that we can        # check if swap happened or not        swapped = False         # Compare all elements with current gap        for i in range(0, n-gap):            if arr[i] > arr[i + gap]:                arr[i], arr[i + gap]=arr[i + gap], arr[i]                swapped = True  # Driver code to test abovearr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0]combSort(arr) print ("Sorted array:")for i in range(len(arr)):    print (arr[i]),  # This code is contributed by Mohit Kumra
Output :  
Sorted array: 
-44 -6 0 1 3 4 8 23 28 56 
Please refer complete article on Comb Sort for more details! 
sumitgumber28
python sorting-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python | Get the first key in dictionary
Python Program for Merge Sort
Python | Find most frequent element in a list
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python program to find smallest number in a list
Python - Convert JSON to string
Multimethods in Python - GeeksforGeeks

21 Apr, 2020
Multimethod basically means a function that has multiple versions, distinguished by the type of the arguments. For better understanding consider the below example.
@multimethod
def sum(x: int, y: int):
    return x + y

@multimethod
def sum(x: str, y: str):
    return x+" "+y

The above example is similar to

def sum(x, y):
    
    if isinstance(x, int) and isinstance(y, int):
        return x + y
    
    elif isinstance(x, str) and isinstance(y, str):
        return x + ' ' + y

At syntactical level, Python does not support multiple dispatch but it is possible to add multiple dispatch using a library extension multimethod. To install this library type the below command in the terminal.
pip install multimethod
Example 1:
# Python program to demonstrate# multimethods    from multimethod import multimethod    # Function that will be called# for integer addition@multimethoddef sum(x: int, y: int):    return x + y  # Function that will be called# for string addition@multimethoddef sum(x: str, y: str):    return x+" "+y  # Driver's codeprint(sum(2, 3))print(sum("Hello", "World"))
Output:
5
Hello World
Example 2:
# Python program to demonstrate# multimethods    from multimethod import multimethod    class GFG(object):          @multimethod    def double(self, x: int):        print(2 * x)      @multimethod    def double(self, x: complex):        print("sorry, I don't like complex numbers")          # Driver Codeobj = GFG()obj.double(3)obj.double(6j)
Output:
6
sorry, I don't like complex numbers
Python Decorators
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Pandas Series.hasnans - GeeksforGeeks

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.hasnans attribute returns a boolean value. It return True if the given Series object has missing values in it else it return False.
Syntax:Series.hasnans
Parameter : None
Returns : boolean
Example #1: Use Series.hasnans attribute to check if the given Series object has any missing values in it.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4']   # Print the seriesprint(sr)
Output :
Now we will use Series.hasnans attribute to check for the missing values in sr object.
# check for missing values.sr.hasnans
Output :
As we can see in the output, the Series.hasnans attribute has returned False indicating that there is no missing values in the given series object. Example #2 : Use Series.hasnans attribute to check if the given Series object has any missing values in it.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([1000, 'Calgarry', 5000, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.hasnans attribute to check for the missing values in sr object.
# check for missing values.sr.hasnans
Output :As we can see in the output, the Series.hasnans attribute has returned True indicating that there is at least one missing value in the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Angular10 NgFor Directive - GeeksforGeeks

03 Jun, 2021
In this article, we are going to see what is NgFor in Angular 10 and how to use it.
NgFor is used as a structural directive that renders each element for the given collection each element can be displayed on the page.
Syntax:
<li *ngFor='condition'></li>
NgModule: Module used by NgForOf is:
CommonModule
 
Selectors:
[ngFor]
Approach: 
Create the angular app to be used
There is no need for any import for the NgFor to be used
In app.component.ts define the array to be used with ngFor directive.
In app.component.html use NgFor directive with list element to display array elements.
serve the angular app using ng serve to see the output
Example 1:
app.component.ts
import { Component } from '@angular/core';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',})export class AppComponent  {  a=['gfg1', 'gfg2', 'gfg3', 'gfg4']}
app.component.html
<ul>  <li *ngFor='let i of a'> {{i}} </li></ul>
Output:
Example 2:
app.component.ts
import { Component } from '@angular/core';  @Component({  selector: 'app-root',  templateUrl: './app.component.html',})export class AppComponent  {  a=['gfg1', 'gfg2', 'gfg3', 'gfg4']}
app.component.html
<ol>    <li *ngFor='let i of a'> {{i}} </li></ol>
Output:
Reference: https://angular.io/api/common/NgForOf
Angular10
AngularJS-Directives
Misc
Web Technologies
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Matching of patterns in a String in R Programming - agrep() Function - GeeksforGeeks

14 Apr, 2021
agrep() function in R Language is used to search for approximate matches to pattern within each element of the given string. 
Syntax: agrep(pattern, x, ignore.case=FALSE, value=FALSE)Parameters:pattern: Specified pattern which is going to be matched with given elements of the string. x: Specified string vector. ignore.case: If its value is TRUE, it ignore case. value: If its value is TRUE, it return the matching elements vector, else return the indices vector.  
Example 1:  
Python3
# R program to illustrate# agrep function # Creating string vectorx <- c("GFG", "gfg", "Geeks", "GEEKS") # Calling agrep() functionagrep("gfg", x)agrep("Geeks", x)agrep("gfg", x, ignore.case = TRUE)agrep("Geeks", x, ignore.case = TRUE)
Output :  
[1] 2
[1] 3
[1] 1 2
[1] 3 4
Example 2:  
Python3
# R program to illustrate# agrep function # Creating string vectorx <- c("GFG", "gfg", "Geeks", "GEEKS") # Calling agrep() functionagrep("gfg", x, ignore.case = TRUE, value = TRUE)agrep("G", x, ignore.case = TRUE, value = TRUE)agrep("Geeks", x, ignore.case = FALSE, value = FALSE)agrep("GEEKS", x, ignore.case = FALSE, value = FALSE)          
Output:  
[1] "GFG" "gfg"
[1] "GFG"   "gfg"   "Geeks" "GEEKS"
[1] 3
[1] 4
 
arorakashish0911
R String-Functions
R-strings
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
Python - Split in Nested tuples - GeeksforGeeks

03 Jul, 2020
Sometimes, while working with Python tuples, we can have a problem in which we need to perform split of elements in nested tuple, by a certain delimiter. This kind of problem can have application in different data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(3, (‘Gfg’, ‘best’, 6)), (10, (‘CS’, ‘good’, 9))]Output : [[3, ‘Gfg’, ‘best’, 6], [10, ‘CS’, ‘good’, 9]]
Input : test_list = [(3, (1, 2, 3, 6))]Output : [[3, 1, 2, 3, 6]]
Method #1 : Using list comprehension + unpack operator(*)The combination of above functions can be used to solve this problem. In this, we perform the task of unpacking the elements by delimiter using * operator and list comprehension to iterate and form pairs.
# Python3 code to demonstrate working of # Split in Nested tuples# Using list comprehension + unpack operator  # initializing listtest_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]  # printing original listprint("The original list is : " + str(test_list))  # Split in Nested tuples# Using list comprehension + unpack operatorres = [[a, *b] for a, b in test_list]  # printing result print("The splitted elements : " + str(res)) 
The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]

 
Method #2 : Using map() + list()The combination of above functions can be used to solve this problem. In this, we perform task of extending logic to each elements using map() and list() is used to pack the strings to different containers.
# Python3 code to demonstrate working of # Split in Nested tuples# map() + list()  # initializing listtest_list = [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]  # printing original listprint("The original list is : " + str(test_list))  # Split in Nested tuples# map() + list()res = []for sub in test_list:    res.append(list(map(str, (*[sub[0]], *[*sub[1]]))))  # printing result print("The splitted elements : " + str(res)) 
The original list is : [(3, ('Gfg', 'best')), (10, ('CS', 'good')), (7, ('Gfg', 'better'))]
The splitted elements : [[3, 'Gfg', 'best'], [10, 'CS', 'good'], [7, 'Gfg', 'better']]

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

22 Nov, 2019
To wrap setTimeout in a promise returned by a future. We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes upto two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise. There can be two different values if the function called onFulfilled that’s mean promise is fulfilled. If the function onRejected called that means promise is rejected.
Syntax:
Promise.then(onFulfilled, onRejected)
Below example will illustrate the approach:
Example:
<!DOCTYPE html><html>  <head>    <title>        How to wrap setTimeout in a promise?    </title></head>  <body style="text-align:center;">      <h1 style="color:green;">        GeeksforGeeks    </h1>      <h3>        How to wrap setTimeout in a promise?    </h3>    <br>      <button onclick="change()">        Click to print    </button></body>  <script>    function change() {        return new Promise(function(resolve, reject) {              // Setting 2000 ms time            setTimeout(resolve, 2000);        }).then(function() {            console.log("Wrapped setTimeout after 2000ms");        });    }</script>  </html>    
Output:
Before Clicking the button:
After clicking the button:
Reference:Promise.prototype.then() Method
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Math.Exp() Method in C#

The Math.Exp() method in C# is used to return e raised to the specified power.
public static double Exp (double val);
Here, Val is the power.
If Val equals NaN or PositiveInfinity, that value is returned. However, if d equals NegativeInfinity, 0 is returned.
Let us now see an example to implement Math.Exp() method −
using System;
public class Demo {
   public static void Main(){
      Console.WriteLine(Math.Exp(0.0));
      Console.WriteLine(Math.Exp(Double.PositiveInfinity));
      Console.WriteLine(Math.Exp(Double.NegativeInfinity));
   }
}
This will produce the following output −
1
∞
0
Let us see another example to implement Math.Exp() method −
using System;
public class Demo {
   public static void Main(){
      Console.WriteLine(Math.Exp(10.0));
      Console.WriteLine(Math.Exp(Double.NaN));
   }
}
This will produce the following output −
22026.4657948067
NaN
Tryit Editor v3.7

Tryit: HTML headings
Multiplicative Cipher

While using Caesar cipher technique, encrypting and decrypting symbols involves converting the values into numbers with a simple basic procedure of addition or subtraction.
If multiplication is used to convert to cipher text, it is called a wrap-around situation. Consider the letters and the associated numbers to be used as shown below −
The numbers will be used for multiplication procedure and the associated key is 7. The basic formula to be used in such a scenario to generate a multiplicative cipher is as follows −
(Alphabet Number * key)mod(total number of alphabets)

The number fetched through output is mapped in the table mentioned above and the corresponding letter is taken as the encrypted letter.
The basic modulation function of a multiplicative cipher in Python is as follows −
def unshift(key, ch):
   offset = ord(ch) - ASC_A
   return chr(((key[0] * (offset + key[1])) % WIDTH) + ASC_A)

Note − The advantage with a multiplicative cipher is that it can work with very large keys like 8,953,851. It would take quite a long time for a computer to brute-force through a majority of nine million keys.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to upload multiple files and store them in a folder with PHP?

Below are the steps to upload multiple files and store them in a folder −
Input name must be defined as an array i.e. name="inputName[]"
Input element should have multiple="multiple" or just multiple
In the PHP file, use the syntax "$_FILES['inputName']['param'][index]"
Empty file names and paths have to be checked for since the array might contain empty strings. To resolve this, use array_filter() before count.
Below is a demonstration of the code −
<input name="upload[]" type="file" multiple="multiple" />
$files = array_filter($_FILES['upload']['name']); //Use something similar before processing files.
// Count the number of uploaded files in array
$total_count = count($_FILES['upload']['name']);
// Loop through every file
for( $i=0 ; $i < $total_count ; $i++ ) {
   //The temp file path is obtained
   $tmpFilePath = $_FILES['upload']['tmp_name'][$i];
   //A file path needs to be present
   if ($tmpFilePath != ""){
      //Setup our new file path
      $newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
      //File is uploaded to temp dir
      if(move_uploaded_file($tmpFilePath, $newFilePath)) {
         //Other code goes here
      }
   }
}
The files are listed and the count of the number of files that need to be uploaded is stored in ‘total_count’ variable. A temporary file path is created and every file is iteratively put in this temporary path that holds a folder.
Explain the insertion sort by using C language.

Sorting is the process of arranging the elements either in ascending (or) descending order.
C language provides five sorting techniques, which are as follows −
Bubble sort (or) Exchange Sort
Selection sort
Insertion sort(or) Linear sort
Quick sort (or) Partition exchange sort
Merge Sort (or) External sort
The logic used to sort the elements by using the insertion sort technique is as follows −
for(i = 1; i <= n - 1; i++){
   for(j = i; j > 0 && a[j - 1] > a[j]; j--){
      t = a[j];
      a[j] = a[j - 1];
      a[j - 1] = t;
   }
}
Let us consider some elements which are in unsorted order −
Following is the C program to sort the elements by using the insertion sort technique −
#include<stdio.h>
int main() {
   int a[50], i,j,n,t;
   printf("enter the No: of elements in the list:\n");
   scanf("%d", &n);
   printf("enter the elements:\n");
   for(i=0; i<n; i++){
      scanf ("%d", &a[i]);
   }
   for(i = 1; i <= n - 1; i++){
      for(j=i; j > 0 && a[j - 1] > a[j]; j--){
         t = a[j];
         a[j] = a[j - 1];
         a[j - 1] = t;
      }
   }
   printf ("after insertion sorting the elements are:\n");
   for (i=0; i<n; i++)
   printf("%d\t", a[i]);
   return 0;
}
When the above program is executed, it produces the following output −
Enter the No: of elements in the list:
10
Enter the elements:
34
125
2
6
78
49
1
3
89
23
After insertion sorting the elements are:
1 2 3 6 23 34 49 78 89 125
Print all combinations of balanced parentheses in C++

In this problem, we are given an integer n. Our task is to print all possible pairs of n balanced parentheses.
Balanced parentheses are parentheses pairs that have a closing symbol for every corresponding opening symbol. Also, pairs should be properly nested.
Let’s take an example to understand the problem,
Input: n = 2
Output: {}{} {{}}
To solve this problem, we need to keep track of pairs of brackets. The initial count of brackets is 0. Then we will recursively a function till the total bracket count is less than n. Count brackets, recursively call for brackets based on the count. If opening bracket count is more than closing, put closing brackets and then go for a remaining count of pairs, if the opening bracket is less than n recursively call for remaining bracket pairs.
The below code with show implementation of our solution,
 Live Demo
# include<iostream>
using namespace std;
# define MAX_COUNT 100
void printParenthesesPairs(int pos, int n, int open, int close){
   static char str[MAX_COUNT];
   if(close == n) {
      cout<<str<<endl;
      return;
   }
   else {
      if(open > close) {
         str[pos] = '}';
         printParenthesesPairs(pos+1, n, open, close+1);
      }
      if(open < n) {
         str[pos] = '{';
         printParenthesesPairs(pos+1, n, open+1, close);
      }
   }
}
int main() {
   int n = 3;
   cout<<"All parentheses pairs of length "<<n<<" are:\n";
   if(n > 0)
      printParenthesesPairs(0, n, 0, 0);
   getchar();
   return 0;
}
All parentheses pairs of length 3 are −
{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}
Python | Decimal exp() method - GeeksforGeeks

05 Sep, 2019
Decimal#exp() : exp() is a Decimal class method which returns the value of the (natural) exponential function e**x at the given number
Syntax: Decimal.exp()
Parameter: Decimal values
Return: the value of the (natural) exponential function e**x at the given number
Code #1 : Example for exp() method
# Python Program explaining # exp() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal('0.142857')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.exp() methodprint ("\n\nDecimal a with exp() method : ", a.exp())  print ("Decimal b with exp() method : ", b.exp())
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with exp() method :  0.3678794411714423215955237702
Decimal b with exp() method :  1.153564830100120253802476512


Code #2 : Example for exp() method
# Python Program explaining # exp() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('7.555')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.exp() methodprint ("\n\nDecimal a with exp() method : ", a.exp())  print ("Decimal b with exp() method : ", b.exp())
Output :
Decimal value a :  -3.14
Decimal value b :  7.555


Decimal a with exp() method :  0.04328279790196590079772976615
Decimal b with exp() method :  1910.270243928773816178935745

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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
AngularJS | ng-checked Directive - GeeksforGeeks

26 Mar, 2019
The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radiobutton to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radiobutton will be checked otherwise it will be unchecked.
Syntax:
<input type="checkbox|radio" ng-checked="expression"> Contents... </input>
If expression returns true then the element’s checked attribute will be checked.
Example: This example uses ng-checked Directive to select checkbox and return the all selected checkbox value.
<!DOCTYPE html><html>      <head>    <title>ng-checked Directive</title>      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">    </script></head>  <body ng-app="app">    <div ng-controller="geek">        <h1 style="color:green">GeeksforGeeks</h1>        <h2>ng-checked Directive</h2>           <input type="checkbox" ng-checked="check1 &&                check2 && check3 && check4 && check5"                ng-model="isChecked" /><b>Select All</b><br>                      <input type="checkbox" ng-model="check1"             ng-checked="isChecked" />First<br>                  <input type="checkbox" ng-model="check2"             ng-checked="isChecked" />Second<br>                      <input type="checkbox" ng-model="check3"            ng-checked="isChecked" />Three<br>                  <input type="checkbox" ng-model="check4"             ng-checked="isChecked" /> Four<br>                      <input type="checkbox" ng-model="check5"            ng-checked="isChecked" />Five<br><br>                  <b>isAllSelected = {{isChecked}}</b>    </div>          <script>        var app = angular.module("app", []);        app.controller('geek', ['$scope', function ($scope) {        }]);    </script></body>  </html>
Output:Before clicking the checkbox:After clicking the checkbox (select all):
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Angular PrimeNG Calendar Component
Auth Guards in Angular 9/10/11
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Can we declare the method of an Interface final in java?

An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
By default, all the methods of an interface are public and abstract. For example, In the following Java program, we are having a declaring a method with name demo.
public interface MyInterface{
   void demo();
}
If you compile this using the javac command as shown below −
c:\Examples>javac MyInterface.java
it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −
c:\Examples>javap MyInterface
Compiled from "MyInterface.java"
public interface MyInterface {
   public abstract void demo();
}
You can observe that the compiler has placed the public and, abstract modifiers before the method on behalf of you.
In addition to this as of Java9 you can have default, static, private, private and static with the methods of an interface. Except these you cannot use any other modifiers with the methods of an interface.
Moreover, if you declare a method final you cannot override/implement it and, an abstract method must be overridden or implemented. Therefore, you cannot declare the method of an interface final.
If you still do so, it generates a compile time error saying “modifier final not allowed here”.
In the following Java program, we are trying to declare a method of an interface final.
public interface MyInterface{
   public abstract final void demo();
}
On compiling, the above program generates the following compile time error −
MyInterface.java:2: error: modifier final not allowed here
   public abstract final void demo();
                              ^
1 error
How to create our own/custom functional interface in Java?


The functional interface is a simple interface with only one abstract method. A lambda expression can be used through a functional interface in Java 8. We can declare our own/custom
functional interface by defining the Single Abstract Method (SAM) in an interface.
interface CustomInterface {
   // abtstact method
}
@FunctionalInterface
interface CustomFunctionalInterface {
   void display();
}
public class FunctionInterfaceLambdaTest {
   public static void main(String args[]) {
      // Using Anonymous inner class
      CustomFunctionalInterface test1 = new CustomFunctionalInterface() {
         public void display() {
            System.out.println("Display using Anonymous inner class");
         }
      };
      test1.display();
      // Using Lambda Expression
      CustomFunctionalInterface test2 = () -> {    // lambda expression
         System.out.println("Display using Lambda Expression");
      };
      test2.display();
   }
}
Display using Anonymous inner class
Display using Lambda Expression
C++ Program to Check if a Binary Tree is a BST

Binary Search Tree is a binary tree data structure in which we have 3 properties −
The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key.
The left subtree of a binary search tree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key.
The right subtree of a binary search tree node contains only nodes with keys greater than the node’s key.
The left and right of a subtree each must also be a binary search tree.
The left and right of a subtree each must also be a binary search tree.
Begin
   function BSTUtill()
      If node is equals to NULL then
         Return 1.
      If data of node is less than minimum or greater than
      maximum data then
         Return 0.
      Traverse left and right sub-trees recursively. 
End.
 Live Demo
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;
struct n {
   int d;
   n* l;
   n* r;
};
int BSTUtil(n* node, int min, int max);
int isBST(n* node) {
   return(BSTUtil(node, INT_MIN, INT_MAX));
}
int BSTUtil(struct n* node, int min, int max) {
   if (node==NULL)
      return 1;
   if (node->d < min || node->d > max)
      return 0;
      return BSTUtil(node->l, min, node->d - 1) && BSTUtil(node->r, node->d + 1, max);
}
n* newN(int d) {
   n* nod = new n;
   nod->d = d;
   nod->l = NULL;
   nod->r = NULL;
   return nod;
}
int main() {
   n *root = newN(7);
   root->l = newN(6);
   root->r = newN(10);
   root->l->l = newN(2);
   root->l->r = newN(4);
   if (isBST(root))
      cout<<"The Given Binary Tree is a BST"<<endl;
   else
      cout<<"The Given Binary Tree is not a BST"<<endl;
      n *root1 = newN(10);
      root1->l = newN(6);
      root1->r = newN(11);
      root1->l->l = newN(2);
      root1->l->r = newN(7);
      if (isBST(root1))
         cout<<"The Given Binary Tree is a BST"<<endl;
      else
         cout<<"The Given Binary Tree is not a BST"<<endl;
      return 0;
}
The Given Binary Tree is not a BST
The Given Binary Tree is a BST
Tryit Editor v3.6 - Show React

import React from 'react';
import ReactDOM from 'react-dom/client';

const myElement = <h1>React is {5 + 5} times better with JSX</h1>;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
How to find the href and target attributes in a link in JavaScript?

Javascript has provided document.href and document.target to get the href and target attributes in a link. A link is usually placed in a <p> tag and inside it, an anchor tag is provided, which in turn contains href and target attributes. Let's discuss them individually.
To get the href attribute, document.href must be used. In the following example, the href attribute consists of a link called "http://www.tutorialspoint.com/", which will be displayed once the program is executed.
Live Demo
<html>
<body>
<p><a id="myId" href="http://www.tutorialspoint.com/">tutorialspoint</a></p>
<script>
   var ref = document.getElementById("myId").href;
   document.write(ref);
</script>
</body>
</html>
tutorialspoint

http://www.tutorialspoint.com/
To get the target attribute, document.target must be used. In the following example, the target attribute "_union" was displayed when the program was executed.
Live Demo
<html>
<body>
<p><a id="myId" target="_union" href="http://www.tutorialspoint.com/">tutorialspoint</a></p>
<script>
   var ref = document.getElementById("myId").target;
   document.write(ref);
</script>
</body>
</html>
tutorialspoint

_union
Call Stored Procedures within a Stored Procedure with IF Logic?

To call stored procedures within a stored procedure, the syntax is as follows −
If yourInputValue > 100 then
     call yourProcedureName1();
 else
    call yourProcedureName2();
    end If ;
    END
Let us implement the above syntax. In order to implement the above concept, let us create a stored procedure −
mysql> delimiter //
mysql> create procedure Hello_Stored_Procedure()
   -> BEGIN
   -> select 'Hello World!!!';
   -> END
   -> //
Query OK, 0 rows affected (0.18 sec)
The query to create the second stored procedure is as follows −
mysql> create procedure Hi_Stored_Procedure()
   -> BEGIN
   -> select 'Hi!!!';
   -> END
   -> //
Query OK, 0 rows affected (0.17 sec)
Here is the query to call stored procedures within a stored procedure with IF logic −
mysql> DELIMITER //
mysql> create procedure test(IN input int)
   -> BEGIN
   -> If input > 100 then
   -> call Hello_Stored_Procedure();
   -> else
   -> call Hi_Stored_Procedure();
   -> end If ;
   -> END
   -> //
Query OK, 0 rows affected (0.18 sec)
Now you can call the stored procedure with the help of call −
mysql> delimiter ;
mysql> call test(110);
This will produce the following output −
+----------------+
| Hello World!!! |
+----------------+
| Hello World!!! |
+----------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
java.time.Duration.ofSeconds() Method Example

The java.time.Duration.ofSeconds(long seconds) method obtains a Duration representing a number of standard seconds.
Following is the declaration for java.time.Duration.ofSeconds(long seconds) method.
public static Duration ofSeconds(long seconds)

seconds − the number of seconds, positive or negative.
a Duration, not null.
ArithmeticException − if the input seconds exceeds the capacity of Duration.
The following example shows the usage of java.time.Duration.ofSeconds(long seconds) method.
package com.tutorialspoint;

import java.time.Duration;

public class DurationDemo {
   public static void main(String[] args) {

      Duration duration = Duration.ofSeconds(2);
      System.out.println(duration.getSeconds());      
   }
}
Let us compile and run the above program, this will produce the following result −
2

 Print
 Add Notes
 Bookmark this page
Removing redundant elements from array altogether - JavaScript

We are required to write a function that takes in an array and returns a new array that have all duplicate values removed from it. The values that appeared more than once in the original array should not even appear for once in the new array.
For example, if the input is −
const arr = [763,55,43,22,32,43,763,43];
The output should be −
const output = [55, 22, 32];
We will be using the following two methods −
Array.prototype.indexOf() −It returns the index of first occurrence of searched string if it exists, otherwise -1.
It returns the index of first occurrence of searched string if it exists, otherwise -1.
Array.prototype.lastIndexOf()It returns the index of last occurrence of searched string if it exists, otherwise -1.
It returns the index of last occurrence of searched string if it exists, otherwise -1.
Following is the code −
const arr = [763,55,43,22,32,43,763,43];
const deleteDuplicate = (arr) => {
   const output = arr.filter((item, index, array) => {
      return array.indexOf(item) === array.lastIndexOf(item);
   });
   return output;
};
console.log(deleteDuplicate(arr));
This will produce the following output in console −
[ 55, 22, 32 ]
GATE | GATE-CS-2004 | Question 53 - GeeksforGeeks

28 Jun, 2021
The employee information in a company is stored in the relation
Employee (name, sex, salary, deptName)
Consider the following SQL query
select deptName
       from Employee
       where sex = 'M'
       group by deptName
       having avg (salary) > (select avg (salary) from Employee)

It returns the names of the department in which(A) the average salary is more than the average salary in the company(B) the average salary of male employees is more than the average salary of all male employees in the company(C) the average salary of male employees is more than the average salary of employees in the same department
(D) the average salary of male employees is more than the average salary in the companyAnswer: (D)Explanation: In this SQL query, we have
select deptName ---------------  Select the department name
from Employee  ----------------  From the database of employees
where sex = 'M' ---------------  Where sex is male (M)
group by deptName -------------  Group by the name of the department
having avg (salary) >   
(select avg (salary) from Employee)  -----  Having the average salary 
                                            greater than the average salary 
                                            of all employees in the organization.

So, this query would return the name of all departments in which the average salary of male employees is greater than the average salary of all employees in the company.
Hence, D is the correct choice.
 
Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
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-2000 | Question 41
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-2003 | Question 90