code-rag-bench/online-tutorials huggingface dataset:
What is the difference between Array.slice() and Array.splice() in JavaScript ? - GeeksforGeeks

19 Feb, 2020
Javascript arrays are variables that can hold more than one value. There are many methods associated with these arrays. The methods slice() and splice() are widely used methods for array manipulations. There are various differences between them which are listed in the table below.
Syntax:
slice():array_name.slice(s, e)
array_name.slice(s, e)
splice():array_name.splice(i, n, item 1, item 2, .....item n)
array_name.splice(i, n, item 1, item 2, .....item n)
Examples for slice() methodExample 1: Both the start and end are specified.
<script>    var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire'];    var new_cars=cars.slice(1, 4);    document.write("cars :", cars, "<br><br>");     document.write("new_cars :", new_cars);</script>
Output:
cars :Benz, Innova, Breeza, Etios, Dzire
new_cars :Innova, Breeza, Etios
Example 2: only the start is specified. The end is by default the length of the array.
<script>    var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire'];    var new_cars=cars.slice(2);    document.write("cars :", cars, "<br><br>");    document.write("new_cars :", new_cars);</script>
Output:
cars :Benz, Innova, Breeza, Etios, Dzire

new_cars :Breeza, Etios, Dzire
Examples for splice() methodExample 1: Now let us just add some more items but not remove any item.
<script>    var cars=['Benz', 'Innova', 'Breeza', 'Etios', 'Dzire'];    cars.splice(2, 0, 'ambassedor', 'BMW', 'Audi');    document.write("cars :", cars, "<br><br>");</script>
Output:
cars :Benz, Innova, ambassedor, BMW, Audi, Breeza, Etios, Dzire
Example 2: Removing one element and not adding any new item
<script>    var cars=['Benz', 'Innova', 'ambassedor', 'BMW', 'Audi', 'Breeza', 'Etios', 'Dzire'];    cars.splice(2, 1);    document.write("cars :", cars, "<br><br>");</script>
Output:
cars :Benz, Innova, BMW, Audi, Breeza, Etios, Dzire

Example 3: Removing more than one element and not adding any new item.
<script>    var cars=['Benz', 'Innova', 'ambassedor', 'BMW', 'Audi', 'Breeza', 'Etios', 'Dzire'];    cars.splice(2, 3);    document.write("cars :", cars, "<br><br>");</script>
Output:
cars :Benz, Innova, Breeza, Etios, Dzire
While removing more than one element, in the above case, the starting index specified is ‘2’ and ‘3-elements’ are required to be removed, so it starts removing elements from the index itself. Thus the items in index 2, 3 and 4 are removed.
PHP-function
Picked
Technical Scripter 2019
JavaScript
Technical Scripter
Web Technologies
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 Open URL in New Tab 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 ?
How to insert spaces/tabs in text using HTML/CSS?
How to Iterate over Dataframe Groups in Python-Pandas? - GeeksforGeeks

18 Aug, 2020
In this article, we’ll see how we can iterate over the groups in which a dataframe is divided. So, let’s see different ways to do this task.
First, Let’s create a dataframe:
Code:
Python3
# import pandas libraryimport pandas as pd  # dictionarydict = {'X': ['A', 'B', 'A', 'B'],        'Y': [1, 4, 3, 2]}  # create a dataframedf = pd.DataFrame(dict)  # show the dataframedf
Output:
Method 1: Using Dataframe.groupby().
This function is used to split the data into groups based on some criteria. 
Example: we’ll simply iterate over all the groups created.
Python3
# import pandas libraryimport pandas as pd  # dictionarydict = {'X': ['A', 'B', 'A', 'B'],        'Y': [1, 4, 3, 2]}  # create a dataframedf = pd.DataFrame(dict)  # group by 'X' columngroups = df.groupby("X")  for name, group in groups:    print(name)    print(group)    print("\n")
Output:
In above example, we have grouped on the basis of column “X”. As there are two different values under column “X”, so our dataframe will be divided into 2 groups. Then our for loop will run 2 times as the number groups are 2. “name” represents the group name and “group” represents the actual grouped dataframe. 
Method 2: Using Dataframe.groupby() and Groupby_object.groups.keys() together.
Groupby_object.groups.keys() method will return the keys of the groups.
Example: we’ll iterate over the keys.
Python3
# import pandas libraryimport pandas as pd  # dictionarydict = {'X': ['A', 'B', 'A', 'B'],        'Y': [1, 4, 3, 2]}  # create a dataframedf = pd.DataFrame(dict)  # group by "X" columngroups = df.groupby('X')  # extract keys from groupskeys = groups.groups.keys()  for i in keys:    print(groups.get_group(i))    print('\n')
Output:
In above example, we’ll use the function groups.get_group() to get all the groups. First we’ll get all the keys of the group and then iterate through that and then calling get_group() method for each key. get_group()  method will return group corresponding to the key.
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
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
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Custom Hooks in ReactJS

