code-rag-bench/online-tutorials huggingface dataset:
React.js useImperativeHandle Additional Hook - GeeksforGeeks

17 Mar, 2021
The useImperativeHandle hook works in the similar phase of useRef hook but only it allows us to modify the instance that is going to be passed with the ref object which provides a reference to any DOM element. Although this hook is used in rare cases, it has some most advanced functionality.
Syntax:
useImperativeHandle(ref, createHandle, [deps])
Creating React Application:
Step 1: Create a React application using the following command.npx create-react-app functiondemo
Step 1: Create a React application using the following command.
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command.cd functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command.
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a custom input button which on being in focus performs the custom user-defined. It is our custom input field which we will import in App.js file.
Input.js
import React, { useRef, useImperativeHandle, forwardRef } from 'react';  function Input(props, ref) {  const btn = useRef();  useImperativeHandle(ref, () => ({    focus: () => {      console.log('Input is in focus');    },  }));  return <input ref={btn} {...props} placeholder="type here" />;}  export default forwardRef(Input);
App.js
import React, { useRef } from 'react';import Input from './Input';  const App = () => {  const inputRef = useRef(null);  return (    <div>      <Input onFocus={() => inputRef.current.focus()}       ref={inputRef} />    </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:
Reference:https://reactjs.org/docs/hooks-reference.html#useimperativehandle
React-Hooks
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to set background images in ReactJS ?
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
How to create a multi-page website using React.js ?
ReactJS useNavigate() Hook
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python Program to Replace Specific Line in File - GeeksforGeeks

14 Sep, 2021
In this article, we are going to write a Python program to replace specific lines in the file.
We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after that, we open the file in write-only mode and write the modified data using writelines().
File for demonstration:
First, open the File in read-only mode and read the file line by line using readlines() method, and store it in a variable.
with open('example.txt','r',encoding='utf-8') as file:
    data = file.readlines()
The variable will contain a list of lines, Printing it will show all the lines present inside the list.
print(data)
Make necessary changes to a specific line. (Here, I have modified the second line)
data[1] = "Here is my modified Line 2\n"
Open the file again in write-only mode and write the modified data using writelines() method.
With open('example.txt', 'w', encoding='utf-8') as file:
    file.writelines(data)
Python3
with open('example.txt', 'r', encoding='utf-8') as file:    data = file.readlines()  print(data)data[1] = "Here is my modified Line 2\n"  with open('example.txt', 'w', encoding='utf-8') as file:    file.writelines(data)
Output:
['Line 1\n', 'Here is my modified Line 2\n', 'Line 3']
After Modification:
Blogathon-2021
Picked
Python file-handling-programs
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Import JSON Data into SQL Server?
How to Install Tkinter in Windows?
SQL - Multiple Column Ordering
How to pass data into table from a form using React Components
How to Create a Table With Multiple Foreign Keys in SQL?
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 install and import Python modules at runtime?

You can use pip to install packages at runtime and importlib.import_module(moduleName) to import module by using its name as a string. For example,
import pip
import importlib
def import_with_auto_install(package):
    try:
        return importlib.import_module(package)
    except ImportError:
        pip.main(['install', package])
    return importlib.import_module(package)
# Example
if __name__ == '__main__':
    scrapy = import_with_auto_install('scrapy')
    print(scrapy)
The above script installs the scrapy module and imports it when installation of the module completes.
Finding the elements of nth row of Pascal's triangle in JavaScript

Pascal's triangle is a triangular array constructed by summing adjacent elements in preceding
rows.
The first few elements of Pascals triangle are −
We are required to write a JavaScript function that takes in a positive number, say num as the
only argument.
The function should return an array of all the elements that must be present in the pascal's
triangle in the (num)th row.
For example −
If the input number is −
const num = 9;
Then the output should be −
const output = [1, 9, 36, 84, 126, 126, 84, 36, 9, 1];
Following is the code −
const num = 9;
const pascalRow = (num) => {
   const res = []
   while (res.length <= num) {
      res.unshift(1);
      for(let i = 1; i < res.length - 1; i++) {
         res[i] += res[i + 1];
      };
   };
   return res
};
console.log(pascalRow(num));
Following is the console output −
[
   1, 9, 36, 84, 126,
   126, 84, 36, 9, 1
]
Python Pillow - Cropping an Image

Cropping is one of the important operations of the image processing to remove unwanted portions of an image as well as to add required features to an image. It is widely used process in web applications, for uploading an image.
The crop() function of the image class in Pillow requires the portion to be cropped as rectangle. The rectangle portion to be cropped from an image is specified as a four-element tuple and returns the rectangle portion of the image that has been cropped as an image Object.
Following example demonstrates how to rotate an image using python pillow −
#Import required Image library
from PIL import Image

#Create an Image Object from an Image
im = Image.open('images/elephant.jpg')

#Display actual image
im.show()

#left, upper, right, lowe
#Crop
cropped = im.crop((1,2,300,300))

#Display the cropped portion
cropped.show()

#Save the cropped image
cropped.save('images/croppedBeach1.jpg')
If you save the above program as Example.py and execute, it displays the original and cropped images using standard PNG display utility, as follows −
Original image


Cropped image



    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
What is the difference between ++i and i++ in C++?

There is a big distinction between the suffix and prefix versions of ++.
In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression.
In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i. So basically it first assigns a value to expression and then increments the variable.                                     
Let's look at some code to get a better understanding −
#include<iostream>
using namespace std;
int main() {
   int x = 3, y, z;
   y = x++;
   z = ++x;
   cout << x << ", " << y << ", " << z;
   return 0;
}
This would give us the output −
5, 3, 5
Why is this? Let's look at it in detail −
 Initialize x to 3
 Assign y the value we get by evaluating the expression x++, ie, the value of x before increment then increment x.
 Increment x then assign z the value we get by evaluating the expression ++x, ie, value of x after the increment.
 Print these values
Creating First REST API with FastAPI - GeeksforGeeks

05 Sep, 2020
FastAPI :FastAPI is modern Web Framework . It is used for building API and is very easy to learn .
Features of FastAPI :
High Performance than many Web Frameworks, faster than Node.js, etc .
Easy to Develop API’s
Production Ready
Well Documentation to learn code fast
Swagger UI to form API Documentation
Avoid Redundancy of Code
Easy Testing
Support for GraphQL, Background Fetching, Dependency Injection
CREATING REST API USING FastAPI :
Install Python 3 and pip/pip3 according to your Operating System
Now, install fastapi using pip or pip3 :   pip install fastapi

   pip install fastapi

Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :  pip install uvicorn

  pip install uvicorn

Now create a main.py file and import fastapi, also create a server  from fastapi import FastAPI
  app = FastAPI()

  from fastapi import FastAPI
  app = FastAPI()

Now, let’s add the code for sample get request as shown below : @app.get("/")
 def read_root():
    return {"Hello": "World"}

 @app.get("/")
 def read_root():
    return {"Hello": "World"}

Hence, the main.py file will look like :from fastapi import FastAPIapp = FastAPI() @app.get("/")def first_example():    """       GFG Example First Fast API Example     """   return {"GFG Example": "FastAPI"}
from fastapi import FastAPIapp = FastAPI() @app.get("/")def first_example():    """       GFG Example First Fast API Example     """   return {"GFG Example": "FastAPI"}
Now, start the server usinguvicorn main:app --reload

uvicorn main:app --reload

Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docsYou will be able to see the Swagger UI Home page as below :
Expand the “First Example” :
Now try to Execute the API, you will get the success status with 200 code .The Response will be {“GFG Example”: “FastAPI”} as shown below :
Programming Language
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of Object Oriented Programming
5 Best Languages for Competitive Programming
R - Matrices
7 Highest Paying Programming Languages For Freelancers in 2022
R - Data Types
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Get the Day of the Week from Today's Date in Java

To get the day of the week, use the Calendar.DAY_OF_WEEK.
Firstly, let us get the current date.
java.util.Date utilDate = new java.util.Date();
java.sql.Date dt = new java.sql.Date(utilDate.getTime());
Now, using GregorianCalendar, set the time.
java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
cal.setTime(dt);
The last step would display the day of the week as shown in the following example.
 Live Demo
import java.text.ParseException;
public class Demo {
   public static void main(String[] args) throws ParseException {
      java.util.Date utilDate = new java.util.Date();
      java.sql.Date dt = new java.sql.Date(utilDate.getTime());
      System.out.println("Today's date: "+dt);
      java.util.GregorianCalendar cal = new java.util.GregorianCalendar();
      cal.setTime(dt);
      // Getting the day of the week
      System.out.println("Day of the week: "+cal.get(java.util.Calendar.DAY_OF_WEEK));
   }
}
Today's date: 2018-11-19
Day of the week: 2
Can we declare an interface as final in java?

Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.
Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it.
If you declare a class final cannot extend it. If you make a method final you cannot override it and, if you make a variable final you cannot modify it. i.e. use final with Java entities you cannot modify them further.
If you make an interface final, you cannot implement its methods which defies the very purpose of the interfaces. Therefore, you cannot make an interface final in Java. Still if you try to do so, a compile time exception is generated saying “illegal combination of modifiers − interface and final”.
In the following example we are defining an interface with name MyInterface and using the final modifier with it.
public final interface MyInterface{
   public static final int num = 10;
   public abstract void demo();
}
On compiling, the above program generates the following error
MyInterface.java:1: error: illegal combination of modifiers: interface and final
   public final interface MyInterface{
^
1 error
Hash Table Data Structure in Javascript

Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access to data becomes very fast if we know the index of the desired data.
Thus, it becomes a data structure in which insertion and search operations are very fast irrespective of the size of the data. Hash Table uses an array as a storage medium and uses the hash technique to generate an index where an element is to be inserted or is to be located from.
Hashing is a technique to convert a range of key values into a range of indexes of an array. We're going to use modulo operator to get a range of key values. Consider an example of a hash table of size 20, and the following items are to be stored. Item is in the (key, value) format.
Here we have a hash function that takes in keys and generates indices for a table. These indices let us know where the value is stored. Now whenever we want to search for a value associated with a key, we just need to run the hash function on the key again and get the value in nearly constant time.
Hash functions are pretty hard to design though. Let's take an example −
Let's say we have the following hash function − 
function modBy11(key) {
   return key % 11;
}
And we start running this on key-value pairs we want to store, for example −
(15, 20) - Hash code: 4
(25, 39) - Hash code: 3
(8, 55) - Hash code: 8
(26, 84) - Hash code: 4
Here we see that we have a collision, ie, if we were to store 15 first and then encounter the key 26 with this hash function, it'll try to fix this entry in the same hole. This is called a collision. And to handle such situations, we need to define a collision handling mechanism. There are some well defined simple collision resolution algorithms. For example −
Linear Probing: In this algorithm, we can search the next empty location in the array by looking into the next cell until we find an empty cell. In our example, since hole at 4 is taken, we can fill it in 5.
Separate Chaining: In this implementation: We associate each location in the hash table with a list. Whenever we get a collision, we append the key-value pair at the end of this list. This can lead to much longer search times if chains keep getting longer.
Now that we understand how a hash table works and how we can use collision resolution, let's implement the HashTable class.
We'll implement these methods in our implementation −
put(key, value): Adds a new key-value pair to the hash table
get(key): Gets the value associated with a key
remove(key): Removes the key-value pair from the table
forEach(): Allows iterating over all key-value pairs
static join(): A static method to join 2 hash tables in a new one
Python | Pandas dataframe.median()

24 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.median() function return the median of the values for the requested axisIf the method is applied on a pandas series object, then the method returns a scalar value which is the median value of all the observations in the dataframe. If the method is applied on a pandas dataframe object, then the method returns a pandas series object which contains the median of the values over the specified axis.
Syntax:DataFrame.median(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)Parameters :axis : Align object with threshold along the given axis.skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : median : Series or DataFrame (if level specified)
Example #1: Use median() function to find the median of all the observations over the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1],                   "B":[5, 2, 54, 3, 2],                   "C":[20, 16, 7, 3, 8],                    "D":[14, 3, 17, 2, 6]})  # Print the dataframedf
Lets use the dataframe.median() function to find the median over the index axis
# Find median Even if we do not specify axis = 0, the method # will return the median over the index axis by defaultdf.median(axis = 0)
Output :
 Example #2: Use median() function on a dataframe which has Na values. Also find the median over the column axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1],                   "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})  # Print the dataframedf
Lets implement the median function.
# skip the Na values while finding the mediandf.median(axis = 1, skipna = True)
Output :
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.
Rounding off values in R Language – round() Function

15 Apr, 2021
round() function in R Language is used to round off values to a specific number of decimal value. 
Syntax: round(x, digits)Parameters: x: Value to be round off digits: Number of digits to which value has to be round off
Example 1: Rounding off the values  
Python3
# R program to illustrate# round function # Create example valuesx1 <- 1.2                          x2 <- 1.8x3 <- - 1.3x4 <- 1.7 # Apply round functionround(x1)                          round(x2)round(x3)round(x4) print(x1, x2, x3, x4)
Output :  
 1
 2
-1
 2
Here in the above code, we have round off the values with 4 data x1, x2, x3, and x4 using the function round(), and printed the new values.Example 2: Rounding off to certain digits  
Python3
# R program to illustrate# round to a certain digit # Create numeric with many digitsx2 <- 3.14734343243   # Round to three decimal places                 round(x2, digits = 3)  print(x2)            
Output:
 3.147 
Here in the above code, the value of a numeric vector is round off till 3 digits. 
arorakashish0911
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Tweepy – Getting the name of a user

18 Jun, 2020
In this article we will see how we can get the name of a user. Name is the display name of the twitter account. It is the name that users choose to identify themselves on the network. Many users choose to either use their real name as the basis for their display name. Unlike screen names, the names need not be unique. Moreover the names can be in any language script, the screen name can only be in English(Latin). Names can also have spaces and special characters in them.
Identifying the name in the GUI :
In the above mentioned profile, GeeksforGeeks is the name of the profile.
In order to get the name we have to do the following :
Identify the user ID or screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the name attribute present in it.
Identify the user ID or screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the name attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the userid = 57741058  # fetching the useruser = api.get_user(id)  # fetching the namename = user.name  print("The name of the user is : " + name)
Output :
The name of the user is : GeeksforGeeks

Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG.
# the screen name of the userscreen_name = "PracticeGfG"  # fetching the useruser = api.get_user(screen_name)  # fetching the namename = user.name  print("The name of the user is : " + name)
Output :
The name of the user is : Practice GfG

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Goldeneye DDos Tool in Kali Linux

24 Jun, 2021
Goldeneye is a free and Open source tool available on GitHub. We can perform a denial of service attack using this tool. It’s a framework written in .NET Core. This tool provides many base classes and extensions to use with your daily work. This tool allows a single machine to take down another machine’s web server it uses perfectly legitimate HTTP traffic. It makes a full TCP connection and then requires only a few hundred requests at long-term and regular intervals. As a result, the tool doesn’t need to use a lot of traffic to exhaust the available connections on a server. 
Goldeneye uses perfectly legitimate HTTP traffic.
Deniel of service attack can be executed with the help of Goldeneye by generating heavy traffic of botnets.
Goldeneye sends multiple requests to the target as a result generates heavy traffic botnets.
Goldeneye is an open-source tool, so you can download it from GitHub free of cost.
Goldeneye can be used to perform ddos attacks on any webserver.
Step 1: Open your Kali Linux and then Open your Terminal. Use the following command to install the tool.
git clone https://github.com/jseidl/GoldenEye.git
Step 2: Use the following command to move to Goldeneye directory.
cd GoldenEye
Step 3: Use the following command to list out the contents of the directory.
ls
Step 4: The tool is running successfully now.
Example 1: Use the GoldenEye tool to perform DDoS attack on any domain.
./goldeneye.py https://www.google.com -s 1000
The tool is running successfully and started attacking the domain www.google.com. This tool is useful for security researchers.
Example 2: To display all usage options of the golden eye tool, type the following command
sudo ./goldeneye.py -h
Example 3: To send traffic in ‘random’ mode with 5 workers running 10 connections each
sudo ./goldeneye.py  http://192.168.0.233:80/ -s 10 -m random
Example 4: Use the GoldenEye tool to send traffic to the target machine and capture traffic on Wireshark tool.
Wireshark
The tool will start hitting the server. Now open Wireshark and capture packets.
The tool is running successfully and started attacking the domain and the Wireshark is capturing the packets. 
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the new image URL after refreshing the image using JavaScript ?

13 Jun, 2022
The browser cache relies on the image URL to decide whether the image is the same or not and whether to use the stored version. It means if we change something within the URL and then attempt to reload the image, the cache will no longer be able to change that it is the same resource. The cache will fetch it again from the server.
Approach: To change the URL without affecting the image, you can change the parameter that can be attached to the end of the URL. The parameter needs to be unique. We can use a timestamp, the URL will always be unique.
To refresh the image in JavaScript, we can simply select the img element and modify its src attribute to be that of the target image, along with the timestamp parameter to ensure it does not access it from the cache.
Example:
HTML
<!DOCTYPE html><html> <head>    <title>Refresh Image</title></head> <body>    <!-- Display the image -->    <img id="gfgimage" src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png"         width="500" />     <script>        // Create a timestamp        var timestamp = new Date().getTime();         // Get the image element        var image = document.getElementById("gfgimage");         // Adding the timestamp parameter to image src        image.src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-20.png?t=" + timestamp;        console.log(image.src);    </script>   </body> </html>
Output:
 
Now, even if the image is replaced with a new image it will load the new image. In general, this may have some performance issues as it won’t be using the image from the cache and will have to use the image from the server always.
HTML is the foundation of web pages and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
sanjyotpanure
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – Create translucent Push Button

22 Apr, 2020
In this article we will see how to create translucent button, here translucent refer as button which are not completely opaque.
In order to do this, we have to change the alpha level of push button, alpha level is the opaque factor greater the value of alpha more the object is opaque, but unlike main window we can’t use setWindowOpacity method, therefore in order to change the alpha value we will use setStyleSheet method.
Below is the difference between normal button and translucent button.
 
Syntax : button.setStyleSheet(“color : rgba(0, 0, 0, 100)”)
Argument : It takes string as argument. Here Rgba refer to red, green, blue and alpha level, they all vary from 0 to 255.
Action performed : It will set the alpha level of push button
Code :
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a push button        button = QPushButton("CLICK", self)          # setting geometry of button        button.setGeometry(200, 150, 100, 40)          # setting alpha level        button.setStyleSheet("color : rgba(0, 0, 0, 100)")          # adding action to a button        button.clicked.connect(self.clickme)      # action method    def clickme(self):            # printing pressed        print("pressed")  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chained Exceptions in C#

Chained Exceptions are a chain of try-catch statements that handle exceptions. To create a chain of exceptions i.e. chained exceptions −
Set the first try-catch −
static void Main(string[] args) {
   try {
      One();
   } catch (Exception e) {
      Console.WriteLine(e);
   }
}
Now try-catch under method One() −
static void One() {
   try {
      Two();
   } catch (Exception e) {
      throw new Exception("First exception!", e);
   }
}
The method Two() also continues chained exception.
static void Two() {
   try {
      Three();
   } catch (Exception e) {
      throw new Exception("Second Exception!", e);
   }
}
Now the next method.
static void Three() {
   try {
      Last();
   } catch (Exception e) {
      throw new Exception("Third Exception!", e);
   }
}
The takes us to the last.
static void Last() {
   throw new Exception("Last exception!");
}
On running the above, the exceptions would be handled like this −
System.Exception: First exception! ---< System.Exception: Middle Exception! ---< System.Exception: Last exception!
at Demo.Two () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
--- End of inner exception stack trace ---
at Demo.Two () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0
at Demo.One () [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
--- End of inner exception stack trace ---
at Demo.One () [0x00016] in <199744cb72714131b4f5995ddd1a021f>:0
at Demo.Main (System.String[] args) [0x00000] in <199744cb72714131b4f5995ddd1a021f>:0
Split a string in equal parts (grouper in Python) - GeeksforGeeks

16 Jun, 2020
Grouper recipe is an extended toolset made using an existing itertool as building blocks. It collects data into fixed-length chunks or blocks.
Existing Itertools Used:izip_longest(*iterables[, fillvalue]) : Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted.
Performance:
The extended tools offer the same high performance as the underlying toolset.
The superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once.
Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables.
High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generators which incur interpreter overhead.
Examples:
Input : str = ABCDEFG, l = 3
Output : ABC DEF Gxx
Explanation: 
Grouping characters of string in set of 3: ABC DEF Gxx.
'x' is added to the set which doesn't have 3 elements in it. 

Input : str = GEEKSFORGEEKS, l = 5
Output : GEEKS FORGE EKSxx
 Below is the Python3 code :
# Python3 code for the grouper recipe  # import the existing itertool izip_longestfrom itertools import izip_longest  # function for the grouper recipedef grouper(iterable, n, fillvalue ='x'):          # create 'n'-blocks for collection    args = [iter(iterable)] * n          # collect data into fixed length blocks of    # length 'n' using izip_longest and store    # result as a list    ans = list(izip_longest(fillvalue = fillvalue, *args))          # (optional) loop to convert ans to string    t = len(ans)    for i in range(t):        ans[i] = "".join(ans[i])          # return ans as string        return " ".join(ans)        # Driver codes = "ABCDEFG"k = 3  result = grouper(s, k)print(result)    
Output:
ABC DEF Gxx
adisakshya
Akanksha_Rai
python-string
Technical Scripter 2018
Python
Technical Scripter
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
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
Getting a syntax error unknown fields in SAP ABAP

You need to add spaces after or before braces as follows −
SELECT  *
FROM CNTRB
WHERE AGE > 30
AND   CNTRB > 10000
AND NOT ( FUND1 = 'value' AND FUND2 = '0' )
Style input type submit with CSS

The input type button can be a submit button or reset button. With CSS, we can style any button on a web page.
You can try to run the following code to style input type submit:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         input[type = submit] {
            background-color: orange;
            border: none;
            text-decoration: none;
            color: white;
            padding: 20px 20px;
            margin: 20px 20px;
            cursor: pointer;
         }
      </style>
   </head>
   <body>
      <p>Fill the below form,</p>
      <form>
         <label for = "subject">Subject</label>
         <input type = "text" id="subject" name  ="sub"><br><br>
         <label for = "student">Student</label>
         <input type = "text" id = "student" name = "stu"><br>
         <input type = "submit" value = "Submit">
      </form>
   </body>
</html>
How to hide status bar in Android using Kotlin?

This example demonstrates how to hide status bar in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Hello World!"
      android:textColor="@android:color/holo_blue_dark"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Window
import android.view.WindowManager
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
      WindowManager.LayoutParams.FLAG_FULLSCREEN)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Moore - Penrose Pseudoinverse | Mathematics - GeeksforGeeks

03 Oct, 2019
In linear algebra pseudoinverse () of a matrix A is a generalization of the inverse matrix. The most common use of pseudoinverse is to compute the best fit solution to a system of linear equations which lacks a unique solution. Moore – Penrose inverse is the most widely known type of matrix pseudoinverse. The term generalized inverse is sometimes used as a synonym of pseudoinverse.
Let the system is given as:
We know A and , and we want to find .Where: and  are vectors,A is a matrix
If A is a square matrix, we proceed as below:
But if A is not a square matrix, we cannot compute the usual . Nevertheless, we can form the pseudoinverse.
If we go in detail at the system i.e. , then it represents the following set of equations:
. .. .. .
which can also be written in matrix form as below:
Where m > n which means the number of rows is greater than the number of columns or the number of rows is greater than the number of variables.
Solution to the above problem:There are multiple ways to solve the above problem. One solution involves Moore – Penrose Pseudoinverse. We write the Moore – Penrose pseudoinverse as .We have  but  unless A has the usual inverse.So, to solve the problem we proceed as follow:
This is how simply we solve the linear equations using the Moore – Penrose pseudoinverse. The derivation for Moore – Penrose pseudoinverse is beyond the scope of this article. You can go through this link in case you want to know more about it. Here, it is simply presented the method for computing it. The Moore – Penrose pseudoinverse is computed as
Example:
Consider below 3 linear equations:






Equivalently we can write above equations in matrix form as shown below:





After we compute the Moore - Penrose pseudoinverse using , we will get:



Check the matrix product  you will get identity matrix I.


We have,


Then,





After you compute above computation, you will get the final answer as


Note: Moore – Penrose pseudoinverse solves the problem in least squared error sense. In general, there is no exact solution to overdetermined problems. So if you cross check the solution you will not get the exact required y but an approx value of y.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Support Vector Machine Algorithm
k-nearest neighbor algorithm in Python
Singular Value Decomposition (SVD)
Intuition of Adam Optimizer
ML | Logistic Regression using Python
CNN | Introduction to Pooling Layer
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
DBSCAN Clustering in ML | Density based clustering
Normalization vs Standardization
Python String min() Method

Python string  method min() returns the min alphabetical character from the string str.
Following is the syntax for min() method −
min(str)

str − This is the string from which min alphabetical character needs to be returned.
str − This is the string from which min alphabetical character needs to be returned.
This method returns the min alphabetical character from the string str.
The following example shows the usage of min() method.
#!/usr/bin/python

str = "this-is-real-string-example....wow!!!";
print "Min character: " + min(str)

str = "this-is-a-string-example....wow!!!";
print "Min character: " + min(str)
When we run above program, it produces following result −
Min character: !
Min character: !


    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
Print Bracket Number in C++

In this problem, we are given expression. And we have to print the bracket number sequence. Let’s look at an example to understand the problem better.
Example,
Input : ((()())())
Output : 1233442551
Explanation − Here we have encountered 5 bracket pairs and we have printed them in a sequence of their[ occurrence.
Now since we know about the problem, let’s create a solution to this solution.
The solution to this problem requires a stack data structure. We will use one variable that keeps the count of the number of left brackets and stack keeps track of right brackets. We will count left brackets and push them into the stack and pop when the right bracket is encountered.
Step 1 : Initialise leftBrackets = 1. stack rightBrackets, empty.
Step 2 : traverse the expression using variable i = 0 to n-1.
Step 3 : if expression[i] == ‘(’ i.e. left bracket is encountered. Then,
   Step 3.1 : PRINT ‘leftBracket ‘.
   Step 3.2 : push the value of leftBracket in stack.
   Step 3.3 : leftBracket++.
Step 4 : if expression[i] == ‘)’ i.e. right bracket is encountered. Then,
   Step 4.1 : PRINT top of stack.
   Step 4.2 : pop top element of the stack.
Step 5 : EXIT.
Now let’s create programming to illustrate the implementation of the above algorithm.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void bracketCount(string expression, int n){
   int leftBracket = 1;
   stack<int> rightBracket;
   for (int i = 0; i < n; i++) {
      if (expression[i] == '(') {
         cout<<leftBracket<<" ";
         rightBracket.push(leftBracket);
         leftBracket++;
      }
      else if(expression[i] == ')') {
         cout<<rightBracket.top() << " ";
         rightBracket.pop();
      }
   }
}
int main(){
   string expression = "()((())()())";
   int n = expression.size();
   bracketCount(expression, n);
   return 0;
}
1 1 2 3 4 4 3 5 5 6 6 2
How to convert File into a Stream in Java?

Let’s say we have a file “input.txt” here in the directory E:/ with the following content:
Open a file with Bufferedreader. We have taken the above file here which is located at E: directory;
BufferedReader buffReader = Files.newBufferedReader(Paths.get("E:\\input.txt"),StandardCharsets.UTF_8);
Now get the stream of lines from the above file and display:
buffReader.lines().forEach(System.out::println);
The following is an example to convert File into a Stream in Java:
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Demo {
   public static void main(String[] argv) throws Exception {
      BufferedReader buffReader = Files.newBufferedReader(Paths.get("E:\\input.txt"), StandardCharsets.UTF_8);
      System.out.println("Stream of lines...");
      buffReader.lines().forEach(System.out::println);
   }
}
Stream of lines...
Amit
Tom
David
Andre
Keemo
Gayle
The Anonymous Functions in Python

These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons.
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
 Live Demo
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
How to loop through a menu list on a webpage using Selenium?

We can loop through a menu list on a webpage using Selenium webdriver.
In a webpage, a list is represented by an ul tag and it consists of elements with li tag. Thus the li tag can be said as the child of ul.
First, we have to identify the element with ul tag with any locator, then traverse through its li sub-elements with the help of a loop. Finally, use the method getText to obtain the text on the li elements.
Let us try to identify the menu list on a webpage.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class MenuItemLst{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify elements in menu with findElements
      List<WebElement> p = driver.
      findElements(By.xpath("//ul[@class='toc reading']/li"));
      System.out.println("Menu Items are: ");
      //iterate through list
      for( WebElement i: p){
         System.out.println(i.getText());
         driver.quit();}
      }
   }
}
How to create default function parameter in PHP? - GeeksforGeeks

15 May, 2020
The default parameter concept comes from C++ style default argument values, same as in PHP you can provide default parameters so that when a parameter is not passed to the function. Then it is still available within the function with a pre-defined value. This function also can be called optional parameter.
Syntax:
function greeting($name=" parameter_value ")
Parameter: This function accepts a single parameter that is $name here, holds the parameter value.
Below examples illustrate the procedure to create and use the default function parameter:Example 1:
<?php      function greeting($name="GeeksforGeeks")    {          echo "Welcome to $name ";          echo("\n");    }      greeting("Gfg");       // Passing no value     greeting();     greeting("A Computer Science Portal");  ?>  
Output:
Welcome to Gfg 
Welcome to GeeksforGeeks 
Welcome to A Computer Science Portal 
Example 2:
<?php        function welcome($first="GeeksforGeeks",                     $last="A Computer Science Portal for Geeks")                     {                            echo "Greeting: $first $last";                           echo("\n");    }        welcome();      welcome("night_fury");      welcome("night_fury","Contributer");  ?>    
Output:
Greeting: GeeksforGeeks A Computer Science Portal for Geeks
Greeting: night_fury A Computer Science Portal for Geeks
Greeting: night_fury Contributer
PHP-basics
Picked
PHP
Web Technologies
Web technologies Questions
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 ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in 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 ?
How to insert spaces/tabs in text using HTML/CSS?