code-rag-bench/online-tutorials huggingface dataset:
Difference between the list() and listFiles() methods in Java

The class named File of the java.io package represents a file or directory (path names) in the system. To get the list of all the existing files in a directory this class provides the list() and ListFiles() methods.
The main difference between them is that
The list() method returns the names of all files in the given directory in the form of a String array.
The list() method returns the names of all files in the given directory in the form of a String array.
The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File.
The ListFiles() method returns the objects (File) of the files in the given directory, in the form of an array of type File.
i.e. If you just need the names of the files within a particular directory you can use the list() method and, if you need the details of the files in a directory such as name, path etc. you need to use the ListFiles() method, retrieve the objects of all the files and get the required details by invoking the respective methods.
import java.io.File;
import java.io.IOException;
public class ListOfFiles {
   public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File path = new File("D:\\ExampleDirectory");
      //List of all files and directories
      String contents[] = path.list();
      System.out.println("List of files and directories in the specified directory:");
      for(int i=0; i < contents.length; i++) {
         System.out.println(contents[i]);
      }
   }
}
List of files and directories in the specified directory:
SampleDirectory1
SampleDirectory2
SampleFile1.txt
SampleFile2.txt
SapmleFile3.txt
import java.io.File;
import java.io.IOException;
public class ListOfFiles {
   public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File path = new File("D:\\ExampleDirectory");
      //List of all files and directories
      File files [] = path.listFiles();
      System.out.println("List of files and directories in the specified directory:");
      for(File file : files) {
         System.out.println("File name: "+file.getName());
         System.out.println("File path: "+file.getAbsolutePath());
         System.out.println(" ");
      }
   }
}
List of files and directories in the specified directory:
File name: SampleDirectory1
File path: D:\ExampleDirectory\SampleDirectory1

File name: SampleDirectory2
File path: D:\ExampleDirectory\SampleDirectory2

File name: SampleFile1.txt
File path: D:\ExampleDirectory\SampleFile1.txt

File name: SampleFile2.txt
File path: D:\ExampleDirectory\SampleFile2.txt

File name: SapmleFile3.txt
File path: D:\ExampleDirectory\SapmleFile3.txt
How to get the smallest integer greater than or equal to a number in JavaScript?

To get the smallest integer greater than or equal to a number, use the JavaScript Math.ceil() method. This method returns the smallest integer greater than or equal to a number.
You can try to run the following code to get the smallest integer greater than or equal to a number −
<html>
   <head>
      <title>JavaScript Math ceil() Method</title>
   </head>
   <body>
      <script>
         var value = Math.ceil(80.55);
         document.write("First Value : " + value );
         
         value = Math.ceil(42.45);
         document.write("<br />Second Value : " + value );
         
         value = Math.ceil(-70.70);
         document.write("<br />Third Value : " + value );
         
         value = Math.ceil(-20.30);
         document.write("<br />Fourth Value : " + value );
      </script>
   </body>
</html>
Iterator Functions in Python

In this article, we will learn about the four iterator functions available in Python 3.x. Or earlier namely accumulate() , chain(), filter false() , dropwhile() methods.
Now let’s look on each of them in detail −
Accumulate() method takes two arguments, one being iterable to operate on and another the function/operation to be performed. By default, the second argument performs the addition operation.
Chain() method prints all the iterable targets after concatenating all of the iterables.
The below example explains the implementation −
 Live Demo
