code-rag-bench/online-tutorials huggingface dataset:
Powershell - Create Text File

New-Item cmdlet is used to create a text file and Set-Content cmdlet to put content into it.
In this example, we're creating a new text file named test.txt
Type the following command in PowerShell ISE Console
New-Item D:\temp\test\test.txt
You can see the test.txt created in D:\temp\test directory.
In this example, we're adding content to test.txt.
Type the following command in PowerShell ISE Console
Set-Content D:\temp\test\test.txt 'Welcome to TutorialsPoint'
In this example, we're reading content of test.txt.
get-Content D:\temp\test\test.txt

You can see following output in PowerShell console.
Welcome to TutorialsPoint


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
What is setInterval() method in JavaScript?

This is one of the many timing events. The window object allows code to execute at every certain interval of time. This object has provided SetInterval() to repeat a function for every certain amount of time. It takes two parameters as arguments. One is the function and the other is the time that specifies the interval after which the function should be repeated.
window.setInterval(function, milliseconds, param1, param2, ...));
This method can also take other parameters and can add it to the function.
In the following example, setInterval() method is defined and a time interval of 3000 millisecs or 3 seconds is declared. Therefore the function provided inside it will repeat for every 3 secs. The result, for a time span of 9 secs, is showed in the output.
Live Demo
<html>
<body>
<script>
   setInterval(function(){
      document.write("Tutorix </br>");
   }, 3000);
</script>
</body>
</html>
Tutorix
Tutorix
Tutorix
In the following example, setInterval() method is defined and a time interval of 2000 millisecs is declared. Therefore the function provided inside it will repeat for every 2 secs. The result is showed in the output.
Live Demo
<html>
<body>
<script>
   setInterval(function(){
      document.write("Hello </br>");
   }, 2000);
</script>
</body>
</html>
Hello
Hello
p5.js | Mouse | mouseButton - GeeksforGeeks