In this article, we are going to learn how to define custom hooks in ReactJS.
All the rules and usage guidelines are the same as that of the predefined ReactJS hooks like −
Call Hooks at the Top Level
Call Hooks at the Top Level
Call Hooks from React Functions only
Call Hooks from React Functions only
In this example, we will build an input validator application that will display some text based on the user-defined conditions in the custom hook.
App.jsx
import React from 'react';
import useForm from './CustomHook';

const App = () => {
   const input = useForm();
   return (
      <div>
      <input onChange={input.onChange} value={input.value} />
      {input.valid ? 'Welcome to TutorialsPoint' : 'Try again'}
      </div>
   );
};
export default App;
CustomHook.jsx
import React, { useState } from 'react';

const useForm = () => {
   const [val, setVal] = useState('');
   const [valid, setValid] = useState(false);

   const inputHandler = (e) => {
      setVal(e.target.value);
      e.target.value === 'TutorialsPoint' ? setValid(true) : setValid(false);
   };
   return { value: val, onChange: inputHandler, valid };
};

export default useForm;
In the above example, when the user types in the input field, then the custom hook is called which decides whether the text is valid or not based on certain conditions.
This will produce the following result.
Find the safe position | Practice | GeeksforGeeks

There was a group of Jewish soldiers who were surrounded by Roman Army in a circular fence. They decided not to get captured by the brutal Roman Army. So, they made a plan.
They planned to kill each other. The soldier would kill the fellow soldier next to him on left. They would do so till only one soldier is left and in the last the remained soldier would kill themselves. But there was a problem, soldier A didn’t want to die he want to stay alive so he wanted to stand a position where he could stand till last. After all his fellow soldiers died he would simple surrender himself rather then killing himself. So, given N i,e number of Jewish soldiers, find the safe_position of soldier A.
 
Example 1:
Input: N = 10
Output: 5
Explanation: 1 kills 2 : 3 kills 4 : 
5 kills 6 : 7 kills 8 : 9 kills 10
Now 1 kills 3 : 5 kills 7 : 9 kills 1 
Now 5 kills 9 

Example 2:
Input: N = 3
Output: 3
Explanation: 1 kills 2 : 3 kills 1
Safe_Position  : 3

 
Your Task:
You don't need to read or print anything. Your task is to complete the function find_pos() which takes N as input parameter and returns the safe position for soldier A.
 
Expected Time Complexity: O(log(N))
Expected Space Complexity: O(1)
 
Constraints:
1 <= N <= 100000
 
0
vikramadityakumar1 month ago
def find_pos(self, N):
	    p = 1
        while p <= N:
            p *= 2
        return (2 * N) - p + 1
0
Kingshuk Basak5 years ago
Kingshuk Basak
Program Stopped!! Your program is taking more than 5 sec.Hint : There might be an infinite loop or non-terminating recursion in your code.
Need Help
Code:
#codet=int(input())while(t>0):    n=int(input())    d=[]    for i in range(1,n+1):        d.append(i)    j=len(d)    while(j>1):        if(j%2==0):            for i in range(j-1,0,-2):                del d[-i]        else:            for i in range(j-2,0,-2):                del d[-i+1]            del d[0]        j=len(d)    print(d[0])    t=t-1
0
sunil maurya5 years ago
sunil maurya
focus on power of 2  its simple.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
Python - Compare Dictionaries on certain Keys - GeeksforGeeks

