code-rag-bench/online-tutorials huggingface dataset:
Passing unknown number of arguments to a function in Javascript

When you call a function in JavaScript you can pass in any number of arguments. There is no function parameter limit. This also means that functions can't be overloaded in traditional ways in js.
The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.
For example, if a function is passed 3 arguments, you can access them as follows −
arguments[0] // first argument
arguments[1] // second argument
arguments[2] // third argument
Note − arguments is an Array-like object accessible inside functions that contains the values of the arguments passed to that function. “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have Array's built-in methods like forEach() and map().
For example, to accept a arbitrary number of args, you can create a function as follows −
function printAllArguments(a, b) {
   console.log("First arg: " + a)
   console.log("Second arg: " + b)
   console.log("All args: " + arguments)
}
printAllArguments(1)
printAllArguments(1, "hello")
printAllArguments(1, "hello", 1, "hello")
First arg: 1 
Second arg: undefined 
All args: {"0":1}
First arg: 1
Second arg: hello 
All args: {"0":1,"1":"hello"} 
First arg: 1
Second arg: hello 
All args: {"0":1,"1":"hello","2":1,"3":"hello"}
PHP - Function move_uploaded_file()

The move_uploaded_file() function can move an uploaded file to new location. If the filename is not a valid upload file, then no action can occur and return false. If the filename is a valid upload file but can't be moved for some reason, then no action can occur and return false. Additionally, a warning can be issued. 
bool move_uploaded_file ( string $filename , string $destination )

 This function can check to ensure that the file designated by filename is a valid upload file, which means that it has uploaded via PHP's HTTP POST upload mechanism. If the file is valid, it can be moved to the filename given by the destination. 
 This sort of check is especially used if there is any chance that anything done with uploaded files can reveal their contents to the user, or even to other users on the same system. 
<?php
   $uploads_dir = "/PhpProject/uploads";
   foreach($_FILES["pictures"]["error"] as $key => $error) {
      if($error == UPLOAD_ERR_OK) {
         $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
         $name = basename($_FILES["pictures"]["name"][$key]);
         move_uploaded_file($tmp_name, "$uploads_dir/$name");
      }
   }
?>

    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2017 (Set 1) | Question 63 - GeeksforGeeks

28 Jun, 2021
Recall that Belady’s anomaly is that the pages-fault rate may increase as the number of allocated frames increases. Now consider the following statements:
S1: Random page replacement algorithm (where
    a page chosen at random is replaced) 
    suffers from Belady’s anomaly.

S2: LRU page replacement algorithm suffers
    from Belady’s anomaly .

Which of the following is CORRECT?(A) S1 is true, S2 is true(B) S1 is true, S2 is false(C) S1 is false , S2 is true(D) S1 is false, S2 is falseAnswer: (B)Explanation: Belady’s anomaly proves that it is possible to have more page faults when increasing the number of page frames while using the First in First Out (FIFO) page replacement algorithm. For example, if we consider reference string 3 2 1 0 3 2 4 3 2 1 0 4 and 3 slots, we get 9 total page faults, but if we increase slots to 4, we get 10 page faults.
S1: Random page replacement algorithm (where a page chosen at random is replaced) suffers from Belady’s anomaly.-> Random page replacement algorithm can be any including FIFO so its true
S2: LRU page replacement algorithm suffers from Belady’s anomaly .-> LRU does’nt suffer from Belady’s anomaly .
Therefore, option B is correctQuiz of this Question
GATE-CS-2017 (Set 1)
GATE-GATE-CS-2017 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
traceroute command in Linux with Examples

27 May, 2019
traceroute command in Linux prints the route that a packet takes to reach the host. This command is useful when you want to know about the route and about all the hops that a packet takes. Below image depicts how traceroute command is used to reach the Google(172.217.26.206) host from the local machine and it also prints detail about all the hops that it visits in between.
The first column corresponds to the hop count. The second column represents the address of that hop and after that, you see three space-separated time in milliseconds. traceroute command sends three packets to the hop and each of the time refers to the time taken by the packet to reach the hop.
Syntax:
traceroute [options]  host_Address [pathlength]

Options:
-4 Option: Use ip version 4 i.e. use IPv4Syntax:$ traceroute -4 10 google.com
Syntax:
$ traceroute -4 10 google.com
-6 Option: Use ip version 6 i.e. use IPv6Syntax:$ traceroute -6 10 google.com
Syntax:
$ traceroute -6 10 google.com
-F Option: Do not fragment packet.Syntax:$ traceroute -F google.com
Syntax:
$ traceroute -F google.com
-f first_ttl Option: Start from the first_ttl hop (instead from 1).Syntax:$ traceroute -f 10 google.com
Syntax:
$ traceroute -f 10 google.com
-g gate Option: Route the packet through gate.Syntax:$ traceroute -g 192.168.43.45 google.com
Syntax:
$ traceroute -g 192.168.43.45 google.com
-m max_ttl Option: Set the max number of hops for the packet to reach the destination.Default value is 30.Syntax:$traceroute  -m 5 google.com
Syntax:
$traceroute  -m 5 google.com
-n Option: Do not resolve IP addresses to their domain names.Syntax:$traceroute -n google.com
Syntax:
$traceroute -n google.com
-p port Option: Set the destination port to use. Default is 33434.Syntax:$traceroute  -p 20292 google.com
Syntax:
$traceroute  -p 20292 google.com
-q nqueries Option: Set the number of probes per each hop. Default is 3.Syntax:$traceroute -q 1 google.com
Syntax:
$traceroute -q 1 google.com
packetlen Option: The full packet length. Default len is 60 byte packets.Syntax:$traceroute  google.com 100
Syntax:
$traceroute  google.com 100
–help: Display help messages and exit.Syntax:$traceroute --help
Syntax:
$traceroute --help
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Illustrate a Method with 2 Parameters and without Return Type