16 Apr, 2019
The mouseButton variable in p5.js is used to get automatically which kind of key is pressed on mouse. The value of the system variable mouseButton is either LEFT, RIGHT, or CENTER depending on which button was pressed last.
Syntax:
mouseButton
Below programs illustrate the mouseButton variable in p5.js:
Example 1: This example uses mouseButton variable to detect the mouse button.
function setup() {          // Create canvas    createCanvas(500, 500);}   function draw() {          // Set background color    background(237, 34, 93);          // Fill color    fill(0);       if (mouseIsPressed) {        if (mouseButton === LEFT) {            ellipse(height/2, width/2, 100, 100);        }        if (mouseButton === RIGHT) {            rect(height/2, width/2, 100, 100);        }    }}
Output:
Example 2: This example uses mouseButton variable to detect the mouse button.
function setup() {          // Create canvas    createCanvas(500, 500);          // Set the text size    textSize(40); }   function draw() {          // Set background color    background(237, 34, 93);          // Set the text color    fill(255);          // Check the status of the mouse    if (mouseIsPressed) {        text(mouseButton, height/2, width/2);    }}
Output:Reference: https://p5js.org/reference/#/p5/mouseButton
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
IntStream boxed() in Java - GeeksforGeeks

06 Dec, 2018
IntStream boxed() returns a Stream consisting of the elements of this stream, each boxed to an Integer.
Note : IntStream boxed() is a intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.Syntax :
Stream<Integer> boxed()

Parameters :
Stream : A sequence of elements supporting sequential and parallel aggregate operations.Integer : The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
Stream : A sequence of elements supporting sequential and parallel aggregate operations.
Integer : The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
Return Value : The function returns a Stream boxed to an Integer.
Example 1 :
// Java code for IntStream boxed()import java.util.*;import java.util.stream.Stream;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.range(3, 8);          // Creating a Stream of Integers        // Using IntStream boxed() to return        // a Stream consisting of the elements        // of this stream, each boxed to an Integer.        Stream<Integer> stream1 = stream.boxed();          // Displaying the elements        stream1.forEach(System.out::println);    }}
Output :
3
4
5
6
7

Example 2 :
// Java code for IntStream boxed()import java.util.*;import java.util.stream.Stream;import java.util.stream.IntStream;  class GFG {      // Driver code    public static void main(String[] args)    {        // Creating an IntStream        IntStream stream = IntStream.range(3, 8);          // Creating a Stream of Integers        // Using IntStream boxed() to return        // a Stream consisting of the elements        // of this stream, each boxed to an Integer.        Stream<Integer> stream1 = stream.boxed();          Stream<Object> stream2 = Stream.concat(stream1,                                    Stream.of("Geeks", "for", "Geeks"));          // Displaying the elements        stream2.forEach(System.out::println);    }}
Output :
3
4
5
6
7
Geeks
for
Geeks

Java - util package
Java-Functions
java-intstream
java-stream
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
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Google Interview Experience for Internship (Coding Round) - GeeksforGeeks

16 Oct, 2020
Google Internship (North America) coding round was held between 28th August to 5th September 2020 by Google(NA) for Software Engineering students of Pre-final and final year. The level of this Coding Round was easy.  The coding round comprised of two questions which are as follows :
Question 1: Most Booked Hotel Room
Problem Description: Given a hotel which has 10 floors [0-9] and each floor has 26 rooms [A-Z]. You are given a sequence of rooms, where + suggests the room is booked, – the room is freed. You have to find the number of rooms that were booked.
You may assume that the list describes a correct sequence of bookings in chronological order; that is, only free rooms can be booked, and only booked rooms can be freed. 
You may assume:
N (length of input) is an integer within the range [1, 600]
Each element of array A is a string consisting of three characters: “+” or “-“; a digit “0”-“9”; and uppercase English letter “A” – “Z”
Example:
Input: ["+1A", "+3E", "-1A", "+4F", "+1A", "-3E"]
Output: 4
Explanation: 4 rooms are booked at this time.
Input: ["-1C", "-3F", "-1L", "-ZF", "-1R", "-3E"]
Output: 0
Explanation: All rooms are free.
Question 2: Maximum Time
Problem Description: You are given a string that represents time in the format HH: MM. Some digits are blank (represented by ?). Fill in? With the same digit such that the time represented by this string is the maximum possible.
 Maximum time: 23:59, minimum time: 00:00. You can assume that the input string is always valid.
Example :
Input: "?4:5?"
Output: "14:51"
Input: "23:5?"
Output: "23:59"
Input: "0?:??"
Output: "05:55"
Input: "??:??"
Output: "22:22"
Google
Marketing
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
Zoho Interview Experience (Off-Campus ) 2022
HashedIn by Deloitte Interview Experience for SDE Intern+FTE | (Off-Campus) 2022
McKinsey Interview Experience for Software Associate Internship
Groww Interview Experience for SDE Intern (Web) Off-Campus
Amazon Interview Questions
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Overriding toString() method in Scala - GeeksforGeeks

24 Jun, 2019
Consider the following Scala program:
// Scala Program without override toString method  // Creating Classclass Language(LangArticle: Int, LangName: String) {      // Defining getLangArticle method    def getLangArticle() : Int = {                  return LangArticle;    }          // Defining getLangName method    def getLangName() : String = {                  return LangName;    }  }  // Creating objectobject GFG {    // Main method    def main(args: Array[String])    {                  var language = new Language(50, "Scala");                  println(language)              }}
Language@506e1b77

The output is, class name, then ‘at’ sign, and at the end hashCode of object. All classes in Scala inherit from the Object class, directly or indirectly . The object class has some basic methods like clone(), toString(), equals(), .. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. Below is the example to override toString method.
// Scala Program to override toString method  // Creating Classclass Language(LangArticle: Int, LangName: String) {      // Defining getLangArticle method    def getLangArticle() : Int = {                  return LangArticle;    }          // Defining getLangName method    def getLangName() : String = {                  return LangName;    }          // Overriding tostring method    override def toString() : String = {                  return "[Total Article : " + LangArticle +                 ", Language Name = " + LangName+"]";    }  }  // Creating objectobject GFG {    // Main method    def main(args: Array[String])    {                  var language = new Language(50, "Scala");                  println(language)              }}
[Total Article : 50, Language Name = Scala]

In above example Language class, which is overriding the toString() method and returning string value. This method has attributes names and values. The class defines two variables LangArticle and LangName and three methods: getLangArticle, getLangName and toString. getLangArticle takes one integer arguments and return a value. getLangName takes one string arguments and return a value. toString, on the other hand, does take any parameters but returns a String value. Since toString overrides the pre-defined toString method, it has to be tagged with the override flag.
Note: When we override the any super class method . We should use override keyword before the method (i.e: override def toString()).
Scala-OOPS
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Inheritance in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Break statement in Scala
How to get the first element of List in Scala
Fabric.js | Rect padding Property - GeeksforGeeks

25 May, 2020
In this article, we are going to see how to change the padding between the object and controlling the border of a canvas rectangle using FabricJS. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width.
To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rect provided by FabricJS and change the padding between object and controlling border of the rectangle using padding property and render the Rect on the Canvas as given in the example below.
Syntax:
fabric.Rect({
    width: number,
    height: number,
    padding: number
});
Parameters: This function accepts three parameters as mentioned above and described below:
width: It specifies the width of rectangle.
height: It specifies the height of rectangle.
padding: It specifies the padding between object and controlling border.
Example: This example uses FabricJS to change padding between object and controlling border of a canvas rectangle. Note that you have to click on the object to see the padding.
<!DOCTYPE html> <html>   <head>     <title>         Fabric.js | Rect padding Property    </title>           <!-- Adding the FabricJS library -->    <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">     </script> </head>   <body>     <div style="text-align: center;width: 600px;">          <h1 style="color: green;">              GeeksforGeeks          </h1>          <b>              Fabric.js | Rect padding Property          </b>      </div>     <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000">     </canvas>           <script>               // Initiate a Canvas instance         var canvas = new fabric.Canvas("canvas");           // Initiate a Rect instance         var rectangle = new fabric.Rect({             width: 200,            height: 100,            fill: '',             stroke: 'green',            strokeWidth: 3,            padding: 40        });           // Render the Rect in canvas         canvas.add(rectangle);         canvas.centerObject(rectangle);    </script> </body>   </html>
Output:
Fabric.js
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Angular File Upload
Lodash _.debounce() Method
GATE | GATE-CS-2014-(Set-1) | Question 31 - GeeksforGeeks

07 Dec, 2021
Consider the relation scheme R = {E, F, G, H, I, J, K, L, M, M} and the set of functional dependencies {{E, F} -> {G}, {F} -> {I, J}, {E, H} -> {K, L}, K -> {M}, L -> {N} on R. What is the key for R?(A) {E, F}(B) {E, F, H}(C) {E, F, H, K, L}(D) {E}Answer: (B)Explanation: All attributes can be derived from {E, F, H}
To solve these kind of questions that are frequently asked in GATE paper, try to solve it by using shortcuts so that enough amount of time can be saved.
First Method:
Using the given options try to obtain closure of each options. The solution is the one that contains R and also minimal Super Key, i.e Candidate Key.

A) {EF}+ = {EFGIJ} ≠ R(The given relation)

B) {EFH}+ = {EFGHIJKLMN} = R (Correct since each member of the 
                                    given relation is determined)

C) {EFHKL}+ = {EFGHIJKLMN} = R (Not correct although each member 
                                of the given relation can be determined 
                                but it is not minimal, since by the definition
                                of Candidate key it should be minimal Super Key)

 D) {E}+ = {E} ≠ R