import itertools
import operator as op
# initializing list 1
li1 = ['t','u','t','o','r']
# initializing list 2
li2 = [1,1,1,1,1]
# initializing list 3
li3 = ['i','a','l','s','p','o','i','n','t']
# using accumulate() add method
print ("The sum after each iteration is : ",end="")
print (list(itertools.accumulate(li1,op.add)))
# using accumulate() multiply method
print ("The product after each iteration is : ",end="")
print (list(itertools.accumulate(li2,op.mul)))
# using chain() method
print ("All values in mentioned chain are : ",end="")
print (list(itertools.chain(li1,li3)))
The sum after each iteration is : ['t', 'tu', 'tut', 'tuto', 'tutor']
The product after each iteration is : [1, 1, 1, 1, 1]
All values in mentioned chain are : ['t', 'u', 't', 'o', 'r', 'i',
'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
Drop while() method accepts a function to check the condition and an input iterable to operate on. It returns all values of the iterable after the condition becomes false.
Filterfalse() method accepts a function to check the condition and an input iterable to operate on. It returns the value when the given condition becomes false.
 Live Demo
import itertools
# list
l = ['t','u','t','o','r']
# using dropwhile() method
print ("The values after condition fails : ",end="")
print (list(itertools.dropwhile(lambda x : x!='o',l)))
# using filterfalse() method
print ("The values when condition fails : ",end="")
print (list(itertools.filterfalse(lambda x : x!='o',l)))
The values after condition fails : ['o', 'r']
The values when condition fails : ['o']
In this article, we learned about the different types of iterator functions available in Python 3.x. Or earlier.
DataFrame.to_pickle() in function Pandas - GeeksforGeeks

05 Jun, 2020
The to_pickle() method is used to pickle (serialize) the given object into the file. This method uses the syntax as given below :
Syntax:
DataFrame.to_pickle(self, path,
                    compression='infer',
                    protocol=4)

Example 1:
Python3
# importing packagesimport pandas as pd  # dictionary of datadct = {'ID': {0: 23, 1: 43, 2: 12,              3: 13, 4: 67, 5: 89,              6: 90, 7: 56, 8: 34},        'Name': {0: 'Ram', 1: 'Deep',                2: 'Yash', 3: 'Aman',                 4: 'Arjun', 5: 'Aditya',                6: 'Divya', 7: 'Chalsea',                8: 'Akash' },        'Marks': {0: 89, 1: 97, 2: 45, 3: 78,                 4: 56, 5: 76, 6: 100, 7: 87,                 8: 81},        'Grade': {0: 'B', 1: 'A', 2: 'F', 3: 'C',                 4: 'E', 5: 'C', 6: 'A', 7: 'B',                 8: 'B'}      }  # forming dataframe and printingdata = pd.DataFrame(dct)print(data)  # using to_pickle function to form file # with name 'pickle_file'data.to_pickle('pickle_file')
Output :
   ID     Name  Marks Grade
0  23      Ram     89     B
1  43     Deep     97     A
2  12     Yash     45     F
3  13     Aman     78     C
4  67    Arjun     56     E
5  89   Aditya     76     C
6  90    Divya    100     A
7  56  Chalsea     87     B
8  34    Akash     81     B

Example 2:
Python3
# importing packagesimport pandas as pd   # dictionary of datadct = {"f1": range(6), "b1": range(6, 12)}   # forming dataframe and printingdata = pd.DataFrame(dct)print(data)   # using to_pickle function to form # file with name 'pickle_file'data.to_pickle('pickle_file')
Output:
   f1  b1
0   0   6
1   1   7
2   2   8
3   3   9
4   4  10
5   5  11
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
How to Delete files in Python using send2trash module? - GeeksforGeeks

16 Jul, 2020
In this article, we will see how to safely delete files and folders using the send2trash module in Python. Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently deleting them. The OS module’s unlink(), remove() and rmdir() functions can be used to delete files or folders. But, these functions delete the files permanently. The operations cannot be undone if there were any accidental deletions performed. This can be prevented using send2trash.
OS : The OS module in Python provides functions for interacting with the operating system. OS module comes with Python’s Standard Library.
send2trash : Send2Trash is a small package that sends files to the Trash (or Recycle Bin) natively and on all platforms. To install it type the below command in the terminal.
pip install send2trash

The send2trash() function accepts the location of the file or folder to be deleted.
Python3
import send2trash  send2trash.send2trash("/location/to/file")
The process of deleting a directory is same as above. If the directory contains files or other folders, those are also deleted. A TrashPermissionError exception is raised, in case a file could not be deleted due to permission error or any other unexpected reason.
We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.txt’ files in the given directory.
Python3
import osimport send2trash  # walking through the directoryfor folder, subfolders, files in os.walk('/Users/tithighosh/Documents'):          for file in files:                # checking if file is        # of .txt type        if file.endswith('.txt'):            path = os.path.join(folder, file)                          # printing the path of the file            # to be deleted            print('deleted : ', path )                          # deleting the file            send2trash.send2trash(path)
Output :
deleted :  /Users/tithighosh/Documents/cfile.txt
deleted :  /Users/tithighosh/Documents/e_also_big_output.txt
deleted :  /Users/tithighosh/Documents/res.txt
deleted :  /Users/tithighosh/Documents/tk.txt

python-modules
Python-projects
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
Java Examples - Searching last occurance ?

How to search the last position of a substring ?
This example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.
public class SearchlastString {
   public static void main(String[] args) {
      String strOrig = "Hello world ,Hello Reader";
      int lastIndex = strOrig.lastIndexOf("Hello");
      
      if(lastIndex == - 1){
         System.out.println("Hello not found");
      } else {
         System.out.println("Last occurrence of Hello is at index "+ lastIndex);
      }
   }
}
The above code sample will produce the following result.
Last occurrence of Hello is at index 13

This another example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method.
public class HelloWorld{
   public static void main(String []args) {
      String t1 = "Tutorialspoint";
      int index = t1.lastIndexOf("p");
      System.out.println(index);
   }
}
The above code sample will produce the following result.
9

 Print
 Add Notes
 Bookmark this page
What is difference between raw_input() and input() functions in Python?

The function raw_input() presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. For example,
name = raw_input("What isyour name? ")
print "Hello, %s." %name
This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code. In Python 3, raw_input() was renamed to input() and can be directly used. For example,
name = input("What is your name? ")
print("Hello, %s." %name)
MySQL query to find duplicate tuples and display the count?

To find duplicate tuples, use GROUP BY HAVING clause. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.80 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(101,'David');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(101,'Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(100,'Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(100,'Chris');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+------+-------+
|   Id | Name  |
+------+-------+
|  100 | Chris |
|  101 | David |
|  101 | Mike  |
|  100 | Carol |
|  100 | Chris |
|  100 | Chris |
+------+-------+
6 rows in set (0.00 sec)
Following is the query to find duplicate tuples −
mysql> select Id,Name,count(*) as t from DemoTable
   -> group by Id,Name
   -> having count(*) > 2;
This will produce the following output −
+------+-------+---+
| Id   | Name  | t |
+------+-------+---+
| 100  | Chris | 3 |
+------+-------+---+
1 row in set (0.03 sec)
QlikView - Match Function

The Match() function in QlikView is used to match the value of a string on expression with  data value present in a column. It is similar to the in function that we see in SQL language. It is useful to fetch rows containing specific strings and it also has an extension in form of wildmatch() function.
Let us consider the following data as input file for the examples illustrated below.
Product_Id,Product_Line,Product_category,Product_Subcategory
1,Sporting Goods,Outdoor Recreation,Winter Sports & Activities
2,Food, Beverages & Tobacco,Food Items,Fruits & Vegetables
3,Apparel & Accessories,Clothing,Uniforms
4,Sporting Goods,Athletics,Rugby
5,Health & Beauty,Personal Care
6,Arts & Entertainment,Hobbies & Creative Arts,Musical Instruments
7,Arts & Entertainment,Hobbies & Creative Arts,Orchestra Accessories
8,Arts & Entertainment,Hobbies & Creative Arts,Crafting Materials
9,Hardware,Tool Accessories,Power Tool Batteries
10,Home & Garden,Bathroom Accessories,Bath Caddies
11,Food, Beverages & Tobacco,Food Items,Frozen Vegetables
12,Home & Garden,Lawn & Garden,Power Equipment
13,Office Supplies,Presentation Supplies,Display
14,Hardware,Tool Accessories,Jigs
15,Baby & Toddler,Diapering,Baby Wipes

The following script shows the Load script, which reads the file named product_categories.csv. We search the field Product_Line for values matching with strings 'Food' and 'Sporting Goods'. 
Let us create a Table Box sheet object to show the data generated by the match function. Go to the menu Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below.
The wildmatch() function is an extension of match() function in which we can use wildcards as part of the strings used to match the values with values in the fields being searched for. We search for the strings 'Off*','*ome*.
Let us create a Table Box sheet object to show the data generated by the wildmatch
function. Go to the menu item Layout → New Sheet Object → Table Box. The following window appears in which we mention the Title of the table and then select the required fields to be displayed. Clicking OK displays the data from the CSV file in the QlikView Table Box as shown below.

    70 Lectures 
     5 hours 

 Arthur Fong
 Print
 Add Notes
 Bookmark this page
React Custom Hooks

Hooks are reusable functions.
When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook.
Custom Hooks start with "use". Example: useFetch.
In the following code, we are fetching data in our Home component and displaying it.
We will use the JSONPlaceholder service to fetch fake data. This service is great for testing applications when there is no existing data.
To learn more, check out the JavaScript Fetch API section.
Use the JSONPlaceholder service to fetch fake "todo" items and display the titles on the page:
index.js:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

const Home = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((data) => setData(data));
 }, []);

  return (
    <>
      {data &&
        data.map((item) => {
          return <p key={item.id}>{item.title}</p>;
        })}
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);