07 Feb, 2022
Function without return type stands for a void function. The void function may take multiple or zero parameters and returns nothing. Here, we are going to define a method which takes 2 parameters and doesn’t return anything.
Syntax:
public static void function(int a, int b)
Example: 
public static void fun1(String 1, String 2){
    // method execution code
};
Approach:
Take 2 inputs into two variables.Pass these inputs as an argument to the function.Display the sum from this defined function.
Take 2 inputs into two variables.
Pass these inputs as an argument to the function.
Display the sum from this defined function.
Code:
Java
// Java Program to Illustrate a Method// with 2 Parameters and without Return Typeimport java.util.*;public class Main {    public static void main(String args[])    {        int a = 4;        int b = 5;         // Calling the function with 2 parameters        calc(a, b);    }    public static void calc(int x, int y)    {        int sum = x + y;        // Displaying the sum        System.out.print("Sum of two numbers is :" + sum);    }}
  
Sum of two numbers is :9
 
sumitgumber28
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between <i> and <em> tag of HTML

04 Dec, 2020
1. <i> tag :It is one of the element of HTML which is used in formatting HTML texts. It is used to define a text in technical term, alternative mood or voice, a thought, etc.
Syntax :
<i> Content... </i>
2. <em> tag :It is also one of the element of HTML used in formatting texts. It is used to define emphasized text or statements.
Syntax :
<em> Content... </em>
By default, the visual result is the same. The main difference between these two tag is that the <em> tag semantically emphasizes on the important word or section of words while <i> tag is just offset text conventionally styled in italic to show alternative mood or voice. Below is the code to show this difference between the two :
Example-1 :
HTML
<!DOCTYPE html><html>    <head>        <title>b Tag</title>        <style>            body {                text-align:center;            }            h1 {                color: green;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <p><i>Iron Man</i> is a hero.</p>        <p>Gfg is the <em>best</em> educational site.</p>              </body></html>                    
Output :
Here, there is no added emphasis or importance on the word “Iron Man”. It just indicates here iron isn’t a mineral or metal but it refers to a character. But in the next sentence the reader will use verbal stress on the word “best”.
Example-2 :
HTML
<!DOCTYPE html><html lang="en" dir="ltr">  <head>  <meta charset="utf-8">  <title>Difference between <i> and <em> tag of HTML</title></head>  <body>  <h1><i>This senetence is in Italic</i></h1>    <h1>      <em>This sentence has emphasized meaning.</em></h1></body>  </html>
Output :
Though they appears to be same but semantic meaning is different.Supported Browser : The browser supported by <i> and <em> tag are listed below.
Chrome
Android
Firefox (Gecko)
Firefox Mobile (Gecko)
Internet Explorer (IE)
Edge Mobile
Opera
Opera Mobile
Safari (WebKit)
Safari Mobile
CSS
Difference Between
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to extract all dictionary values | Python

24 Oct, 2019
While working with Python dictionaries, there can be cases in which we are just concerned about getting the values list and don’t care about keys. This is yet another essential utility and solution to it should be known and discussed. Let’s perform this task through certain methods.
Method #1 : Using loop + keys()The first method that comes to mind to achieve this task is the use of loop to access each key’s value and append it into a list and return it. This can be one of method to perform this task.
# Python3 code to demonstrate working of# Ways to extract all dictionary values# Using loop + keys()  # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Extracting all dictionary values# Using loop + keys()res = []for key in test_dict.keys() :    res.append(test_dict[key])  # printing resultprint("The list of values is : " +  str(res))
The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}
The list of values is : [1, 2, 3]

 
Method #2 : Using values()This task can also be performed using the inbuilt function of values(). This is the best and most Pythonic way to perform this particular task and returns the exact desired result.
# Python3 code to demonstrate working of# Ways to extract all dictionary values# Using values()  # initializing dictionarytest_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Extracting all dictionary values# Using values()res = list(test_dict.values())  # printing resultprint("The list of values is : " +  str(res))
The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}
The list of values is : [1, 2, 3]

Python dictionary-programs
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
How to Install PIP on Windows ?
Python String | replace()
Defaultdict in Python
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python program to check whether a number is Prime or not
Python PIL | ImageGrab.grabclipboard() method