04 May, 2020
Sometimes, while working with Python dictionaries, we can have a problem in which we need to compare dictionaries for equality on bases in selected keys. This kind of problem is common and has application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we iterate for both the dictionary and manually test for keys equality using equality operator from selected keys.
# Python3 code to demonstrate working of # Compare Dictionaries on certain Keys# Using loop  # initializing dictionariestest_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5}  # printing original dictionariesprint("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # initializing compare keys comp_keys = ['best', 'geeks']  # Compare Dictionaries on certain Keys# Using loopres = Truefor key in comp_keys:    if test_dict1.get(key) != test_dict2.get(key):        res = False        break       # printing result print("Are dictionary equal : " + str(res)) 
The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}Are dictionary equal : True
 
Method #2 : Using all()This is one liner alternative to perform this task. In this the functionality of comparison is done using all(), comparing all required keys.
# Python3 code to demonstrate working of # Compare Dictionaries on certain Keys# Using all()  # initializing dictionariestest_dict1 = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5}test_dict2 = {'gfg' : 2, 'is' : 3, 'best' : 3, 'for' : 7, 'geeks' : 5}  # printing original dictionariesprint("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2))  # initializing compare keys comp_keys = ['best', 'geeks']  # Compare Dictionaries on certain Keys# Using all()res = all(test_dict1.get(key) == test_dict2.get(key) for key in comp_keys)      # printing result print("Are dictionary equal : " + str(res)) 
The original dictionary 1 : {‘geeks’: 5, ‘gfg’: 1, ‘is’: 2, ‘for’: 4, ‘best’: 3}The original dictionary 2 : {‘geeks’: 5, ‘gfg’: 2, ‘is’: 3, ‘for’: 7, ‘best’: 3}Are dictionary equal : True
Python dictionary-programs
Python
Python Programs
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
Python program to convert a list to string
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 Exclude Columns in Pandas? - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss how to exclude columns in pandas dataframe.
Let’s create a dataframe with four columns in python.
Python3
# import pandas moduleimport pandas as pd  # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4],                     'name': ['idly', 'dosa', 'poori', 'chapathi'],                     'city': ['delhi', 'goa', 'hyd', 'chennai'],                     'cost': [12, 34, 21, 23]})  # displaydata
Output:
We can exclude one column from the pandas dataframe by using the loc function. This function removes the column based on the location.
Syntax:
dataframe.loc[:, ddataframe.columns!='column_name']
Parameters:
dataframe: is the input dataframe
columns: is the method used to get the columns
column_name: is the column to be excluded
Example:
In this example, we will be using the loc() function with the given data frame to exclude columns with name,city, and cost in python.
Python3
# import pandas moduleimport pandas as pd  # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4],                     'name': ['idly', 'dosa', 'poori', 'chapathi'],                     'city': ['delhi', 'goa', 'hyd', 'chennai'],                     'cost': [12, 34, 21, 23]})  # exclude name columnprint(data.loc[:, data.columns != 'name'])  # exclude city columnprint(data.loc[:, data.columns != 'city'])  # exclude cost columnprint(data.loc[:, data.columns != 'cost'])
Output:
Here we are using loc function with isin operator to exclude the multiple columns
Syntax:
dataframe.loc[:, ~dataframe.columns.isin([‘column1’,.................., ‘column n’])]
Example:
In this example, we will be using the isin operator to exclude the name and food_id column from the given data frame.
Python3
# import pandas moduleimport pandas as pd  # create food dataframedata = pd.DataFrame({'food_id': [1, 2, 3, 4],                     'name': ['idly', 'dosa', 'poori', 'chapathi'],                     'city': ['delhi', 'goa', 'hyd', 'chennai'],                     'cost': [12, 34, 21, 23]})  # exclude name and food_id columnprint(data.loc[:, ~data.columns.isin(['name', 'food_id'])])
Output:
pandas-dataframe-program
Picked
Python pandas-dataFrame
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
C program to find Highest Common Factor (HCF) and Least Common Multiple (LCM)

First, let us learn how to find Highest Common Factor (HCF).
The greatest number divides each of the two or more numbers is called HCF or Highest Common Factor. It is also called as Greatest Common Measure(GCM) and Greatest Common Divisor(GCD).
For example,
What is the HCF of 12 and 16?
Factors of 12 = 1, 2, 3, 4, 6,12.
Factors of 16=1,2,4,8,16
Highest common factor (H.C.F) of 12 and 16 = 4.
For two integers x and y, denoted LCM(x,y), it is the smallest positive integer that is divisible by both x and y.
For example,
LCM(2,3) = 6 and LCM(6,10) = 30.
 Live Demo