Run 
Example »

The fetch logic may be needed in other components as well, so we will extract that into a custom Hook.
Move the fetch logic to a new file to be used as a custom Hook:
useFetch.js:
import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);

  return [data];
};

export default useFetch;

index.js:
import ReactDOM from "react-dom/client";
import useFetch from "./useFetch";

const Home = () => {
  const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");

  return (
    <>
      {data &&
        data.map((item) => {
          return <p key={item.id}>{item.title}</p>;
        })}
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);


Run 
Example »

We have created a new file called useFetch.js containing a function called useFetch which contains all of the logic needed to fetch our data.
We removed the hard-coded URL and replaced it with a url variable that can be passed to the custom Hook.
Lastly, we are returning our data from our Hook.
In index.js, we are importing our useFetch Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data from.
Now we can reuse this custom Hook in any component to fetch data from any URL.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to Merge DataFrames of different length in Pandas ? - GeeksforGeeks

28 Apr, 2021
In this article, we will discuss how to merge the two dataframes with different lengths in Pandas. It can be done using the merge() method.
Syntax:
DataFrame.merge(parameters)
Below are some examples that depict how to merge data frames of different lengths using the above method:
Example 1: 
Below is a program to merge two student data frames of different lengths.
Python3
# importing pandas module  import pandas as pd  # create a list that contains # student id of subject 1list1 = [7058, 7059, 7075, 7076]  # create a list that contains# student id of subject 2list2 = [7058, 7059, 7012, 7075, 7076]  # create a list that contains # student names of subject 1list11 = ["Sravan", "Jyothika", "Deepika",          "Kyathi"]  # create a list that contains # student names of subject 2list22 = ["Sravan", "Jyothika", "Salma",           "Deepika", "Kyathi"]    # pass list1 and list11 to the# dataframe1dataframe1 = pd.DataFrame(  {"Student ID": list1, "Student Name": list11})print('First data frame:')display(dataframe1)  # pass list2 and list22 to the# dataframe1dataframe2 = pd.DataFrame(  {"Student ID": list2, "Student Name": list22})print('Second data frame:')display(dataframe2)  # apply merge function to merge the# two dataframesmergedf = dataframe2.merge(dataframe1, how='left')print('Merged data frame:')display(mergedf)
Output:
Example 2:
Here is another program to merge one data frame of length 4 and another dataframe of length 9.
Python3
# importing pandas moduleimport pandas as pd  # create a list that contains# student id of subject 1list1 = [7058, 7059, 7075, 7076]  # create a list that contains# student id of subject 2list2 = [7058, 7059, 7012, 7075, 7076,         7034, 7046, 7036, 7015]  # create a list that contains# student names of subject 1list11 = ["Sravan", "Jyothika", "Deepika",          "Kyathi"]  # create a list that contains# student names of subject 2list22 = ["Sravan", "Jyothika", "salma",           "Deepika", "Kyathi", "meghana",          "pranathi", "bhanu", "keshav"]    # pass list1 and list11 to the# dataframe1dataframe1 = pd.DataFrame(  {"Student ID": list1, "Student Name": list11})print('First data frame:')display(dataframe1)  # pass list2 and list22 to the # dataframe1dataframe2 = pd.DataFrame(  {"Student ID": list2, "Student Name": list22})print('Second data frame:')display(dataframe2)  # apply merge function to merge# the two dataframesmergedf = dataframe2.merge(dataframe1, how='inner')print('Merged data frame:')display(mergedf)
Output:
Picked
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.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | Check if dictionary is empty - GeeksforGeeks

22 May, 2019
Sometimes, we need to check if a particular dictionary is empty or not. And this particular task has its application in web development domain in which we sometimes need to test for results of a particular query or check whether we have any key to add info into database. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using bool()
The bool function can be used to perform this particular task. As name suggests it performs the task of converting an object to a boolean value, but here, passing an empty string returns a False, as failure to convert something that is empty.
# Python3 code to demonstrate# Check if dictionary is empty# using bool()  # initializing empty dictionarytest_dict = {}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # using bool()# Check if dictionary is empty res = not bool(test_dict)  # print resultprint("Is dictionary empty ? : " + str(res))
The original dictionary : {}
Is dictionary empty ? : True

 
Method #2 : Using not operator
This task can also be performed using the not operator that checks for a dictionary existence, this evaluates to True, if any key in the dictionary is not found.
# Python3 code to demonstrate# Check if dictionary is empty# using not operator  # initializing empty dictionarytest_dict = {}  # printing original dictionaryprint("The original dictionary : " + str(test_dict))  # using not operator# Check if dictionary is empty res = not test_dict  # print resultprint("Is dictionary empty ? : " + str(res))
The original dictionary : {}
Is dictionary empty ? : True

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
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
Insert in MongoDB without duplicates

To insert records in MongoDB and avoid duplicates, use “unique:true”. Let us first create a collection with documents.
Here, we are trying to add duplicate records −
> db.insertWithoutDuplicateDemo.createIndex({"StudentFirstName":1},{ unique: true } );
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true });
WriteResult({ "nInserted" : 1 })
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"David"},{ upsert: true });
WriteResult({ "nInserted" : 1 })
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Chris"},{ upsert: true });
WriteResult({
   "nInserted" : 0,
   "writeError" : {
      "code" : 11000,
      "errmsg" : "E11000 duplicate key error collection: test.insertWithoutDuplicateDemo index:             StudentFirstName_1 dup key: { : \"Chris\" }"
   }
})
> db.insertWithoutDuplicateDemo.insert({"StudentFirstName":"Bob"},{ upsert: true });
WriteResult({ "nInserted" : 1 })
Following is the query to display all documents from a collection with the help of find() method −
> db.insertWithoutDuplicateDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5e064405150ee0e76c06a054"),
   "StudentFirstName" : "Chris"
}
{
   "_id" : ObjectId("5e064410150ee0e76c06a055"),
   "StudentFirstName" : "David"
}
{ "_id" : ObjectId("5e06441f150ee0e76c06a057"), "StudentFirstName" : "Bob" }
set_window_position driver method – Selenium Python