29 Jul, 2019
PIL.ImageGrab.grabclipboard() method takes a snapshot of the clipboard image, if any.
Syntax: PIL.ImageGrab.grabclipboard()
Parameters: no arguments
Returns: On Windows, an image, a list of filenames, or None if the clipboard does not contain image data or filenames.
Note: This Module only work for Windows and Mac OS.
# Importing Image and ImageGrab module from PIL package from PIL import Image, ImageGrab        # using the grabclipboard methodim = ImageGrab.grabclipboard()     im.show()
Output:
After changing the image on the clipboard
# Importing Image and ImageGrab module from PIL package from PIL import Image, ImageGrab        # using the grabclipboard methodim = ImageGrab.grabclipboard()     im.show()
Output:
nidhi_biet
Image-Processing
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Priority queue of pairs in C++ (Ordered by first)

04 Oct, 2018
In C++, priority_queue implements heap. Below are some examples of creating priority queue of pair type.
Max Priority queue (Or Max heap) ordered by first element
// C++ program to create a priority queue of pairs.// By default a max heap is created ordered// by first element of pair.#include <bits/stdc++.h>  using namespace std;  // Driver program to test methods of graph classint main(){    // By default a max heap is created ordered    // by first element of pair.    priority_queue<pair<int, int> > pq;      pq.push(make_pair(10, 200));    pq.push(make_pair(20, 100));    pq.push(make_pair(15, 400));      pair<int, int> top = pq.top();    cout << top.first << " " << top.second;    return 0;}
Output :
20 100
Min Priority queue (Or Min heap) ordered by first element
// C++ program to create a priority queue of pairs.// We can create a min heap by passing adding two // parameters, vector and greater().#include <bits/stdc++.h>  using namespace std;  typedef pair<int, int> pi;  // Driver program to test methods of graph classint main(){    // By default a min heap is created ordered    // by first element of pair.    priority_queue<pi, vector<pi>, greater<pi> > pq;      pq.push(make_pair(10, 200));    pq.push(make_pair(20, 100));    pq.push(make_pair(15, 400));      pair<int, int> top = pq.top();    cout << top.first << " " << top.second;    return 0;}
Output :
10 200
addiegupta
cpp-pair
cpp-priority-queue
STL
Heap
Heap
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Sliding Window Maximum (Maximum of all subarrays of size k)
Building Heap from Array
Max Heap in Java
Priority Queue in Python
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Insertion and Deletion in Heaps
Sort a nearly sorted (or K sorted) array
Merge k sorted arrays | Set 1
Find k numbers with most occurrences in the given array
How to make a HTML link that forces refresh ?

23 Apr, 2021
In this article, we will learn to make an HTML link that forces refresh. HTML <meta> http-equiv attribute with refresh value specified in meta element is used to refresh website pages.
Refresh instruction specifies time interval for the page to reload itself, with its value mentioned in content attribute as a positive integer. Positive integer is the number of seconds after which the page will refresh itself. 
Syntax:
<meta http-equiv="refresh" content="5">
HTML
<!DOCTYPE html><html>  <head>    <meta http-equiv="refresh" content="5" />  </head>  <body>    <h2 style="color: green">     Welcome To GFG    </h2>      <p>     This page automatically refreshes      after every 5 seconds    </p>  </body></html>
Output:
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MySQL - USE Statement

The USE statement of MySQL helps you to select/use a database. You can also change to another database with this statement. Once you set the current database it will be same until the end of the session unless you change the it.
Following is the syntax of the MySQL USE statement −
USE db_name

Following example demonstrates the usage of the MySQL USE statement −
mysql> use test;
mysql> CREATE TABLE SAMPLE(NAME VARCHAR(10));
Query OK, 0 rows affected (1.65 sec)
mysql> INSERT INTO SAMPLE VALUES ('Raj');
Query OK, 1 row affected (0.19 sec)
mysql> use sample
Database changed
mysql> SELECT * FROM SAMPLE;
ERROR 1146 (42S02): Table 'sample.sample' doesn't exist
Here we are creating a new database and changing the current database to it.
mysql> CREATE DATABASE myDatabase;
Query OK, 1 row affected (0.23 sec)

mysql> use myDatabase
C program to read a range of bytes from file and print it to console