Second Method:
Since, {EFGHIJKLMN}+ =  {EFGHIJKLMN}

{EFGHIJKLM}+ =  {EFGHIJKLMN} ( Since L -> {N}, hence can replace N by L)

In a similar way K -> {M} hence replace M by K

{EFGHIJKL}+ =  {EFGHIJKLMN} 

Again {EFGHIJ}+ =  {EFGHIJKLMN} (Since  {E, H} -> {K, L}, hence replace KL by EH)

{EFGH}+ =  {EFGHIJKLMN} (Since {F} -> {I, J} )

{EFH}+ =  {EFGHIJKLMN} (Since {E, F} -> {G} )


This explanation is contributed by Manish Rai.
Learn more here:
Finding Attribute Closure and Candidate Keys using Functional DependenciesQuiz of this Question
sweetyty
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
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
How to get file name from a path in PHP ? - GeeksforGeeks

03 Dec, 2021
In this article, we will see how to get the file name from the path in PHP, along with understanding its implementation through the examples. We have given the full path & we need to find the file name from the file path. For this, we will following below 2 methods:
Using the basename() function
Using the pathinfo( ) Function
Input : path = /testweb/var/www/mywebsite/htdocs/home.phpOutput : home.php
Input : path = /testweb/var/www/mywebsite/htdocs/abc.txtOutput : abc.txt
We will understand both functions with the help of examples.
Method 1: Using basename() function:
The basename() function is an inbuilt function that returns the base name of a file if the path of the file is provided as a parameter to the basename() function. 
Syntax:
$filename = basename(path, suffix);
The path is a required field that specifies the path which is to be checked. The suffix is an optional field that specifies a file extension. If the filename has this file extension, the file extension will not show.
Example: This example describes the use of the basename() function that returns the base name of the file.
PHP
<?php  $path = "/testweb/var/www/mywebsite/htdocs/home.php";    $file1 = basename($path);  $file2 = basename($path, ".php");    // Show filename with file extension  echo $file1 . "\n";    // Show filename without file extension  echo $file2;?>
Output:
home.php
home
Method 2: Using pathinfo() function:
The pathinfo() is an inbuilt function that is used to return information about a path using an associative array or a string ie., It will create an array with the parts of the path we want to use.
Syntax:
$filename = pathinfo(path);
Example: This example explains the pathinfo() function that will return information about a path. Here, we will use $filename[‘basename’], when we want to access the file name.
PHP
<?php  // Path of the file stored under pathinfo  $myFile = pathinfo('/usr/admin/config/test.php');    // Show the file name  echo $myFile['basename'], "\n";?>
Output:
test.php
Akanksha_Rai
bhaskargeeksforgeeks
PHP-file-handling
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
C++ while loop