03 Dec, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. 
This article revolves around set_window_position driver method in Selenium. set_window_position method sets the x, y position of the current window (window.moveTo).
Syntax – 
driver.set_window_position(x, y, windowHandle='current')
Example – Now one can use set_window_position method as a driver method as below – 
driver.get("https://www.geeksforgeeks.org/")
driver.set_window_position(1024, 1024, windowHandle='current')
To demonstrate, set_window_position method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s set window position,
Program – 
Python3
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # set window positiondriver.set_window_position(1024, 1024, windowHandle ='current')
Output – Screenshot added –  
 
Akanksha_Rai
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Updating value list in dictionary

26 Jul, 2019
While working with dictionary with list as value is always vulnerable of getting it’s value updated. The ways or shorthands to perform this task can be handy in such situations. This can occur in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionThe naive method to perform this particular task, in this, we just extract the key and then iterate over it’s value in list comprehensive format in packed list. This solved the problem.
# Python3 code to demonstrate working of# Updating value list in dictionary# Using list comprehension  # Initialize dictionarytest_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using list comprehension# Updating value list in dictionarytest_dict['gfg'] = [x * 2 for x in test_dict['gfg']]      # printing result print("Dictionary after updation is : " + str(test_dict))
The original dictionary : {‘is’: 2, ‘gfg’: [1, 5, 6], ‘best’: 3}Dictionary after updation is : {‘is’: 2, ‘gfg’: [2, 10, 12], ‘best’: 3}
 