28 Jun, 2021
Given a file F, the task is to write C program to print any range of bytes from the given file and print it to a console.
Functions Used:
fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.fgetc(): Reading the characters from the file.fclose(): For closing a file.
fopen(): Creation of a new file. The file is opened with attributes as “a” or “a+” or “w” or “w++”.
fgetc(): Reading the characters from the file.
fclose(): For closing a file.
Approach:
Initialize a file pointer, say File *fptr1.
Initialize an array to store the bytes that will be read from the file.
Open the file using the function fopen() as fptr1 = fopen(argv[1], “r”).
Iterate a loop until the given file is read and stored, the characters are scanned in the variable, say C using the fgetc() function.
Store each character C extracted in the above step, to a new string S and print that string using the printf() function.
After completing the above steps, close the file using the fclose() function.
Below is the implementation of the above approach:
C
// C program to read particular bytes// from the existing file#include <stdio.h>#include <stdlib.h>  // Maximum range of bytes#define MAX 1000  // Filename given as the command// line argumentint main(int argc, char* argv[]){    // Pointer to the file to be    // read from    FILE* fptr1;    char c;      // Stores the bytes to read    char str[MAX];    int i = 0, j, from, to;      // If the file exists and has    // read permission    fptr1 = fopen(argv[1], "r");      if (fptr1 == NULL) {        return 1;    }      // Input from the user range of    // bytes inclusive of from and to    printf("Read bytes from: ");    scanf("%d", &from);    printf("Read bytes upto: ");    scanf("%d", &to);      // Loop to read required byte    // of file    for (i = 0, j = 0; i <= to                       && c != EOF;         i++) {          // Skip the bytes not required        if (i >= from) {            str[j] = c;            j++;        }          // Get the characters        c = fgetc(fptr1);    }      // Print the bytes as string    printf("%s", str);      // Close the file    fclose(fptr1);      return 0;}
Output:
C-File Handling
File Handling
C Language
C Programs
File Handling
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
Youtube video downloader using Django

25 May, 2022
In this article, we will see how to make a YouTube video downloader tool in Django. We will be using pytube module for that.
Prerequisite:
pytube: It is python’s lightweight and dependency-free module, which is used to download YouTube Videos.
Django: It is python’s framework to make web-applications.
Here, we will be using Django as a backend along with pytube module to create this tool. We can install pytube module by typing the below command in the terminal.
pip install pytube
So, let’s dive in to make our YouTube video downloader tool.
First, we will create an HTML design (form) where the user can come and enter the URL of a video which he/she wants to download. We will use Django’s POST method to get that URL (because it is secure). We also need to use csrf token if we are using the POST method. Syntax for csrf token is: 
{% csrf_token %}
HTML
<!DOCTYPE html><html><body>  <h1>Youtube video downloader</h1>    <form action="" method="post">  {% csrf_token %}    <label for="link">Enter URL:</label>  <input type="text" id="link" name="link"><br><br>  <input type="submit" value="Submit"></form>  </body></html>
 
 
Now, it’s time to create a function that receives the video link and downloads that video. You need to import function YouTube from module pytube in views.py file.  Now we can define the function to download video.
 
views.py
 
Python3
# importing all the required modulesfrom django.shortcuts import render, redirectfrom pytube import *    # defining functiondef youtube(request):      # checking whether request.method is post or not    if request.method == 'POST':                # getting link from frontend        link = request.POST['link']        video = YouTube(link)          # setting video resolution        stream = video.streams.get_lowest_resolution()                  # downloads video        stream.download()          # returning HTML page        return render(request, 'youtube.html')    return render(request, 'youtube.html')
 
 
Now, we have to define the URL (path) for this function inside urls.py.
 
Python3
from django.contrib import adminfrom django.urls import pathfrom . import views  urlpatterns = [    path('admin/', admin.site.urls),    path('youtube', views.youtube, name='youtube'),]
 
 
That is it for the coding part, now you can run the project by python manage.py runserver and head over to http://localhost:8000/youtube to see the output.
 
Output:
 
 
When you click on submit a video will be downloaded in your Django project’s directory.
 
 
akshaysingh98088
Django-Projects
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find Perimeter of a triangle

22 Jun, 2022
Given side (a, b, c) of a triangle, we have to find the perimeter of a triangle. 
Perimeter : Perimeter of a triangle is the sum of the length of side of a triangle.  
where a, b, c are length of side of a triangle.Perimeter of a triangle can simply be evaluated using following formula : 
Examples :  
Input : a = 2.0, b = 3.0, c = 5.0
Output : 10.0


Input : a = 5.0, b = 6.0, c = 7.0 
Output : 18.0
C++
C
Java
Python
C#
PHP
Javascript
// A simple C++ program to find the perimeter// of triangle#include <iostream>using namespace std; // Function to find perimeterfloat findPerimeter(float a, float b, float c){         // Formula for finding a perimeter    // of triangle    return (a + b + c);} // Driver Codeint main(){    float a = 2.0, b = 3.0, c = 5.0;    cout << findPerimeter(a, b, c);     return 0;} // This code is contributed by Ankita saini
// A simple C program to find the perimeter// of triangle#include <stdio.h> // Function to find perimeterfloat findPerimeter(float a, float b, float c){    // Formula for finding a perimeter of triangle    return (a + b + c);} // Driver Codeint main(){    float a = 2.0, b = 3.0, c = 5.0;    printf("%f", findPerimeter(a, b, c));     return 0;}
// Java program to find perimeter// of triangleclass Test {    static float findPerimeter(float a, float b, float c)    {        // Formula for Perimeter of triangle        return (a + b + c);    }     // Driver method    public static void main(String[] args)    {        float a = 2.0, b = 3.0, c = 5.0;        System.out.println(findPerimeter(a, b, c));    }}
# Python Program to find a perimeter# of triangle # Function to find perimeterdef findPerimeter(a, b, c):     # Calculate the perimeter    return (a + b + c) # Driver Code   a = 2.0b = 3.0c = 5.0print(findPerimeter(a, b, c))
// C# program to find perimeter// of triangleusing System; class Test {         static float findPerimeter(float a,                           float b, float c)    {                 // Formula for Perimeter of triangle        return (a + b + c);    }     // Driver method    public static void Main()    {        float a = 2.0f, b = 3.0f, c = 5.0f;                 Console.WriteLine(findPerimeter(a, b, c));    }} //This code is contributed by vt_m.
<?php// A simple PHP program// to find the perimeter// of triangle // Function to find perimeterfunction findPerimeter($a, $b, $c){         // Formula for finding a    // perimeter of triangle    return ($a + $b + $c);}     // Driver Code    $a = 2.0;    $b = 3.0;    $c = 5.0;    echo findPerimeter($a, $b, $c);     // This code is contributed by anuj_67.?>
<script> // JavaScript program to find perimeter// of trianglefunction findPerimeter(a, b, c){         // Formula for Perimeter of triangle    return (a + b + c);} // Driver Codelet a = 2.0, b = 3.0, c = 5.0; document.write(findPerimeter(a, b, c)); // This code is contributed by code_hunt </script>
Output : 
10.0
Time Complexity: O(1)
Auxiliary Space: O(1)
vt_m
code_hunt
ankita_saini
sooda367
hasani
triangle
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to merge properties of two JavaScript objects dynamically?