#include <stdio.h>
int main() {
   int num1, num2, x, y, temp, gcd, lcm;
   printf("Enter two integers\n");
   scanf("%d%d", &x, &y);
   num1 = x;
   num2 = y;
   while (num2 != 0) {
      temp = num2;
      num2 = num1 % num2;
      num1 = temp;
   }
   gcd = num1;
   lcm = (x*y)/gcd;
   printf("GCD of %d and %d = %d\n", x, y, gcd);
   printf("LCM of %d and %d = %d\n", x, y, lcm);
   return 0;
}
Upon execution, you will receive the following output −
Run 1:
Enter two integers
6 12
GCD of 6 and 12 = 6
LCM of 6 and 12 = 12
Run 2:
Enter two integers
24 36
GCD of 24 and 36 = 12
LCM of 24 and 36 = 72
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

20 Sep, 2021
Let X denote the Exclusive OR (XOR) operation. Let ‘1’ and ‘0’ denote the binary constants. Consider the following Boolean expression for F over two variables P and Q:
F(P, Q) = ( ( 1 X P) X (P X Q) ) X ( (P X Q) X (Q X 0) ) 
The equivalent expression for F is(A) P + Q(B) (P + Q)’(C) P X Q(D) (P X Q)’Answer: (D)Explanation: We need to simplify the above expression. As the given operation is XOR, we shall see property of XOR.
Let A and B be boolean variable.
In A XOR B, the result is 1 if both the bits/inputs are different, else 0.
Now,

( ( 1 X P) X (P X Q) ) X ( (P X Q) X (Q X 0) )

( P' X P X Q ) X ( P X Q X Q ) ( as 1 X P = P' and Q X 0 = Q )

(1 X Q) X ( P X 0) ( as P' X P = 1 , and Q X Q = 0 )

Q' X P ( as 1 X Q = Q' and P X 0 = P )

PQ + P'Q' ( XOR Expansion, A X B = AB' + A'B )

This is the final simplified expression.

Now we need to check for the options.

If we simplify option D expression.

( P X Q )' = ( PQ' + P'Q )' ( XOR Expansion, A X B = AB' + A'B )

((PQ')'.(P'Q)') ( De Morgan's law )

( P'+ Q).(P + Q') ( De Morgan's law )

P'P + PQ + P'Q' + QQ'

PQ + P'Q' ( as PP' = 0 and QQ' = 0 ) 

Hence both the equations are same. Therefore Option D. 
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersBoolean Algebra and Identities | GATE PYQs  with Rishabh Setiya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:001:00 / 22:24•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=mDkgr_tIfYc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-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
Statistical - NORM.S.INV Function

The NORMS.S.INV function returns the inverse of the standard normal cumulative distribution. The distribution has a mean of zero and a standard deviation of one.
NORM.S.INV (probability)

If probability is nonnumeric, NORMS.INV returns the #VALUE! error value.
If probability is nonnumeric, NORMS.INV returns the #VALUE! error value.
If probability <= 0 or if probability >= 1, NORMS.INV returns the #NUM! error value.
If probability <= 0 or if probability >= 1, NORMS.INV returns the #NUM! error value.
Given a value for probability, NORM.S.INV seeks that value z such that
NORM.S.DIST (z,TRUE) = probability

Given a value for probability, NORM.S.INV seeks that value z such that
NORM.S.DIST (z,TRUE) = probability
Thus, precision of NORM.S.INV depends on precision of NORM.S.DIST. NORM.S.INV uses an iterative search technique.
Excel 2010, Excel 2013, Excel 2016

    296 Lectures 
     146 hours 

 Arun Motoori

    56 Lectures 
     5.5 hours 

 Pavan Lalwani

    120 Lectures 
     6.5 hours 

 Inf Sid

    134 Lectures 
     8.5 hours 

 Yoda Learning

    46 Lectures 
     7.5 hours 

 William Fiset

    25 Lectures 
     1.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Swing Examples - Show Confirm Dialog with custom buttons

Following example showcase how to show confirm dialog with customized button texts in swing based application.
We are using the following APIs.
JOptionPane − To create a standard dialog box.
JOptionPane − To create a standard dialog box.
JOptionPane.showOptionDialog() − To show the message alert with multiple options.
JOptionPane.showOptionDialog() − To show the message alert with multiple options.
JOptionPane.YES_NO_OPTION − To get Yes and No buttons.
JOptionPane.YES_NO_OPTION − To get Yes and No buttons.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new FlowLayout();  
      panel.setLayout(layout);       

      JButton button = new JButton("Click Me!");
      final JLabel label = new JLabel();
      button.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            String[] options = {"Yes! Please.", "No! Not now."}; 
            int result = JOptionPane.showOptionDialog(
               frame,
               "Sure? You want to exit?", 
               "Swing Tester",            
               JOptionPane.YES_NO_OPTION,
               JOptionPane.QUESTION_MESSAGE,
               null,     //no custom icon
               options,  //button titles
               options[0] //default button
            );
            if(result == JOptionPane.YES_OPTION){
               label.setText("You selected: Yes! Please");
            }else if (result == JOptionPane.NO_OPTION){
               label.setText("You selected: No! Not now.");
            }else {
               label.setText("None selected");
            }
         }
      });

      panel.add(button);
      panel.add(label);
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }  
} 
 Print
 Add Notes
 Bookmark this page