Method #2 : Using map() + lambdaThis task can be performed using the combination of above two functions in which we use the map() to link the function of updation to each of element of value list and lambda is used to specify the updation.
# Python3 code to demonstrate working of# Updating value list in dictionary# Using map() + lambda  # Initialize dictionarytest_dict = {'gfg' : [1, 5, 6], 'is' : 2, 'best' : 3}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using map() + lambda# Updating value list in dictionarytest_dict['gfg'] = list(map(lambda x:x * 2, test_dict['gfg']))      # printing result print("Dictionary after updation is : " + str(test_dict))
The original dictionary : {‘is’: 2, ‘gfg’: [1, 5, 6], ‘best’: 3}Dictionary after updation is : {‘is’: 2, ‘gfg’: [2, 10, 12], ‘best’: 3}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
How to delete a localStorage item when the browser window/tab is closed?

To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close.
Let's say you have a local storage object called MyStorage as a global
for the sake of this example. Then you can write an event handler −
window.onunload = () => {
   // Clear the local storage
   window.MyStorage.clear()
}
This will clear the local storage on the tab/window close.
Multiple axes in Matplotlib with different scales

In the following code, we will see how to create a shared Y-axis.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Plot line with lists passed in the argument of plot() method with color="red".
Plot line with lists passed in the argument of plot() method with color="red".
Create a twin of Axes with a shared X-axis but independent Y-axis.
Create a twin of Axes with a shared X-axis but independent Y-axis.
Plot the line on ax2 that is created in step 3.
Plot the line on ax2 that is created in step 3.
Adjust the padding between and around subplots.
Adjust the padding between and around subplots.
To show the figure use plt.show() method.
To show the figure use plt.show() method.
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot([1, 2, 3, 4, 5], [3, 5, 7, 1, 9], color='red')
ax2 = ax1.twinx()
ax2.plot([11, 12, 31, 41, 15], [13, 51, 17, 11, 76], color='blue')
fig.tight_layout()
plt.show()
Python time mktime() Method