22 Apr, 2019
Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows the privilege to obtain a list of parameters from an array.
Javascript objects are key-value paired dictionaries. We can merge different objects into one using the spread (...) operator.Syntax:
object1 = {...object2, ...object3, ... }

Example 1:
<script>let A = {    name: "geeksforgeeks",};  let B = {    domain: "https://geeksforgeeks.org"};  let Sites = { ...A, ...B };  console.log(Sites)</script>
Output:
Example 2: Suppose the objects have the same keys. In this case, the value of the key of the object which appears later in the distribution is used.
<script>let A = {    name: "geeksforgeeks",};  let B = {    name: "wordpress"};  let Sites = { ...A, ...B };  console.log(Sites)</script>
Output:
Another method: We can also use the Object.assign() method to merge different objects.
Example:
<script>let A = {  name: "geeksforgeeks",};  let B = {  domain: "https://geeksforgeeks.org"};  let Sites = Object.assign(A, B);  console.log(Sites);</script>
Output:
javascript-object
Picked
JavaScript
Web Technologies
Web technologies Questions
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
Initialization of global and static variables in C - GeeksforGeeks

08 May, 2017
Predict the output of following C programs.
// PROGRAM 1#include <stdio.h>#include <stdlib.h>  int main(void){   static int *p = (int*)malloc(sizeof(p));   *p = 10;   printf("%d", *p);}
// PROGRAM 2#include <stdio.h>#include <stdlib.h>int *p = (int*)malloc(sizeof(p));  int main(void){    *p = 10;    printf("%d", *p);}
Both of the above programs don’t compile in C. We get the following compiler error in C.
error: initializer element is not constant
In C, static and global variables are initialized by the compiler itself. Therefore, they must be initialized with a constant value.
Note that the above programs compile and run fine in C++, and produce the output as 10.
As an exercise, predict the output of following program in both C and C++.
#include <stdio.h>int fun(int x){    return (x+5);}  int y = fun(20);  int main(){    printf("%d ", y);}
This article is contributed by Shankar Shastri. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C Basics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Substring in C++
Function Pointer in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Tryit Editor v3.7

Tryit: Evenly spaced color stops
PHP - password_needs_rehash() Function

The password_needs_rehash() function can check if the given hash matches the given options. 
boolean password_needs_rehash ( string $hash , integer $algo [, array $options ] )

The password_needs_rehash() function can check to see if the supplied hash implements the algorithm and options provided. If not, it's assumed that the hash needs to rehash. 
The password_needs_rehash() function can return true if the hash can be rehashed to match the given algo and options or false otherwise. 
<?php
   $passw01 = "53nh46u74m3nt3";
   $hashp03 = '$argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRa0lQeM';
   $algo03 = PASSWORD_ARGON2I;

   $test03 = password_verify($passw01, $hashp03);
   $conf03 = password_needs_rehash($hashp03, $algo03);

   if($conf03 == true) {
      echo "HASH NEEDS TO BE REHASHED!<br>SUGGESTED FOR THE NEW HASH:<br>";
      $nwhas03 = password_hash($passw01, $algo03);
      echo $nwhas03;
   } else {
      echo "HASH DOES HAS NO NEED TO BE REHASHED!<br>";
      echo $hashp03;

      $getinfo03 = password_get_info($hashp03);

      echo "<br><br>algo = " . $getinfo03["algo"] . "<br>algoName = " . $getinfo03["algoName"] . "<br>memory_cost = " 
           . $getinfo03["options"]["memory_cost"] . "<br>time_cost = " . $getinfo03["options"]["time_cost"] 
           . "<br>threds = " . $getinfo03["options"]["threads"] . "<br><br>";  
   }