Filter null from an array in JavaScript?

To filter null from an array and display only non-null values instead, use filter(). Following is the
code −
var
names=[null,"John",null,"David","","Mike",null,undefined,"Bob","Adam",null,null];
console.log("Before filter null=");
console.log(names);
var filterNull=[];
filterNullValues=names.filter(obj=>obj);
console.log("After filtering the null values=");
console.log(filterNullValues);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo148.js. This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo148.js
Before filter null=[
   null, 'John',
   null, 'David',
   '', 'Mike',
   null, undefined,
   'Bob', 'Adam',
   null, null
]
After filtering the null values=
[ 'John', 'David', 'Mike', 'Bob', 'Adam' ]
Java 8 - Method References

Method references help to point to methods by their names. A method reference is described using "::" symbol. A method reference can be used to point the following types of methods −
Static methods
Instance methods
Constructors using new operator (TreeSet::new)
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
import java.util.List;
import java.util.ArrayList;

public class Java8Tester {

   public static void main(String args[]) {
      List names = new ArrayList();
		
      names.add("Mahesh");
      names.add("Suresh");
      names.add("Ramesh");
      names.add("Naresh");
      names.add("Kalpesh");
		
      names.forEach(System.out::println);
   }
}
Here we have passed System.out::println method as a static method reference.
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java

Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester

It should produce the following output −
Mahesh
Suresh
Ramesh
Naresh
Kalpesh


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
What is the difference between Read(), ReadKey() and ReadLine() methods in C#?

The Read() reads the next characters from the standard input stream. If a key is pressed on the console, then it would close.
int az = Console.Read()
Console.WriteLine(z);
It reads only a single charactare from the standard input stream.
Reads the next line of characters from the standard input stream.
 Live Demo
using System;
class Program {
   static void Main() {

      int x = 10;
      Console.WriteLine(x);
      Console.Write("\nPress any key to continue... ");
      Console.ReadLine();
   }
}
10

Press any key to continue...
Vector capacity() Method in Java - GeeksforGeeks

17 Aug, 2018
The Java.util.Vector.capacity() method in Java is used to get the capacity of the Vector or the length of the array present in the Vector.
Syntax:
Vector.capacity()
Parameters: The method does not take any parameter.
Return Value: The method returns the capacity or the internal data array’s length present in the Vector, which is an integer value.
Below programs illustrate the Java.util.Vector.capacity() method:
Program 1: Vector with string elements.
// Java code to illustrate capacity()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<String> vec_tor = new Vector<String>();          // Use add() method to add elements into the Vector        vec_tor.add("Welcome");        vec_tor.add("To");        vec_tor.add("Geeks");        vec_tor.add("4");        vec_tor.add("Geeks");          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Displaying the capacity of Vector        System.out.println("The capacity is: " + vec_tor.capacity());    }}
Vector: [Welcome, To, Geeks, 4, Geeks]
The capacity is: 10