Pythom time method mktime() is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple and it returns a floating point number, for compatibility with time().
If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised.
Following is the syntax for mktime() method −
time.mktime(t)

t − This is the struct_time or full 9-tuple.
t − This is the struct_time or full 9-tuple.
This method returns a floating point number, for compatibility with time().
The following example shows the usage of mktime() method.
#!/usr/bin/python
import time

t = (2009, 2, 17, 17, 3, 38, 1, 48, 0)
secs = time.mktime( t )
print "time.mktime(t) : %f" %  secs
print "asctime(localtime(secs)): %s" % time.asctime(time.localtime(secs))
When we run above program, it produces following result −
time.mktime(t) : 1234915418.000000
asctime(localtime(secs)): Tue Feb 17 17:03:38 2009


    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
JavaScript Date getYear() Method

Javascript date getYear() method returns the year in the specified date according to universal time. The getYear is no longer used and has been replaced by the getYear method.
The value returned by getYear is the current year minus 1900. JavaScript 1.2 and earlier versions return either a 2-digit or 4-digit year. For example, if the year is 2026, the value returned is 2026. So before testing this function, you need to be sure of the javascript version you are using.
Its syntax is as follows −
Date.getYear()

Returns the year in the specified date according to universal time.
Try the following example.
<html>
   <head>
      <title>JavaScript getYear Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var dt = new Date();
         document.write("getYear() : " + dt.getYear() ); 
      </script>      
   </body>
</html>
getYear() : 208


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Python program to reverse each word in a sentence?

Here we use python built in function. First we split the sentence into a list of word. Then reverse each word and creating a new list ,here we use python list comprehension technique and last joining the new list of words and create an new sentence.
Input :: PYTHON PROGRAM
Output :: NOHTYP MARGORP

Step 1 : input a sentence. And store this in a variable s.
Step 2 : Then splitting the sentence into a list of words.
   w=s.split(“”)
Step 3 : Reversing each word and creating a new list of words nw.
Step 4 : Joining the new list of words and make a new sentence ns.

#  Reverse each word of a Sentence
 # Function to Reverse words
def reverseword(s): 
   
   w = s.split(" ")        # Splitting the Sentence into list of words.
                           # reversing each word and creating a new list of words
                           # apply List Comprehension Technique
   nw = [i[::-1] for i in w]
                           # Join the new list of words to for a new Sentence
   ns = " ".join(nw)
   return ns
# Driver's Code 
s = input("ENTER A SENTENCE PROPERLY ::")
print(reverseword(s))
ENTER A SENTENCE PROPERLY :: PYTHON PROGRAM
NOHTYP MARGORP
Creating a Transparent window in Python Tkinter

Python is the most popular language for developing and creating functional and
desktop applications. It has a rich library of different modules and functions which
provides extensibility and accessibility to create and develop applications.
Tkinter is the most commonly used library for creating GUI-based applications. It
has features like adding widgets and other necessary attributes.
Let us suppose that we want to create a transparent window using tkinter. To create the transparent window, we can use the attributes property and define the opacity value.
#Importing the tkinter library
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Define the size of the window or frame
win.geometry("700x400")

#To Make it transparent use alpha property to define the opacity of
the frame
win.attributes('-alpha', 0.3)
win.mainloop()
Running the above code will generate the output and will show a transparent
window.
factorial() in Python

Finding the factorial of a number is a frequent requirement in data analysis and other mathematical analysis involving python. The factorial is always found for a positive integer by multiplying all the integers starting from 1 till the given number. There can be three approaches to find this as shown below.
We can use a for loop to iterate through number 1 till the designated number and keep multiplying at each step. In the below program we ask the user to enter the number and convert the input to an integer before using it in the loop. This way we ensure we get positive integers in the calculation.
 Live Demo