?>
HASH NEEDS TO BE REHASHED!<br>SUGGESTED FOR THE NEW HASH:<br>$argon2i$v=19$m=65536,t=4,p=1$dDVDRWFFTS9ObjFQMmhuRw$1uWmsNTQBbrwXtQPB7PQqWWIlcd0XBqg2mEDHGaElew


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Calculate the QR decomposition of a given matrix using NumPy - GeeksforGeeks

05 Sep, 2020
In this article, we will discuss QR decomposition of a matrix. QR factorization of a matrix is the decomposition of a matrix say ‘A’ into ‘A=QR’ where Q is orthogonal and R is an upper-triangular matrix. We can calculate the QR decomposition of a given matrix with the help of numpy.linalg.qr(). 
Syntax : numpy.linalg.qr(a, mode=’reduced’)
Parameters :
a : matrix(M,N) which needs to be factored.
mode : it is optional. It can be :
Example 1:
Python3
import numpy as np    # Original matrixmatrix1 = np.array([[1, 2, 3], [3, 4, 5]])print(matrix1)  # Decomposition of the said matrixq, r = np.linalg.qr(matrix1)print('\nQ:\n', q)print('\nR:\n', r)
Output:
[[1 2 3]
 [3 4 5]]

Q:
 [[-0.31622777 -0.9486833 ]
 [-0.9486833   0.31622777]]

R:
 [[-3.16227766 -4.42718872 -5.69209979]
 [ 0.         -0.63245553 -1.26491106]]

Example 2:
Python3
import numpy as np    # Original matrixmatrix1 = np.array([[1, 0], [2, 4]])print(matrix1)  # Decomposition of the said matrixq, r = np.linalg.qr(matrix1)print('\nQ:\n', q)print('\nR:\n', r)
Output:
[[1 0]
 [2 4]]

Q:
 [[-0.4472136  -0.89442719]
 [-0.89442719  0.4472136 ]]

R:
 [[-2.23606798 -3.57770876]
 [ 0.          1.78885438]]

Example 3:
Python3
import numpy as np     # Create a numpy array  arr = np.array([[5, 11, -15], [12, 34, -51],                 [-24, -43, 92]], dtype=np.int32)     print(arr)  # Find the QR factor of array q, r = np.linalg.qr(arr) print('\nQ:\n', q)print('\nR:\n', r)
Output:
[[  5  11 -15]
 [ 12  34 -51]
 [-24 -43  92]]

Q:
 [[-0.18318583 -0.08610905  0.97929984]
 [-0.43964598 -0.88381371 -0.15995231]
 [ 0.87929197 -0.45984624  0.12404465]]

R:
 [[-27.29468813 -54.77256208 106.06459346]
 [  0.         -11.22347731   4.06028083]
 [  0.           0.           4.88017756]]

Python numpy-Linear Algebra
Python-numpy
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
Python program to convert a list to string
Reading and Writing to text files in Python
Python | Remove given element from the list - GeeksforGeeks

20 May, 2019
Given a list, write a Python program to remove the given element (list may have duplicates) from given list. There are multiple ways we can do this task in Python. Let’s see some of Pythonic ways to do this task.
Method #1: Using pop() method [Remove given element found first.]
# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9]     # Printing initial list print ("original list : "+ str(list1))     remove = 9    # using pop() # to remove list element 9if remove in list1:     list1.pop(list1.index(remove))     # Printing list after removal print ("List after element removal is : "  + str(list1)) 
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [1, 8, 4, 9, 2, 9]

 Method #2: Using remove() method
# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9]     # Printing initial list print ("original list : "+ str(list1))   # using remove() to remove list element 9list1.remove(9)     # Printing list after removal print ("List after element removal is : "  + str(list1)) 
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [1, 8, 4, 9, 2, 9]

Now, let’s see the ways to remove all occurrence of given element.
Method #3: Using set
Since the list is converted to set, all duplicates are removed, but the ordering of list cannot be preserved.
# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9]     # Printing initial list print ("original list : "+ str(list1))   # using discard() method to remove list element 9list1 = set(list1) list1.discard(9)     list1 = list(list1)     # Printing list after removal print ("List after element removal is : "  + str(list1)) 
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [8, 1, 2, 4]

 Method #4: Using list comprehension
# Python program to remove given element from the listlist1 = [1, 9, 8, 4, 9, 2, 9]     # Printing initial list print ("original list : "+ str(list1))   # using List Comprehension # to remove list element 9list1 = [ele for ele in list1 if ele != 9]     # Printing list after removal print ("List after element removal is : "  + str(list1)) 
original list : [1, 9, 8, 4, 9, 2, 9]
List after element removal is : [1, 8, 4, 2]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
How to find the mean of columns of an R data frame or a matrix?

If all the columns in an R data frame are numeric then it makes sense to find the mean for each of the columns. This calculation will help us to view how different the values of means are for each of the columns but to make sure that they are significantly different, we will need to run a hypothesis test. To find the column means of a data frame or a matrix we can use colMeans function.
Consider the below data frame −
 Live Demo