Program 2: Vector with Integer elements.
// Java code to illustrate capacity()import java.util.*;  public class VectorDemo {    public static void main(String args[])    {        // Creating an empty Vector        Vector<Integer> vec_tor = new Vector<Integer>();          // Use add() method to add elements into the Vector        vec_tor.add(10);        vec_tor.add(15);        vec_tor.add(30);        vec_tor.add(20);        vec_tor.add(5);          // Displaying the Vector        System.out.println("Vector: " + vec_tor);          // Displaying the capacity of Vector        System.out.println("The capacity is: " + vec_tor.capacity());    }}
Vector: [10, 15, 30, 20, 5]
The capacity is: 10

Java - util package
Java-Collections
Java-Functions
Java-Vector
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Arrays.sort() in Java with examples
Reverse a string in Java
Stream In Java
Interfaces in Java
How to iterate any Map in Java
HTML 5 <summary> Tag - GeeksforGeeks

25 Jan, 2022
The <summary> tag in HTML is used to define a summary for the <details> element. 
The <summary> element is used along with the <details> element and provides a summary visible to the user.
When the summary is clicked by the user, the content placed inside the <details> element becomes visible which was previously hidden.
The <summary> tag was added in HTML 5.
The <summary> tag requires both starting and ending tag.
Note: The <summary> element should be the first child element of the <details> element.
Syntax: 
<summary> Content </summary>
Below program illustrates the <summary> element:Input : 
HTML
<!DOCTYPE html><html><body> <details>  <!-- html summary tag is used here -->  <summary>GeeksforGeeks.</summary>    <p> It is a portal for geeks.</p>  </details> </body></html>
Output :  
Supported Browsers: 
Google Chrome 12.0
Firefox 48.0
Opera 15.0
Safari 6.0
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
nidhi_biet
shubhamyadav4
hritikbhatnagar2182
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
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?
StringTokenizer hasMoreElements() Method in Java with Examples - GeeksforGeeks

28 Jan, 2019
The hasMoreElements() method of StringTokenizer class also checks whether there are any more tokens available with this StringTokenizer. It is similar to the hasMoreTokens(). The method exists exclusively so that the Enumeration interface of this class can be implemented.
Syntax:
public boolean hasMoreElements()
Parameters: The method does not take any parameters.
Return Value: The method returns boolean True if the availability of at least one more token is found in the string after the current position else false.
Below programs illustrate the working of hasMoreElements() Method of StringTokenizer:Example 1:
// Java code to illustrate hasMoreElements() method  import java.util.*;  public class StringTokenizer_Demo {    public static void main(String args[])    {        // Creating a StringTokenizer        StringTokenizer str_arr            = new StringTokenizer(                "Lets practice at GeeksforGeeks");          // Counting the tokens        System.out.println("The number of Tokens are: "                           + str_arr.countTokens());          // Checking for any tokens        System.out.println(str_arr.hasMoreElements());          // Checking and displaying the Tokens        while (str_arr.hasMoreElements()) {            System.out.println("The Next token: "                               + str_arr.nextToken());        }    }}
The number of Tokens are: 4
true
The Next token: Lets
The Next token: practice
The Next token: at
The Next token: GeeksforGeeks

Example 2:
// Java code to illustrate hasMoreElements() method  import java.util.*;  public class StringTokenizer_Demo {    public static void main(String args[])    {        // Creating a StringTokenizer        StringTokenizer str_arr            = new StringTokenizer("");          // Counting the tokens        System.out.println("The number of Tokens are: "                           + str_arr.countTokens());          // Checking for any tokens        System.out.println(str_arr.hasMoreElements());    }}
The number of Tokens are: 0
false

Java - util package
Java-Functions
Java-StringTokenizer
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
How to navigate back to current page from Frame in selenium webdriver?

We can navigate back to the current page from frame with Selenium webdriver. A frame is defined with <iframe>, <frame> or <frameset> tag in html code. A frame is used to embed an HTML document within another HTML document.
Selenium by default has access to the main browser driver. In order to access a frame element, the driver focus has to shift from the main browser window to the frame. To again focus back to the current page from frame, the method switchTo().defaultContent() is used.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class SwitchBackFrame{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://the-internet.herokuapp.com/frames");
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // identify element and click
      driver.findElement(By.partialLinkText("Nested")).click();
      // switching to frame with frame name
      driver.switchTo().frame("frame-bottom");
      WebElement m = driver.findElement(By.cssSelector("body"));
      System.out.println("Frame text: " +m.getText());
      // switch from frame to main page
      driver.switchTo().defaultContent();
      driver.close();
   }
}
Scope resolution operator in C++