n = input("Enter a number: ")
factorial = 1
if int(n) >= 1:
for i in range (1,int(n)+1):
   factorial = factorial * i
print("Factorail of ",n , " is : ",factorial)
Running the above code gives us the following result −
Enter a number: 5
Factorail of 5 is : 120
 Live Demo
num = input("Enter a number: ")
def recur_factorial(n):
if n == 1:
   return n
elif n < 1:
   return ("NA")
else:
   return n*recur_factorial(n-1)
print (recur_factorial(int(num)))
Running the above code gives us the following result −
#Run1:
Enter a number: 5
120
#Run2:
Enter a number: -2
NA
In this case we can directly use factorial function which is available in math module. We need not write the code for factorial functionality rather directly use the math.factorial(). That also takes care of negative numbers and fractional numbers scenario.
 Live Demo
import math
num = input("Enter a number: ")
print("The factorial of ", num, " is : ")
print(math.factorial(int(num)))
Running the above code gives us the following result −
#Run1:
Enter a number: 5
The factorial of 5 is :
120
#Run 2:
Enter a number: 3.6
Traceback (most recent call last):
The factorial of 3.6 is :
File "C:/Users....py", line 5, in
print(math.factorial(int(num)))
ValueError: invalid literal for int() with base 10: '3.6'
How to return an array from a function in C++?

C++ does not return entire array but it can return pointer to an array. Outside the function, address of local variable cannot be returned. By making local variable static, it can return the address of local variable.
The following is the syntax to return a pointer.
int * function_name()
{ body }
Here,
function_name − The name of function given by user.
The following is an example to return an array from a function.
 Live Demo
#include <iostream>
using namespace std;
int * ret() {
   static int x[3];
   for(int i=0 ; i<5 ; i++) {
      cout << " " <<&x[i];
   }
   return x;
}
int main() {
   ret();
   return 0;
}
0x601180 0x601184 0x601188 0x60118c 0x601190
In the above program, a function ret() is created and it is returning an array. A static int type array is declared and addresses of allocated memory blocks are printed.
int * ret() {
   static int x[3];
   for(int i=0 ; i<5 ; i++) {
      cout << " " <<&x[i];
   }
   return x;
}
In the main() function, the function ret() is called −
ret();
HTML canvas fill() Method

The fill() method in HTML canvas is used to fill the current drawing path. The default is black. The <canvas> element allows you to draw graphics on a web page using JavaScript. Every canvas has two elements that describes the height and width of the canvas i.e. height and width respectively.
Following is the syntax−
ctx.fill();
Let us now see an example to implement the fill() method of canvas −
 Live Demo
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="450" height="250" style="border:2px solid blue;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
   var c = document.getElementById("myCanvas");
   var ctx = c.getContext("2d");
   ctx.beginPath();
   ctx.rect(50, 60, 300, 200);
   ctx.fillStyle = "green";
   ctx.fill();
</script>
</body>
</html>
Lodash _.renameKeys() Method - GeeksforGeeks

30 Sep, 2020
The Lodash _.renameKeys() method takes an object and a mapping object and returns a new object where the keys of the given object have been renamed as the corresponding value in the keyMap.
Syntax:
_.renameKeys(obj, mapObj);
Parameters: This method accept two parameters as mentioned above and described below:
obj: Given object to create a new object.
mapObj: Given map object to create a new object.
Return Value: This method returns a generated object.
Note: This will not work in normal JavaScript because it requires the lodash.js contrib library to be installed. Lodash.js contrib library can be installed using the following command:
npm install lodash-contrib
Example 1:
// Defining underscore lodash variable var _ = require('lodash-contrib');   // Declare and object and rename its keyvar obj = _.renameKeys( { 1 : "Geeks",              2 : "Computer_Science_Portal" },             { 1 : "g", 2 : "c" });     console.log("Generated Object: ", obj);
Output:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
Example 2:
// Defining underscore lodash variable var _ = require('lodash-contrib');   // Declare and object and rename its keyvar obj = _.renameKeys(      { 1 : "Geeks", 2 : "Computer_Science_Portal",      3 : "Geeks" }, { 1 : "g", 2 : "c", 3 : "g" });  console.log("Generated Object: ", obj);
Output:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
Example 3:
// Defining underscore lodash variable var _ = require('lodash-contrib');   // Declare and object and rename its keyvar obj = _.renameKeys( [ "Computer_Science_Portal", "Geeks" ],                         { 0 : "a", 1 : "b", 3 : "g" });   console.log("Generated Object: ", obj);
Output:
Generated Object: Object {c: "Computer_Science_Portal", g: "Geeks"}
JavaScript-Lodash
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 get character array from string in JavaScript?
Remove elements from a JavaScript Array
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
\color - Tex Command