set.seed(9)
x1<-rnorm(20,0.2)
x2<-rnorm(20,0.5)
x3<-rnorm(20,0.8)
x4<-rnorm(20,1.5)
x5<-rpois(20,2)
x6<-rpois(20,5)
df<-data.frame(x1,x2,x3,x4,x5,x6)
df
x1 x2 x3 x4 x5 x6
1  -0.56679604 2.2569929 -0.008456344 1.7812222 2 4
2  -0.61645834 0.6822521 -1.219381694 0.2972914 4 5
3   0.05846481 0.2331113 0.061275928 1.9651637 1 3
4  -0.07760503 1.4264216 1.182886561 1.8520164 4 5
5   0.63630690 -0.1933319 2.530863668 0.9101438 2 3
6  -0.98687252 3.1819901 0.596918049 0.6464000 4 10
7   1.39198691 0.7225245 -0.196397348 1.2532679 4 7
8   0.18180966 -0.2066724 -0.506536295 3.0393386 3 5
9  -0.04808460 0.9172132 -0.197831604 2.0460777 0 4
10 -0.16293689 0.8695568 0.234971274 3.0649619 1 3
11 1.47757055 -0.4137643 2.552057836 1.7496702 2 4
12 -0.26889715 0.1830853 0.252228648 -0.4624186 1 4
13 0.27105410 1.5490592 -0.058525708 0.6909398 3 3
14 -0.06603845 0.6681118 0.849294533 1.0013149 2 5
15 2.04525720 0.5314402 0.599955518 1.8051218 1 7
16 -0.63944966 -0.5103305 -0.303954449 1.2107928 0 4
17 0.12255194 0.8827515 1.040588038 2.9577142 0 2
18 -2.41770553 -0.3196965 1.181113616 2.3737555 5 5
19 1.08788403 0.8617111 3.030458950 0.5470440 3 6
20 -0.50749145 0.5933714 1.999202392 1.4683245 1 6
colMeans(df)
x1 x2 x3 x4 x5 x6
0.04572752 0.69578987 0.68103658 1.50990712 2.15000000 4.75000000
Finding the mean of columns of a matrix if the matrix is a square matrix −
 Live Demo
Matrix<-matrix(1:100,nrow=10)
Matrix
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
colMeans(Matrix)
[1] 5.5 15.5 25.5 35.5 45.5 55.5 65.5 75.5 85.5 95.5
 Live Demo
Finding the mean of columns of a matrix if the matrix is not a square matrix −
Matrix_new<-matrix(1:100,ncol=20)
Matrix_new
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,] 1 6 11 16 21 26 31 36 41 46 51 56 61 66
[2,] 2 7 12 17 22 27 32 37 42 47 52 57 62 67
[3,] 3 8 13 18 23 28 33 38 43 48 53 58 63 68
[4,] 4 9 14 19 24 29 34 39 44 49 54 59 64 69
[5,] 5 10 15 20 25 30 35 40 45 50 55 60 65 70
[,15] [,16] [,17] [,18] [,19] [,20]
[1,] 71 76 81 86 91 96
[2,] 72 77 82 87 92 97
[3,] 73 78 83 88 93 98
[4,] 74 79 84 89 94 99
[5,] 75 80 85 90 95 100
colMeans(Matrix_new)
[1] 3 8 13 18 23 28 33 38 43 48 53 58 63 68 73 78 83 88 93 98
How can multiple plots be plotted in same figure using matplotlib and Python?

Matplotlib is a popular Python package that is used for data visualization.
Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations.
It helps in communicating the quantitative insights to the audience effectively.
Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on.
It is written in Python. It is created using Numpy, which is the Numerical Python package in Python.
Python can be installed on Windows using the below command −
pip install matplotlib
The dependencies of Matplotlib are −
Python ( greater than or equal to version 3.4)
NumPy
Setuptools
Pyparsing
Libpng
Pytz
Free type
Six
Cycler
Dateutil
Sometimes, it may be required to understand two different data sets, one with respect to other. This is when such multiple plots can be plotted.
Let us understand how Matplotlib can be used to plot multiple plots −
import numpy as np
import matplotlib.pyplot as plt
x1_val = np.linspace(0.0, 6.0)
x2_val = np.linspace(0.0, 3.0)
y1_val = np.cos(2.3 * np.pi * x1_val) * np.exp(−x1_val)
y2_val = np.cos(2.4 * np.pi * x2_val)
fig, (ax1, ax2) = plt.subplots(2, 1)
fig.suptitle('Two plots')
ax1.plot(x1_val, y1_val ,'o−')
ax1.set_ylabel('Plot 1')
ax2.plot(x2_val, y2_val, '.−')
ax2.set_xlabel('x-axis')
ax2.set_ylabel('Plot 2')
plt.show()
The required packages are imported and its alias is defined for ease of use.
The required packages are imported and its alias is defined for ease of use.
The data is created using the ‘Numpy’ library for two different data sets.
The data is created using the ‘Numpy’ library for two different data sets.
An empty figure is created using the ‘figure’ function.
An empty figure is created using the ‘figure’ function.
The data is plotted using the ‘plot’ function.
The data is plotted using the ‘plot’ function.
The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title.
The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title.
It is shown on the console using the ‘show’ function.
It is shown on the console using the ‘show’ function.
How can we show a popup menu when the user right-clicks on a JComboBox in Java?