A while loop statement repeatedly executes a target statement as long as a given condition is true.
The syntax of a while loop in C++ is −
while(condition) {
   statement(s);
}

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a = 10;

   // while loop execution
   while( a < 20 ) {
      cout << "value of a: " << a << endl;
      a++;
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
What are default arguments in python?

Python allows function arguments to have default values; if the function is called without the argument, the argument gets its default value
Default arguments:
Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator. Below is a typical syntax for default argument. Here, foo parameter has a default value Hi!
def defaultArg(name, foo='Come here!'):
    print name,foo
defaultArg('Joe')
Joe Come here!
We see that in the above code there is one required argument and one default one in the declaration. In the output we see that both the arguments are printed even though only one argument was passed in the function call. The default argument is passed automatically and appears in the output of the function call.
How to find the Odd and Even numbers in an Array in java?

In the loop check, the result of i%2 operation on each element if 0 the element is even else the element is odd.
Live Demo
public class OddNumbersInAnArray {
   public static void main(String args[]) {
      int[] myArray = {23, 93, 56, 92, 39};
      System.out.println("Even numbers in the given array are:: ");
      for (int i=0; i<myArray.length; i++) {
         if(myArray[i]%2 == 0) {
            System.out.println(myArray[i]);
         }
      }
      System.out.println("Odd numbers in the given array are:: ");
      for (int i=0; i<myArray.length; i++) {
         if(myArray[i]%2 != 0) {
            System.out.println(myArray[i]);
         }
      }
   }
}
Even numbers in the given array are::
56
92
Odd numbers in the given array are::
23
93
39
Python | Check if all the values in a list are less than a given value - GeeksforGeeks

10 Dec, 2018
Given a list, write a Python program to check if all the values in a list are less than the given value.
Examples:
Input : list = [11, 22, 33, 44, 55] 
        value = 22 
Output : No

Input : list = [11, 22, 33, 44, 55] 
        value = 65 
Output : Yes
Method #1: Traversing the listCompare each element by iterating through the list and check if all the elements in the given list are less than the given value or not.
# Python program to check if all values # in the list are less than given value  # Function to check the valuedef CheckForLess(list1, val):           # traverse in the list     for x in list1:           # compare with all the          # values with value        if val <= x:             return False    return True      # Driver code list1 = [11, 22, 33, 44, 55] val = 65if (CheckForLess(list1, val)): print("Yes")else: print("No")
Output:
Yes
 
Method #2: Using all() functionUsing all() function we can check if all values are less than any given value in a single line. It returns true if the given condition inside the all() function is true for all values, else it returns false.
# Python program to check if all values # in the list are less than given value  # Function to check the valuedef CheckForLess(list1, val):     return(all(x < val for x in list1))       # Driver code list1 = [11, 22, 33, 44, 55] val = 65if (CheckForLess(list1, val)): print("Yes")else: print("No")
Output:
Yes
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Accessing Attributes and Methods in Python

As an object oriented programming language python stresses on objects. Classes are the blueprint from which the objects are created. Each class in python can have many attributes including a function as an attribute.
To check the attributes of a class and also to manipulate those attributes, we use many python in-built methods as shown below.
getattr() − A python method used to access the attribute of a class.
getattr() − A python method used to access the attribute of a class.
hasattr()  − A python method used to verify the presence of an attribute in a class.
hasattr()  − A python method used to verify the presence of an attribute in a class.
setattr() − A python method used to set an additional attribute in a class.
setattr() − A python method used to set an additional attribute in a class.
The below program illustrates the use of the above methods to access class attributes in python.
class StateInfo:
   StateName='Telangana'
   population='3.5 crore'

   def func1(self):
      print("Hello from my function")

print getattr(StateInfo,'StateName')

# returns true if object has attribute
print hasattr(StateInfo,'population')

setattr(StateInfo,'ForestCover',39)

print getattr(StateInfo,'ForestCover')

print hasattr(StateInfo,'func1')
Running the above code gives us the following result −
Telangana
True
39
True
To access the method of a class, we need to instantiate a class into an object. Then we can access the method as an instance method of the class as shown in the program below. Here through the self parameter, instance methods can access attributes and other methods on the same object.
class StateInfo:
   StateName='Telangana'
   population='3.5 crore'

   def func1(self):
      print("Hello from my function")

print getattr(StateInfo,'StateName')

# returns true if object has attribute
print hasattr(StateInfo,'population')

setattr(StateInfo,'ForestCover',39)

print getattr(StateInfo,'ForestCover')

print hasattr(StateInfo,'func1')

obj = StateInfo()
obj.func1()
Running the above code gives us the following result −
Telangana
True
39
True
Hello from my function
To access the method of one class from another class, we need to pass an instance of the called class to the calling class. The below example shows how it is done.
class ClassOne:
def m_class1(self):
print "Method in class 1"

# Definign the calling Class
class ClassTwo(object):
def __init__(self, c1):
self.c1 = c1

# The calling method
def m_class2(self):
Object_inst = self.c1()
Object_inst.m_class1()

# Passing classone object as an argument to classTwo
obj = ClassTwo(ClassOne)
obj.m_class2()

Running the above code gives us the following result −
Method in class 1
Counting number of whitespaces in text file using java


Here is an example of counting white spaces in text file using java,hope this helps you.
import java.io.*;
public class CountWhiteSpace {
   public static void main(String[] args) throws IOException {
      File file = new File("C:\\Users\\myjava\\count.txt"); //Creates a new File instance by       converting the given pathname string into an abstract pathname
      FileInputStream fn = new FileInputStream(file); //Instantiate the FileInputStream class by          passing an object of the required file as parameter to its constructor.
      InputStreamReader input = new InputStreamReader(fn); //Creates an InputStreamReader that uses          the default charset.
      BufferedReader reader = new BufferedReader(input); //Creates a buffering character-input stream       that uses a default-sized input buffer.
      String sentence;
      // Initializing counters
      int countWord = 0,whitespaceCount = 0;
      if((sentence= reader.readLine()) != null) {
         String[] wordlist = sentence.split("\\s+"); // \\s+ is the space delimiter in java
         countWord += wordlist.length;
         whitespaceCount += countWord -1;
      }
      System.out.println(" Number of whitespaces = " + whitespaceCount);
   }
}
Get exponential value of a number using Math.exp in Java

To get the exponential value of a number in Java, we use the java.lang.Math.exp() method. The Math.exp() returns a double value which is the Euler’s number e raised to the power of the argument. If the parameter is NaN, the result obtained is NaN. If the argument is positive infinity, then the result is positive infinity. In case the argument is negative infinity, then the output is positive zero.
Declaration − The java.lang.Math.exp() method is declared as follows:
public static double exp(double a)
where a is the number representing the power to which e is raised to.
Let us see a program to get an exponential value of a number using Math.exp in Java.
 Live Demo
import java.lang.Math;
public class Example {
   public static void main(String[] args) {
      // declaring and initializing some double values
      double a = -0.7;
      double b = 1;
      double c = 5;
      //printing their exponential values
      System.out.println("Exponential value of " + a + " = " + Math.exp(a));
      System.out.println("Exponential value of " + b + " = " + Math.exp(b));
      System.out.println("Exponential value of " + c + " = " + Math.exp(c));
   }
}
Exponential value of -0.7 = 0.4965853037914095
Exponential value of 1.0 = 2.718281828459045
Exponential value of 5.0 = 148.4131591025766
Find closest number in array in C++

Suppose we have an array A with n elements. And elements are sorted. We have to find the closest value to the given integer. The array may contain duplicate values and negative numbers. So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5.
We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.
 Live Demo
#include<iostream>
#include<list>
using namespace std;
int getNearest(int x, int y, int target) {
   if (target - x >= y - target)
      return y;
   else
      return x;
}
int getNearestElement(int arr[], int n, int target) {
   if (target <= arr[0])
      return arr[0];
   if (target >= arr[n - 1])
      return arr[n - 1];
   int left = 0, right = n, mid = 0;
   while (left < right) {
      mid = (left + right) / 2;
      if (arr[mid] == target)
         return arr[mid];
      if (target < arr[mid]) {
         if (mid > 0 && target > arr[mid - 1])
            return getNearest(arr[mid - 1], arr[mid], target);
            right = mid;
      } else {
         if (mid < n - 1 && target < arr[mid + 1])
            return getNearest(arr[mid], arr[mid + 1], target);
         left = mid + 1;
      }
   }
   return arr[mid];
}
int main() {
   int arr[] = { 2, 5, 6, 7, 8, 8, 9 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int target = 4;
   cout << "Nearest element of " << target << " is: " << getNearestElement(arr, n, target);
}
Nearest element of 4 is: 5
D3.js json() Function - GeeksforGeeks

31 Aug, 2020
The d3.json() function is used to fetch the JSON file. If this function got an init parameter, then this is called along with the fetch operation.
Syntax:
d3.json(input[, init]);
Parameters: This function accepts two parameters as mentioned above and described below.
input: This parameter takes the address of the input file.
init: This parameter takes a function that does some operation with the data of the file.
Note: Please create a JSON file named “sample.json” before writing the given example.
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width,          initial-scale=1.0" />              <script src=        "https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>        // Data of sample.json file        // {        //     "place": "GeeksforGeeks",        //     "visitiors": "100M",        //     "target": "Client",        //     "source": "Server"        // }        d3.json("sample.json", function (d) {            console.log(d);        });    </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.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to detect browser or tab closing in JavaScript ?
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
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
What is useState() in React ?

09 Jun, 2022
The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component. React has two types of components, one is class components which are ES6 classes that extend from React and the other is functional components. Class components a Component and can have state and lifecycle methods: class Message extends React. The  useState hook is a special function that takes the initial state as an argument and returns an array of two entries.  UseState encapsulate only singular value from the state, for multiple state need to have useState calls.
Syntax: The first element is the initial state and the second one is a function that is used for updating the state.
const [state, setState] = useState(initialstate)
We can also pass a function as an argument if the initial state has to be computed. And the value returned by the function will be used as the initial state.
const [sum, setsum] = useState(function generateRandomInteger(){5+7);})
The above function is oneline function which computes the sum of two numbers and will be set as the initial state.
Importing: To use useState you need to import useState from react as shown below:
import React, { useState } from "react"
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Example: Below is the implementation of useState() function.
App.js
Javascript
import React, { useState } from "react"; function App(props) {  const [count, setRandomCount] =    useState(function generateRandomInteger() {    return Math.floor(Math.random() * 100);  });  function clickHandler(e) {    setRandomCount(Math.floor(Math.random() * 100));  }  return (    <div style={{margin: 'auto', width: 100, display: 'block'}}>      <h1> {count} </h1>              <p>        <button onClick={clickHandler}> Click </button>      </p>      </div>  );} export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
 
Explanation: First count variable is initialized with a random number using a random function and setRandomCount is used for updating the state of the count. Every time we click on the button onClick it calls the clickHandler function which sets the count variable again with a random number.
surbhikumaridav
Picked
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | File Test Operators

21 Feb, 2019
File Test Operators in Perl are the logical operators which return True or False values. There are many operators in Perl that you can use to test various different aspects of a file. For example, to check for the existence of a file -e operator is used. Or, it can be checked if a file can be written to before performing the append operation. This will help to reduce the number of errors that a program might encounter.
Following example uses the ‘-e’, existence operator to check if a file exists or not:
#!/usr/bin/perl  # Using predefined modulesuse warnings;use strict;   # Providing path of file to a variablemy $filename = 'C:\Users\GeeksForGeeks\GFG.txt';  # Checking for the file existenceif(-e $filename){          # If File exists    print("File $filename exists\n");}  else{          # If File doesn't exists    print("File $filename does not exists\n");}
Output:
Filename or filehandle is passed as an argument to this file test operator -e. Following is a list of most important File Test Operators:
You can use the AND logical operator in conjunction with file test operators as follows:
#!/usr/bin/perl  # Using predefined modulesuse warnings;use strict;   # Providing path of file to a variablemy $filename = 'C:\Users\GeeksForGeeks\GFG.txt';  # Applying multiple Test Operators # on the Fileif(-e $filename && -f _ && -r _ ){   print("File $filename exists and readable\n"); }  else{    print("File $filename doesn't exists")}
Output:Above example, checks for the existence of the file and if the file is plain or not and if it is readable.
Perl-files
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Polymorphism in OOPs
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Hello World Program in Perl
Use of print() and say() in Perl
Perl | ne operator
Perl | Basic Syntax of a Perl Program
Perl | eq operator
Scrollable ListBox in Python-tkinter

26 Mar, 2020
Tkinter is the standard GUI library for Python. Tkinter in Python comes with a lot of good widgets. Widgets are standard GUI elements, and the Listbox, Scrollbar will also come under this Widgets.
Note: For more information, refer to Python GUI – tkinter
The ListBox widget is used to display different types of items. These items must be of the same type of font and having the same font color. The items must also be of Text type. The user can select one or more items from the given list according to the requirement.
Syntax:
listbox = Listbox(root, bg, fg, bd, height, width, font, ..)
The scrollbar widget is used to scroll down the content. We can also create the horizontal scrollbars to the Entry widget.
Syntax:The syntax to use the Scrollbar widget is given below.
w = Scrollbar(master, options) 
Parameters:
master: This parameter is used to represents the parent window.
options: There are many options which are available and they can be used as key-value pairs separated by commas.
To do this we need to attach the scrollbar to Listbox, and to attach we use a function listbox.config() and set its command parameter to the scrollbar’s set method then set the scrollbar’s command parameter to point a method that would be called when the scroll bar position is changed
from tkinter import *    # Creating the root windowroot = Tk()  # Creating a Listbox and# attaching it to root windowlistbox = Listbox(root)  # Adding Listbox to the left# side of root windowlistbox.pack(side = LEFT, fill = BOTH)  # Creating a Scrollbar and # attaching it to root windowscrollbar = Scrollbar(root)  # Adding Scrollbar to the right# side of root windowscrollbar.pack(side = RIGHT, fill = BOTH)  # Insert elements into the listboxfor values in range(100):    listbox.insert(END, values)      # Attaching Listbox to Scrollbar# Since we need to have a vertical # scroll we use yscrollcommandlistbox.config(yscrollcommand = scrollbar.set)  # setting scrollbar command parameter # to listbox.yview method its yview because# we need to have a vertical viewscrollbar.config(command = listbox.yview)  root.mainloop()
Output
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Print lists in Python (5 Different Ways)
Different ways to create Pandas Dataframe
Queue in Python
Period of() method in Java with Examples

28 Nov, 2018
The of() method of Period Class is used to obtain a period from given number of Years, Months, and Days as parameters. These parameters are accepted in the form of integers. This method returns a Period with the given number of years, months, and days.
Syntax:
public static Period of(
        int numberOfYears, 
        int numberOfMonths,
        int numberOfDays)
Parameters: This method accepts following parameters:
numberOfYears: This is used to represent the amount of years which may be negative.
numberOfMonths: This is used to represent the amount of months which may be negative.
numberOfDays: This is used to represent the amount of days which may be negative.
Returns: This function returns the period which is the Period object parsed with the given number of Years, Months, and Days.
Below is the implementation of Period.of() method:
Example 1:
// Java code to demonstrate of() method  import java.time.Period;  class GFG {    public static void main(String[] args)    {          // Get the number of Years        int numberOfYears = 1;          // Get the number of Months        int numberOfMonths = 5;          // Get the number of Days        int numberOfDays = 21;          // Parse the given amounts into Period        // using of() method        Period p            = Period.of(numberOfYears,                        numberOfMonths,                        numberOfDays);          System.out.println(p.getYears() + " Years\n"                           + p.getMonths() + " Months\n"                           + p.getDays() + " Days");    }}
1 Years
5 Months
21 Days

Example 2:
// Java code to demonstrate of() method  import java.time.Period;  class GFG {    public static void main(String[] args)    {          // Get the number of Years        int numberOfYears = -2;          // Get the number of Months        int numberOfMonths = 10;          // Get the number of Days        int numberOfDays = -11;          // Parse the given amounts into Period        // using of() method        Period p            = Period.of(numberOfYears,                        numberOfMonths,                        numberOfDays);          System.out.println(p.getYears() + " Years\n"                           + p.getMonths() + " Months\n"                           + p.getDays() + " Days");    }}
-2 Years
10 Months
-11 Days

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Period.html#of-int-int-int-
Java-Functions
Java-Period
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Login Twitter using Python Selenium

04 Jan, 2021
Project Description:-Here, we’re going to study a simple how-to log in twitter by selenium. Selenium is a free tool for automated trying out across exceptional browsers.
Requirement:
Selenium – Selenium Python Introduction and Installation
Below are the steps:
First, go to the twitter website using this Link.
Then click on investigate element by urgent ctrl + shift + i or stepping into setting of browser and clicking on investigate detail manually.
Then navigate box where Phone, email, or username are filled then copy the x_path.
Then navigate the Password then copy the x_path.
Then navigate the Login button then copy the x_path.
Below is the implementation:
One can replace the username and password for the account to be successfully logged in. Here the code is for demonstration only.
from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport time  # create instance of Chrome webdriverdriver = webdriver.Chrome() driver.get("https://twitter.com/login")  # find the element where we have to # enter the xpath# fill the number or maildriver.find_element_by_xpath('//*[@id ="react-root"]/div/div/div[2]/main/div/div/div[1]/form/div/div[1]/label/div/div[2]/div/input').send_keys('XXXXXX0418')  # find the element where we have to # enter the xpath# fill the passworddriver.find_element_by_xpath('//*[@id ="react-root"]/div/div/div[2]/main/div/div/div[1]/form/div/div[2]/label/div/div[2]/div/input').send_keys('PrXXXXXXXXX9')  # find the element log in # request using xpath # clicking on that element driver.find_element_by_xpath('//*[@id ="react-root"]/div/div/div[2]/main/div/div/div[1]/form/div/div[3]/div/div').click()
Output –You will be logged in to twitter in the browser selenium has opened automatically.
Python Selenium-Exercises
Python-selenium
Advanced Computer Subject
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Reinforcement learning
Docker - COPY Instruction
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to use JavaScript to redirect an HTML page?

You might have encountered a situation where you clicked a URL to reach a page X but internally you were directed to another page Y. It happens due to page redirection.
It is quite simple to do a page redirect using JavaScript on the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows.
You can try to run the following code to learn how to use JavaScript to redirect an HTML page. Here, we will redirect to the homepage
Live Demo
<html>
   <head>
      <script>
         <!--
            function Redirect() {
               window.location.assign("https://www.tutorialspoint.com");
            }
          //-->
      </script>
   </head>
   <body>
      <p>Click the following button, you will be redirected to home page.</p>
      <input type="button" value="Redirect Me" onclick="Redirect();" />
   </body>
</html>
Tryit Editor v3.7

Tryit: Background image that scrolls with page
Can we define a try block with multiple catch blocks in Java?

Yes, we can define one try block with multiple catch blocks in Java.
Every try should and must be associated with at least one catch block.
Whenever an exception object is identified in a try block and if there are multiple catch blocks then the priority for the catch block would be given based on the order in which catch blocks are have been defined.
Highest priority would be always given to first catch block. If the first catch block cannot handle the identified exception object then it considers the immediate next catch block.
class TryWithMultipleCatch {
   public static void main(String args[]) {
      try{
         int a[]=new int[5];
         a[3]=10/0;
         System.out.println("First print statement in try block");
      } catch(ArithmeticException e) {
         System.out.println("Warning: ArithmeticException");
      } catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Warning: ArrayIndexOutOfBoundsException");
      } catch(Exception e) {
         System.out.println("Warning: Some Other exception");
      }
      System.out.println("Out of try-catch block");
   }
}
Warning: ArithmeticException
Out of try-catch block