\color - Used to specify color for mathematics.
{ \color #1 #2 }
\color command is used to specify color for mathematics.

\color{red}{ \frac{1+\sqrt{5}}{2} }

1+52


\color{#0000FF}AB

AB



\color{red}{ \frac{1+\sqrt{5}}{2} }

1+52


\color{red}{ \frac{1+\sqrt{5}}{2} }
\color{#0000FF}AB

AB


\color{#0000FF}AB

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Decision Coverage Testing

Decision coverage or Branch coverage is a testing method, which aims to ensure that each one of the possible branch from each decision point is executed at least once and thereby ensuring that all reachable code is executed.
That is, every decision is taken each way, true and false. It helps in validating all the branches in the code making sure that no branch leads to abnormal behavior of the application. 
Read A
Read B 
IF A+B > 10 THEN 
  Print "A+B is Large" 
ENDIF 
If A > 5 THEN 
  Print "A Large"
ENDIF
The above logic can be represented by a flowchart as:
To calculate Branch  Coverage, one has to find out the minimum number of paths which will ensure that all the edges are covered. In this case there is no single path which will ensure coverage of  all the edges at once. The aim is to cover all possible true/false decisions.
(1) 1A-2C-3D-E-4G-5H
(2) 1A-2B-E-4F
Hence Decision or Branch Coverage is 2.

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
Array Nesting in C++

Suppose we have a zero-indexed array A of length N that contains all integers from 0 to N-1. We have to find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Now consider the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]... By that analogy, we stop adding right before a duplicate element occurs in S. So if the array is like A = [5,4,0,3,1,6,2], then the output will be 4, as A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, and finally A[6] = 2.
To solve this, we will follow these steps −
So create a function called dfs. This will take node, arr array, v array, and a set visited. Do the following in dfs array −
if node is visited, then return
insert node into v, mark node as visited
dfs(arr[node], arr, v, visited)
From the main method, do the following −
ret := 0, n := size of nums. make a set called visited
for i in range 0 to n – 1create an array vif nums[i] is not visited, then dfs(nums[i], nums, v, visited)ret := max of ret and size of v
create an array v
if nums[i] is not visited, then dfs(nums[i], nums, v, visited)
ret := max of ret and size of v
return ret
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   void dfs(int node, vector <int>& arr, vector <int>& v, set <int>& visited){
      if(visited.count(node)) return;
      v.push_back(node);
      visited.insert(node);
      dfs(arr[node], arr, v, visited);
   }
   int arrayNesting(vector<int>& nums) {
      int ret = 0;
      int n = nums.size();
      set <int> visited;
      for(int i = 0; i < n; i++){
         vector <int> v;
         if(!visited.count(nums[i]))dfs(nums[i], nums, v, visited);
         ret = max(ret, (int)v.size());
      }
      return ret;
   }
};
main(){
   vector<int> v = {5,4,0,3,1,6,2};
   Solution ob;
   cout << (ob.arrayNesting(v));
}
[5,4,0,3,1,6,2]
4
JSTL - XML <x:forEach> Tag

The <x:forEach> tag is used to loop over nodes in an XML document.
The <x:forEach> tag has the following attributes −
The following example shows the use of the <x:forEach> tag −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>

<html>
   <head>
      <title>JSTL x:if Tags</title>
   </head>

   <body>
      <h3>Books Info:</h3>

      <c:set var = "xmltext">
         <books>
            <book>
               <name>Padam History</name>
               <author>ZARA</author>
               <price>100</price>
            </book>
            
            <book>
               <name>Great Mistry</name>
               <author>NUHA</author>
               <price>2000</price>
            </book>
         </books>
      </c:set>

      <x:parse xml = "${xmltext}" var = "output"/>
      
      <ul class = "list">
         <x:forEach select = "$output/books/book/name" var = "item">
            <li>Book Name: <x:out select = "$item" /></li>
         </x:forEach>
      </ul>

   </body>
</html>
You will receive the following result −
Books Info:

Book Name: Padam History
Book Name: Great Mistry


Book Name: Padam History
Book Name: Padam History
Book Name: Great Mistry
Book Name: Great Mistry

    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page