A JComboBox is a subclass of JComponent class that displays a drop-down list and gives users options that we can select one and only one item at a time. A JComboBox can be editable or read-only. A getSelectedItem()
method can be used to get the selected or entered item from a combo box. We can invoke a popup menu from a JComboxBox when the user right-clicks on it by implementing a MouseListener interface and need to override the mouseReleased() method. The method isPopupTrigger() of MouseEvent class can be used to show a popup menu.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JComboBoxPopupTest extends JFrame {
   private JComboBox jcb;
   private JPopupMenu jpm;
   private JMenuItem mItem1, mItem2;
   public JComboBoxPopupTest() {
      setTitle("JComboBoxPopup Test");
      setLayout(new FlowLayout());
      jcb = new JComboBox(new String[] {"Item 1", "Item 2", "Item 3"});
      jpm = new JPopupMenu();
      mItem1 = new JMenuItem("Popup Item 1");
      mItem2 = new JMenuItem("Popup Item 2");    
      jpm.add(mItem1);
      jpm.add(mItem2);
      ((JButton)jcb.getComponent(0)).addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent me) {
            if (me.isPopupTrigger()) {
               jpm.show(jcb, me.getX(), me.getY());
            }
         }
      });
      add(jcb);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) throws Exception {
      new JComboBoxPopupTest();
   }
}
PHP - Function eregi()

int eregi(string pattern, string string, [array regs]);

The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case sensitive. Eregi() can be particularly useful when checking the validity of strings, such as passwords.
The optional input parameter regs contains an array of all matched expressions that were grouped by parentheses in the regular expression.
It returns true if the pattern is validated, and false otherwise.
Following is the piece of code, copy and paste this code into a file and verify the result.
<?php
   $password = "abc";
   
   if (! eregi ("[[:alnum:]]{8,10}", $password))
   {
      print "Invalid password! Passwords must be from 8 - 10 chars";
   } else {
      print "Valid password";
   }
?>
This will produce the following result −
Invalid password! Passwords must be from 8 - 10 chars


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Big Data Analytics - Logistic Regression

Logistic regression is a classification model in which the response variable is categorical. It is an algorithm that comes from statistics and is used for supervised classification problems. In logistic regression we seek to find the vector β of parameters in the following equation that minimize the cost function.
logit(pi)=ln(pi1−pi)=β0+β1x1,i+...+βkxk,i
The following code demonstrates how to fit a logistic regression model in R. We will use here the spam dataset to demonstrate logistic regression, the same that was used for Naive Bayes.
From the predictions results in terms of accuracy, we find that the regression model achieves a 92.5% accuracy in the test set, compared to the 72% achieved by the Naive Bayes classifier.
library(ElemStatLearn)
head(spam) 

# Split dataset in training and testing 
inx = sample(nrow(spam), round(nrow(spam) * 0.8)) 
train = spam[inx,] 
test = spam[-inx,]  

# Fit regression model 
fit = glm(spam ~ ., data = train, family = binomial()) 
summary(fit)  

# Call: 
#   glm(formula = spam ~ ., family = binomial(), data = train) 
#  

# Deviance Residuals:  
#   Min       1Q   Median       3Q      Max   
# -4.5172  -0.2039   0.0000   0.1111   5.4944
# Coefficients: 
# Estimate Std. Error z value Pr(>|z|)     
# (Intercept) -1.511e+00  1.546e-01  -9.772  < 2e-16 *** 
# A.1         -4.546e-01  2.560e-01  -1.776 0.075720 .   
# A.2         -1.630e-01  7.731e-02  -2.108 0.035043 *   
# A.3          1.487e-01  1.261e-01   1.179 0.238591     
# A.4          2.055e+00  1.467e+00   1.401 0.161153     
# A.5          6.165e-01  1.191e-01   5.177 2.25e-07 *** 
# A.6          7.156e-01  2.768e-01   2.585 0.009747 **  
# A.7          2.606e+00  3.917e-01   6.652 2.88e-11 *** 
# A.8          6.750e-01  2.284e-01   2.955 0.003127 **  
# A.9          1.197e+00  3.362e-01   3.559 0.000373 *** 
# Signif. codes:  0 *** 0.001 ** 0.01 * 0.05 . 0.1  1  

### Make predictions 
preds = predict(fit, test, type = ’response’) 
preds = ifelse(preds > 0.5, 1, 0) 
tbl = table(target = test$spam, preds) 
tbl 

#         preds 
# target    0   1 
# email   535  23 
# spam     46 316 
sum(diag(tbl)) / sum(tbl) 
# 0.925


    65 Lectures 
     6 hours 

 Arnab Chakraborty

    18 Lectures 
     1.5 hours 

 Pranjal Srivastava, Harshit Srivastava

    23 Lectures 
     2 hours 

 John Shea

    18 Lectures 
     1.5 hours 

 Pranjal Srivastava

    46 Lectures 
     3.5 hours 

 Pranjal Srivastava

    37 Lectures 
     3.5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page