The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary. You can use the unary scope operator if a namespace scope or global scope name is hidden by a particular declaration of an equivalent name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator.
#include <iostream>  
using namespace std;  

int my_var = 0;
int main(void) {
   int my_var = 0;
   ::my_var = 1;  // set global my_var to 1
   my_var = 2;    // set local my_var to 2
   cout << ::my_var << ", " << my_var;
   return 0;
}
This will give the output −
1, 2
The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope.
You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example,
#include <iostream>
using namespace std;
class X {
   public:
   static int count;
};
int X::count = 10;  // define static data member

int main () {
   int X = 0;   // hides class type X
   cout << X::count << endl;   // use static member of class X
}
This will give the output −
10
Python | Use of __slots__ - GeeksforGeeks

27 Dec, 2019
When we create objects for classes, it requires memory and the attribute are stored in the form of a dictionary. In case if we need to allocate thousands of objects, it will take a lot of memory space.slots provide a special mechanism to reduce the size of objects.It is a concept of memory optimisation on objects.
Example of python object without slots :
class GFG(object):      def __init__(self, *args, **kwargs):                self.a = 1                self.b = 2  if __name__ == "__main__":     instance = GFG()     print(instance.__dict__)
Output :
{'a': 1, 'b': 2}
As every object in Python contains a dynamic dictionary that allows adding attributes. For every instance object, we will have an instance of a dictionary that consumes more space and wastes a lot of RAM. In Python, there is no default functionality to allocate a static amount of memory while creating the object to store all its attributes.Usage of __slots__ reduce the wastage of space and speed up the program by allocating space for a fixed amount of attributes.
Example of python object with slots :
class GFG(object):      __slots__=['a', 'b']      def __init__(self, *args, **kwargs):                self.a = 1                self.b = 2  if __name__ == "__main__":     instance = GFG()     print(instance.__slots__)
Output :
['a', 'b']
Example of python if we use dict :
class GFG(object):      __slots__=['a', 'b']      def __init__(self, *args, **kwargs):                self.a = 1                self.b = 2  if __name__ == "__main__":     instance = GFG()     print(instance.__dict__)
Output :
AttributeError: 'GFG' object has no attribute '__dict__'
This error will be caused.
Result of using __slots__:
Fast access to attributesSaves memory space
Fast access to attributes
Saves memory space
Python
Python Programs
Technical Scripter
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 ?
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 clear Python shell?

Python provides a python shell which is used to execute a single Python command and display the result. It is also called REPL. REPL stands for Read, Evaluate, Print and Loop. The command is read, then evaluated, afterwards the result is printed and looped back to read the next command.
Sometimes after executing so many commands and getting haphazard output or having executed some unnecessary commands, we may need to clear the python shell. If the shell is not cleared, we will need to scroll the screen too many times which is inefficient. Thus, it is required to clear the python shell.
The commands used to clear the terminal or Python shell are cls and clear.
In Windows
import os
os.system(‘CLS’)
In Linux
import os
os.system(‘clear’)
Let us suppose, we need to show some output for few seconds and then we want to clear the shell. The following code serves the purpose.
Import os and sleep
Import os and sleep
Define a function where the commands to clear the shell are specified, cls for windows and clear for linux.
Define a function where the commands to clear the shell are specified, cls for windows and clear for linux.
Print some output
Print some output
Let the screen sleep for few seconds
Let the screen sleep for few seconds
Call the function to clear the screen
Call the function to clear the screen
from os import system, name
from time import sleep
def clear():
   # for windows
   if name == 'nt':
      _ = system('cls')

   # for mac and linux
   else:
   _ = system('clear')

print(“Hi Learner!!”)
sleep(5)
clear()
D3.js curveCardinal() Method - GeeksforGeeks

09 Sep, 2020
The curveCardinal() method produces a cubic cardinal spline. The curve is also based on these cubic cardinal splines.
Syntax:
d3.curveCardinal()
Parameters: This method does not accept any parameters.
Return Value: This method does not return any value.
Example 1: 
HTML
<!DOCTYPE html><html><meta charset="utf-8">  <head>    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js">    </script></head>  <body>    <h1 style="text-align:center;color:green;">        GeeksforGeeks    </h1>    <center>        <svg id="gfg" width="200" height="200"></svg>    </center>          <script>        var data = [            { x: 0, y: 0 },            { x: 1, y: 3 },            { x: 2, y: 15 },            { x: 5, y: 15 },            { x: 6, y: 1 },            { x: 7, y: 5 },            { x: 8, y: 1 }];          var xScale = d3.scaleLinear()            .domain([0, 8]).range([25, 175]);        var yScale = d3.scaleLinear()            .domain([0, 20]).range([175, 25]);          var line = d3.line()            .x((d) => xScale(d.x))            .y((d) => yScale(d.y))            .curve(d3.curveCardinal);          d3.select("#gfg")            .append("path")            .attr("d", line(data))            .attr("fill", "none")            .attr("stroke", "green");    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html><meta charset="utf-8">  <head>    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js">    </script></head>  <body>    <h1 style="text-align:center; color:green;">        GeeksforGeeks    </h1>    <center>        <svg id="gfg" width="200" height="200"></svg>    </center>      <script>        var points = [            { xpoint: 25, ypoint: 150 },            { xpoint: 75, ypoint: 85 },            { xpoint: 100, ypoint: 115 },            { xpoint: 175, ypoint: 25 },            { xpoint: 200, ypoint: 150 }];          var Gen = d3.line()            .x((p) => p.xpoint)            .y((p) => p.ypoint)            .curve(d3.curveCardinal);          d3.select("#gfg")            .append("path")            .attr("d", Gen(points))            .attr("fill", "none")            .attr("stroke", "green");    </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Command Line arguments in C#

If you want to pass arguments by command line, then use command line arguments in C# −
When we create a program in c#, static void main is used and we can see the arguments in it .
class HelloWorld {
   static void Main(string[] args) {
      /* my first program in C# */
      Console.WriteLine("Hello World");
      Console.ReadKey();
   }
The string[] args is a variable that has all the values passed from the command line as shown above.
Now to print those arguments, let’s say we have an argument, “One” −
Console.WriteLine("Length of the arguments: "+args.Length);
Console.WriteLine("Arguments:");
foreach (Object obj in args) {
   Console.WriteLine(obj);
}
The above will print −
Length of the arguments: 1
Arguments: One
Python List len() Method

Python list method len() returns the number of elements in the list.
Following is the syntax for len() method −
len(list)

list − This is a list for which number of elements to be counted.
list − This is a list for which number of elements to be counted.
This method returns the number of elements in the list.
The following example shows the usage of len() method.
#!/usr/bin/python

list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
When we run above program, it produces following result −
First list length :  3
Second list length :  2


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to Redirect 404 errors to a page in Express.js ? - GeeksforGeeks

10 Oct, 2021
Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request method (GET, POST, DELETE, etc) and the requested route.
In Express if we want to redirect the user to the 404 error page if a particular route does not exist then we can use the app.all() method as the last route handler method and * (asterisk) as the route name. Asterisk is a wildcard that matches any route name.
Syntax:
app.all('*', (req, res) => {
    // code logic
})
The route mentioned above can handle all kinds of HTTP request methods and request to any route name.
 
Project Setup
Step 1: Install Node.js if you haven’t already.
Step 2: Create a folder for your project and cd (change directory) into it. Create a new file named app.js inside that folder. Now, initialize a new Node.js project with default configurations using the following command.
npm init -y
Step 3: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like the following.
app.js
const express = require('express');const app = express();  app.get('/', (req, res) => {  res.send('<h1>Home page</h1>');});  app.get('/products', (req, res) => {  res.send('<h1>Products page</h1>');});  // This route will handle all the requests that are // not handled by any other route handler. In // this hanlder we will redirect the user to // an error page with NOT FOUND message and status// code as 404 (HTTP status code for NOT found)app.all('*', (req, res) => {  res.status(404).send('<h1>404! Page not found</h1>');});  app.listen(3000, () => {  console.log('Server is up on port 3000');});
Step to run the application: You can run your express server by using the following command on the command line.
node app.js
Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/some_invalid_route and you will be redirected to our error page with a message.
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript