code-rag-bench/online-tutorials huggingface dataset:
How to Subtract Two Columns in Pandas DataFrame?

19 Dec, 2021
In this article, we will discuss how to subtract two columns in pandas dataframe in Python.
Dataframe in use:
This is the __getitem__ method syntax ([]), which lets you directly access the columns of the data frame using the column name.
Example: Subtract two columns in Pandas dataframe
Python3
import numpy as npimport pandas as pd  data = np.arange(0, 20).reshape(4, 5)    df1 = pd.DataFrame(data,                   index=['Row 1', 'Row 2', 'Row 3', 'Row 4'],                   columns=['Column 1', 'Column 2', 'Column 3',                            'Column 4', 'Column 5'])  # using our previous example# now let's subtract the values of two columnsdf1['Column 1'] - df1['Column 2']
Output: 
We can create a function specifically for subtracting the columns, by taking column data as arguments and then using the apply method to apply it to all the data points throughout the column. 
Example: Subtract two columns in Pandas dataframe
Python3
import numpy as npimport pandas as pd  def diff(a, b):    return b - a  data = np.arange(0, 20).reshape(4, 5)    df = pd.DataFrame(data,                  index=['Row 1', 'Row 2', 'Row 3', 'Row 4'],                  columns=['Column 1', 'Column 2', 'Column 3',                           'Column 4', 'Column 5'])    df['Difference_2_1'] = df.apply(    lambda x: diff(x['Column 2'], x['Column 2']), axis=1)
Output : 
Since the operation we want to perform is simple we can you can directly use the apply() method without explicitly defining a function. Provide the axis argument as 1 to access the columns. 
Syntax:
s.apply(func, convert_dtype=True, args=())
Parameters:
func: .apply takes a function and applies it to all values of pandas series.
convert_dtype: Convert dtype as per the function’s operation.
args=(): Additional arguments to pass to function instead of series.
Return Type: Pandas Series after applied function/operation.
Example: Subtract two columns in Pandas Dataframe 
Python3
import pandas as pdimport numpy as np  data = np.arange(0, 20).reshape(4, 5)    df = pd.DataFrame(data,                  index=['Row 1', 'Row 2', 'Row 3', 'Row 4'],                  columns=['Column 1', 'Column 2', 'Column 3',                           'Column 4', 'Column 5'])    df['diff_3_4'] = df.apply(lambda x: x['Column 3'] - x['Column 4'], axis=1)df
Output:
assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones. 
Example: Subtract two columns in Pandas dataframe
Python3
import numpy as npimport pandas as pd  data = np.arange(0, 20).reshape(4, 5)    df = pd.DataFrame(data,                  index=['Row 1', 'Row 2', 'Row 3', 'Row 4'],                  columns=['Column 1', 'Column 2', 'Column 3',                           'Column 4', 'Column 5'])    df = df.assign(diff_1_5=df['Column 1'] - df['Column 5'])  df
Output : 
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP headers | Link

23 Jun, 2020
For serialising one or more links in HTTP headers, the HTTP Link header-field is used. It allows the server to point an interested client to another resource containing metadata about the requested resource. It is semantically equivalent to the HTML <link> element. Syntax: 
Link: <uri-reference>; param1="value1" param2="value2"

Directive: This header accept a single directive as mentioned above and described below. The link header contains parameters, which are separated with ; and are equivalent to attributes of the <link> element. 
<uri-reference>: The URI reference, must be enclosed between < and >. 
Examples: 
This means that more information about the requested resource is available in the resource whose relative URI is https://www.geeksforgeeks.org/.
Link: <https://www.geeksforgeeks.org/>; rel="preconnect"

The URI must be enclosed between < and >. So, this is not a good way to write.
Link:https://www.geeksforgeeks.org/; rel="preconnect"

Specifying multiple links:  You can specify multiple links separated by commas. 
Example: 
Link: <https://example.one.com>; rel="preconnect", 
<https://example.two.com>; rel="preconnect", 
<https://example.three.com>; rel="preconnect"

Typical uses are: 
A map of different language, content-type and version-specific URIs
Licensing, such as Creative Commons
Information about how to edit the file
Policy information about appropriate use and/or distribution of the data
Supported Browsers: The browser supported by HTTP-header  link are unknown till now. 
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Difference Between PUT and PATCH Request
ReactJS | Router
Roadmap to Learn JavaScript For Beginners
How to float three div side by side using CSS?
How to get character array from string in JavaScript?
Is there any way to check if there is a null value in an object or array in JavaScript?

To check if there is a null value in an object or array, use the concept of includes().
Following is the code −
var nameArray1 = ["John", "David", "Mike", "Sam", null];
if (nameArray1.includes(null) == true) {
   console.log("array1 contains null value");
} else {
   console.log("array1 does not contains null value");
}
var nameArray2 = ["Adam", "Bob", "Robert"];
if (nameArray2.includes(null) == true) {
   console.log("array2 contains null value");
} else {
   console.log("array2 does not contains null value");
}
var objectData = { name: null };
if (Object.values(objectData).includes(null)) {
   console.log("object contains null value");
   } else {
      console.log("object does not contains null value");
}
To run the above program, you need to use the below command −
node fileName.js.
Here, my file name is demo314.js.
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo314.js
array1 contains null value
array2 does not contains null value
object contains null value
Python program to remove the nth index character from a non-empty string - GeeksforGeeks

19 Dec, 2021
Given a String, the task is to write a Python program to remove the nth index character from a non-empty string
Examples:
Input: str = "Stable"
Output: Modified string after removing  4 th character 
Stable.
 
Input: str = "Arrow"
Output: Modified string after removing  4 th character 
Arro
The first approach uses a new string variable for storing the modified string. We keep a track of the characters of the string and as soon as we encounter a character at nth index, we don’t copy it to the modified string variable. Else, we copy it to a new variable. 
Python3
# declaring a string variablestr = "Geeksforgeeks is fun." # index to remove character atn = 4 # declaring an empty string variable for storing modified stringmodified_str = '' # iterating over the stringfor char in range(0, len(str)):     # checking if the char index is equivalent to n    if(char != n):        # append original string character        modified_str += str[char] print("Modified string after removing ", n, "th character ")print(modified_str)
Output:
Modified string after removing  4 th character  
Geekforgeeks is fun.
Time Complexity = O(n), where n is the length of the string. 
Space Complexity = O(n)
The second approach uses the idea of extraction of a sequence of characters within a range of index values. The syntax used in Python is as follows : 
string_name[start_index : end_index] – extracts the characters starting at start_index and less than end_index, that is, up to end_index-1. If we don’t specify the end_index, it computes till the length of the string.
Therefore, we extract all the characters of a string in two parts, first until nth index and the other beginning with n+1th index. We then append these two parts together. 
Python3
# declaring a string variablestr = "Geeksforgeeks is fun." # index to remove character atn = 8 # extracts 0 to n-1th indexfirst_part = str[0:n] # extracts characters from n+1th index until the endsecond_part = str[n+1:]print("Modified string after removing ", n, "th character ") # combining both the parts togetherprint(first_part+second_part)
Output:
Modified string after removing  8 th character  
Geeksforeeks is fun.
Time Complexity = O(n), where n is the length of the string.
Space Complexity = O(n)
kk9826225
Python string-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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
CLOC - Count number of lines of code in file - GeeksforGeeks

23 Aug, 2021
cloc is a command-line-based tool. It counts the blank lines, comment lines, actual code lines written in many programming languages. cloc is completely written in the Perl language, and it has no external dependencies. cloc can run on many operating systems like Linux, macOS, Windows, OpenBSD and many more.
Now let’s see how we can install the cloc on different operating systems. Use one of the following commands according to your operating system:
sudo apt install cloc          
sudo yum install cloc            
sudo dnf install cloc            
sudo pacman -S cloc              
sudo emerge -av dev-util/cloc    
sudo apk add cloc                
doas pkg_add cloc                
sudo pkg install cloc            
sudo port install cloc           
brew install cloc                
choco install cloc               
scoop install cloc               
To install the cloc using npm use the following command:
npm install -g cloc              
Now we have installed the cloc on the system. Let’s see how to use the cloc. The general syntax of using cloc is as follows
cloc [options] <FILE|DIR> ...
Now let’s see understand by one example. We have one source file written in CPP and contains the following code:
// hello.C
#include <iostream>
int main ()
{
std::cout << "hello" << std::endl;  // comment 1
std::cout << "again" << std::endl;  /* comment
2 */
}
Now let’s use the cloc to count the line
As we can see, the cloc has correctly counted the comments and code lines.
cloc can also count the number of lines physical, commented, an empty line written in different languages in compressed files
cloc compressed_file
Let’s see one example, we have one compressed file which contains some files written in JS and markdown, Let’s use the cloc on that compressed file.
To get the line of code count file-wise in folder or zip file use the –by-file option with the cloc command.
cloc --by-file folder/compressedFile
cloc can also count the codes written in different files in the GitHub repository. Now let’s clone cloc GitHub repository. To count the number of lines in the GitHub repo the following command:
cloc commit
First, clone the repository and use the cloc.
git clone https://github.com/AlDanial/cloc
cd cloc
cloc ec44eb0
cloc provide many other options. To know more about the cloc read the man page of cloc.
man cloc
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2
How to use JavaScript in Selenium to click an Element?

We can use the JavaScript Executor in Selenium to click an element.
Selenium can execute JavaScript commands with the help of the method executeScript.
Sometimes while clicking a link, we get the IllegalStateException, to avoid this exception, the JavaScript executor is used instead of the method click. The parameters to be passed to the executeScript method to click an element are - arguments[0].click(); and the web element locator.
WebElement m=driver.findElement(By.linkText("Company"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", m);
Let us click the link Company on the below page −
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ClickLnkJS{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement m = driver.findElement(By.linkText("Company"));
      // click with Javascript Executor
      JavascriptExecutor js = (JavascriptExecutor) driver;
      js.executeScript("arguments[0].click();", m);
      System.out.println("Page navigated to:" + driver.getTitle());
      driver.quit();
   }
}
C++ List Library - push_front() Function

The C++ function std::list::push_front() inserts new element at the beginning of list and increases size of list by one.
Following is the declaration for std::list::push_front() function form std::list header.
void push_front (const value_type& val);

void push_front (const value_type& val);

val − Value of element to be inserted into list.
None.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::list::push_front() function.
#include <iostream>
#include <list>

using namespace std;

int main(void) {
   list<int> l;

   for (int i = 0; i < 5; ++i)
      l.push_front(i + 1);

   cout << "List contains following elements" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
List contains following elements
5
4
3
2
1

 Print
 Add Notes
 Bookmark this page
Java Program to subtract integers and check for overflow

To check for Integer overflow, we need to check the Integer.MAX_VALUE with the subtracted integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java.
Let us see an example wherein integers are subtracted and if the result is more than Integer.MAX_VALUE, then an exception is thrown.
The following is an example showing how to check for Integer overflow.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int val1 = 9898999;
      int val2 = 8784556;
      System.out.println("Value1: "+val1);
      System.out.println("Value2: "+val2);
      long sub = (long)val1 - (long)val2;
      if (sub > Integer.MAX_VALUE) {
         throw new ArithmeticException("Overflow!");
      }
      // displaying subtraction result
      System.out.println("Subtraction Result: "+(int)sub);
   }
}
Value1: 9898999
Value2: 8784556
Subtraction Result: 1114443
In the above example, we have taken the following two integers −
int val1 = 9898999;
int val2 = 8784556;
Now we will cast and subtract them to a long.
long sub = (long)val1 - (long)val2;
If the result is more than the maximum value, then an exception is thrown.
If (sub > Integer.MAX_VALUE) {
   throw new ArithmeticException("Overflow!");
}
C# | Type.GetTypeCode() Method - GeeksforGeeks

20 May, 2019
Type.GetTypeCode() Method is used to get the underlying type code of the specified Type.
Syntax: public static TypeCode GetTypeCode (Type type);Here, it takes the type whose underlying type code to get.
Return Value: This method returns the code of the underlying type, or Empty if type is null.
Below programs illustrate the use of Type.GetTypeCode() Method:
Example 1:
// C# program to demonstrate the// Type.GetTypeCode() Methodusing System;using System.Globalization;using System.Reflection;  class GFG {      // Main Method    public static void Main()    {          // creating and initializing object Type        Type type = typeof(int);          // Getting the TypeCode        TypeCode code = Type.GetTypeCode(type);          // Display the Result        Console.WriteLine("TypeCode is {0}", code);    }}
TypeCode is Int32

Example 2:
// C# program to demonstrate the// Type.GetTypeCode() Methodusing System;using System.Globalization;using System.Reflection;  class GFG {      // Main Method    public static void Main()    {        // Calling get() Method        get(typeof(int));        get(typeof(decimal));        get(typeof(double));        get(typeof(short));        get(typeof(string));    }      // defining get Method    public static void get(Type type)    {          // Getting Typecode        TypeCode code = Type.GetTypeCode(type);          // Display the Result        Console.WriteLine("TypeCode of {1} is {0}", code, type);    }}
TypeCode of System.Int32 is Int32
TypeCode of System.Decimal is Decimal
TypeCode of System.Double is Double
TypeCode of System.Int16 is Int16
TypeCode of System.String is String

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.type.gettypecode?view=netframework-4.8
CSharp-method
CSharp-Type-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
Switch Statement in C#
Convert String to Character Array in C#
C# | How to insert an element in an Array?
Lambda Expressions in C#
What are objects in C#?

Like any other object-oriented language, C# also has object and classes. Objects are real-world entities and instance of a class. Access the members of the class using an object.
To access the class members, you need to use the dot (.) operator after the object name. The dot operator links the name of an object with the name of a member, for example,
Box b1 = new Box();
Above you can see Box1 is our object. We will use it to access the members −
b1.height = 7.0;
You can also use it to call member functions −
b1.getVolume();
The following is an example showing how objects and class work in C# −
 Live Demo
using System;

namespace BoxApplication {
   class Box {
      private double length; // Length of a box
      private double breadth; // Breadth of a box
      private double height; // Height of a box

      public void setLength( double len ) {
         length = len;
      }

      public void setBreadth( double bre ) {
         breadth = bre;
      }

      public void setHeight( double hei ) {
         height = hei;
      }

      public double getVolume() {
         return length * breadth * height;
      }
   }

   class Boxtester {
      static void Main(string[] args) {
         // Creating two objects
         Box Box1 = new Box(); // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;

         // using objects to call the member functions
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         Console.ReadKey();
      }
   }
}
Volume of Box1 : 210
Volume of Box2 : 1560
How to put author/title name over image in ReactJS? - GeeksforGeeks

06 Sep, 2021
We can place the author or title name over the image using the GridListTileBar Component in ReactJS. This component adds an overlay over the child component. Material UI for React has this component available for us and it is very easy to integrate. We can use the GridListTileBar component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/icons
Project Structure: It will look like the following.
Project Structure
Filename-App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import GridList from '@material-ui/core/GridList';import GridListTile from '@material-ui/core/GridListTile';import GridListTileBar from '@material-ui/core/GridListTileBar';import ListSubheader from '@material-ui/core/ListSubheader';import IconButton from '@material-ui/core/IconButton';import InfoIcon from '@material-ui/icons/Info'; const App = () => {  return (    <div style={{ width: 700, margin: 'auto' }}>      <h3>How to put title over image in ReactJS?</h3>      <GridList cellHeight={180} >        <GridListTile key="Subheader" cols={2} rows={4} style={{ height: 'auto' }}>          <ListSubheader component="div">December</ListSubheader>        </GridListTile>        <GridListTile>         <img         src="https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"/>          <GridListTileBar            title='Computer Science Portal'            subtitle={<span>by: GeeksforGeeks</span>}            actionIcon={              <IconButton aria-label={`Best Place to learn`}>                <InfoIcon />              </IconButton>            }          />        </GridListTile>      </GridList>    </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: Now open your browser and go to http://localhost:3000/, you will see the following output:
 
 
sagar0719kumar
JavaScript
ReactJS
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
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
How to write the temperature conversion table by using function?

Temperature conversion is nothing but converting Fahrenheit temperature to Celsius or Celsius to Fahrenheit.
In this programming, we are going to explain, how to convert the Fahrenheit temperature to Celsius temperature and how to represent the same in the form of the table by using a function.
Following is the C program for temperature conversion −
 Live Demo
#include<stdio.h>
float conversion(float);
int main(){
   float fh,cl;
   int begin=0,stop=300;
   printf("Fahrenheit \t Celsius\n");// display conversion table heading
   printf("----------\t-----------\n");
   fh=begin;
   while(fh<=stop){
      cl=conversion(fh); //calling function
      printf("%3.0f\t\t%6.lf\n",fh,cl);
      fh=fh+20;
   }
   return 0;
}
float conversion(float fh) //called function{
   float cl;
   cl= (fh - 32) * 5 / 9;
   return cl;
}
When the above program is executed, it produces the following result −
Fahrenheit  Celsius
---------- -----------
   0          -18
   20         -7
   40          4
   60          16
   80          27
   100         38
   120         49
   140         60
   160         71
   180         82
   200         93
   220         104
   240         116
   260         127
   280         138
   300         149
In a similar way, you can write the program for converting Celsius to Fahrenheit
By simply changing the equation to
Fahrenheit = (Celsius* 9 / 5) + 32.
Cross Product Operation in DFA - GeeksforGeeks

20 Nov, 2019
Prerequisite: Designing finite automataLet’s understand the cross product operation in Deterministic Finite Automata (DFA) with help of the below example-
Designing a DFA for the set of string over {a, b} such that string of the language contains even number of a’s and b’s then desired language will be like below-
L = {ε, aa, bb, abab, aabb, baba, bbaa, .......}
Let’s see steps for cross product operation in DFA:
Step-1:Let’s form a DFA which count even number of a’s-In the below state transition diagram, ‘W’ is the initial state and final state too, which accept language of string containing even number of a’s and any number of b’s.The language accepted by above DFA is-
L = {ε, aab, b, baa, aabbbbb, aaaab, ..........}
The language does not accepted by above DFA is-
L = {aaa, abbb, baaa, bbaaba, ...........}
Step-2:Let’s form a DFA which count even number of b’s-In the below state transition diagram, ‘Y’ is the initial state and final state too, which accept language of string containing even number of b’s and any number of a’s.The language accepted by above DFA is-
L = {ε, bba, a, abb, bbbbaaaa, bbbba, ...........}
The language does not accepted by above DFA is-
L = {bbb, bbba, abbb, aaba, ...........}
Step-3:Here the states of step-1 and step-2 get cross multiplied and produce a result like below-
{W, X} * {Y, Z} = {WY, WZ, XY, XZ} 
And in the below, state transition diagram four states {WY, WZ, XY, XZ} used is the result of the cross product of step 1 and 2 states out of which ‘WY’ is the initial and final state too because in step 1 ‘W’ is the initial and final state and in step 2 ‘Y’ is the initial and final state and rest are normal states.Then the resultant state transition diagram after cross product operation becomes like below-Thus the above DFA accepts all the language of an even number of a’s and b’s string and the language which is accepted and not accepted by above DFA is given below-
L1 = {ε, aa, bb, abab, aabb, baba, bbaa, .......}
L2 = {aaa, aaabb, aaabaabb, aaabb, baaba, bbbaa, .......}

L1 is accepted by above DFA but L2 does not.
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Clustered and Non-clustered index
Phases of a Compiler
Regular Expressions, Regular Grammar and Regular Languages
Preemptive and Non-Preemptive Scheduling
Introduction of Process Synchronization
Regular Expressions, Regular Grammar and Regular Languages
Difference between DFA and NFA
Introduction of Finite Automata
Difference between Mealy machine and Moore machine
Pumping Lemma in Theory of Computation
Dart Programming - Defining a Function

A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The syntax for defining a standard function is given below −
function_name() {  
   //statements      
}

OR
void function_name() { 
   //statements 
}

The void keyword indicates that the function does not return any value to the caller.
test() { 
   //function definition 
   print("function called"); }

    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
How to retrieve table names from a database in MySQL?

To retrieve table names from a database in MySQL, the syntax is as follows −
show tables from yourDatabaseName;
Let us implement the above query in order to retrieve table names from a database in MySQL −
mysql> show tables from hb_student_tracker;
This will produce the following output −
+------------------------------+
| Tables_in_hb_student_tracker |
+------------------------------+
| demotable192                 |
| demotable193                 |
| demotable194                 |
| demotable195                 |
| demotable196                 |
| demotable197                 |
| demotable198                 |
| demotable199                 |
| demotable200                 |
| demotable201                 |
| demotable202                 |
| demotable203                 |
| demotable204                 |
| demotable205                 |
| demotable206                 |
| demotable207                 |
| demotable208                 |
| demotable209                 |
| demotable210                 |
| demotable211                 |
| demotable212                 |
| demotable213                 |
| demotable214                 |
| demotable215                 |
| demotable216                 |
| demotable217                 |
| demotable218                 |
| demotable219                 |
| demotable220                 |
| demotable221                 |
| demotable223                 |
| demotable224                 |
| demotable225                 |
| demotable226                 |
| demotable227                 |
| demotable228                 |
| demotable229                 |
| demotable230                 |
| demotable231                 |
| demotable232                 |
| demotable233                 |
| insertcurrentdate            |
| reorderintegerexcept0        |
| student                      |
+------------------------------+
44 rows in set (0.00 sec)
Python Plotly – Exporting to Static Images

19 Dec, 2021
In this article, we will discuss how to export plotly graphs as static images using Python.
To get the job done there are certain additional installations that need to be done. Apart from plotly, orca and psutil have to be installed.
psutil (python system and process utilities) is a cross-platform Python package that retrieves information about running processes and system utilisation.  It can be installed as follows.
pip install psutil
ocra cannot be installed via pip so conda is employed for the same.
conda install -c plotly plotly-orca psutil
Once all installations are successful, we have to import plotly.io when importing other required modules and use, write_image() function to save the output plot.
Syntax:
write_image(figure, path)
Parameter:
figure: plot
format: location to save along with the format
Plotly images can be made static if they are exported either as images or in vector format. The only difference is specifying the format while importing.
Example: 
In this example, we export a plotly graph as an image in python. 
Dataset used here: bestsellers.csv
Python3
# import librariesimport plotly.express as pximport pandas as pdimport plotly.io as pio  # read datasetdata = pd.read_csv("bestsellers.csv")  # create plotfig = px.scatter(data, x="Year", y="Price", color="Genre")  # export as static imagepio.write_image(fig, "op.png")
Output:
Example: In this example, we export plotly graph as a vector image in python.
Python3
# import librariesimport plotly.express as pximport pandas as pdimport plotly.io as pio  # read datasetdata = pd.read_csv("bestsellers.csv")  # create plotfig = px.scatter(data, x="Year", y="Price", color="Genre")  # export as static imagepio.write_image(fig, "op.pdf")
Output:
Picked
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
HTML | target Attribute

13 Dec, 2021
The HTML target Attribute is used to specify where to open the linked document. It can be used on various elements such as:
HTML | <a> target Attribute
HTML | <area> target Attribute
HTML | <base> target Attribute
HTML | <form> target Attribute
Syntax:
<element target="_blank|_self|_parent|_top|framename"\>
Attribute Values:
_blank: It opens the link in a new window.
_self: It is the default value. It opens the linked document in the same frame.
_parent: It opens the linked document in the parent frameset.
_top: It opens the linked document in the full body of the window.
framename: It opens the linked document in the named frame.
Example:
<!DOCTYPE html> <html>   <head>     <title>         HTML target Attribute     </title> </head>   <body>     <center>         <h1>GeeksForGeeks</h1>           <h2>HTML Target Attribute</h2>           <p>Welcome to             <a href="https://ide.geeksforgeeks.org/"                    id="GFG" target="_self">                 GeeksforGeeks             </a>         </p>     </center> </body>   </html> 
Output:
Supported Browsers: The browser supported by HTML target Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
arorakashish0911
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript | typedArray.subarray() with Examples

14 Feb, 2019
The typedArray.subarray() is an inbuilt function in JavaScript which is used to return a part of the typedArray object.Syntax:
typedarray.subarray(begin, end)
Parameters: It accepts two parameters which are described below:
begin: It specifies the index of the starting element from which the part of the given array to be started. It is optional and inclusive.end: It specifies the index of the ending element up to which the part of the given array to be included. It is optional and exclusive.
begin: It specifies the index of the starting element from which the part of the given array to be started. It is optional and inclusive.
end: It specifies the index of the ending element up to which the part of the given array to be included. It is optional and exclusive.
Return value: It returns a new array which is formed from the given typedArray object.
<script>     // Creating a new typedArray Uint8Array() object   const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]);     // Calling subarray() functions   B = A.subarray(1, 3)   C = A.subarray(1)   D = A.subarray(3)   E = A.subarray(0, 6)   F = A.subarray(0)        // Printing some new typedArray which are   // the part of the given input typedArray   document.write(B +"<br>");   document.write(C +"<br>");   document.write(D +"<br>");   document.write(E +"<br>");   document.write(F +"<br>");  </script>
Output:
10,15
10,15,20,25,30,35
20,25,30,35
5,10,15,20,25,30
5,10,15,20,25,30,35
Code #2:When index are in negative then elements get accessed from the end of the typedArray object.
Below is the required code which illustrates this negative indexing concept.
<script>     // Creating a new typedArray Uint8Array() object   const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]);     // Calling subarray() functions   B = A.subarray(-1)   C = A.subarray(-2)   D = A.subarray(-3)   E = A.subarray(3)   F = A.subarray(0)        // Printing some new typedArray which are   // the part of the given input typedArray   document.write(B +"<br>");   document.write(C +"<br>");   document.write(D +"<br>");   document.write(E +"<br>");   document.write(F +"<br>");  </script>
Output:
35
30,35
25,30,35
20,25,30,35
5,10,15,20,25,30,35
javascript-functions
javascript-typedArray
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
JavaScript String includes() Method
JavaScript | fetch() Method
Lodash _.groupBy() Method
Compare two file paths in Java

Two file paths can be compared lexicographically in Java using the method java.io.File.compareTo(). This method requires a single parameter i.e.the abstract path name that is to be compared. It returns 0 if the two file path names are equal.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      File file1 = new File("C:/File/demo1.txt");
      File file2 = new File("C:/File/demo1.txt");
      if (file1.compareTo(file2) == 0) {
         System.out.println("Both the paths are lexicographically equal");
      } else {
         System.out.println("Both the paths are lexicographically not equal");
      }
   }
}
The output of the above program is as follows −
Both the paths are lexicographically equal
Now let us understand the above program.
The method java.io.File.compareTo() is used to compare the two file paths lexicographically. If 0 is returned by the method, the file paths are lexicographically equal, otherwise not. A code snippet that demonstrates this is given as follows −
File file1 = new File("C:/File/demo1.txt");
File file2 = new File("C:/File/demo1.txt");
if (file1.compareTo(file2) == 0) {
   System.out.println("Both the paths are lexicographically equal");
} else {
   System.out.println("Both the paths are lexicographically not equal");
}
Java - ByteArrayInputStream

The ByteArrayInputStream class allows a buffer in the memory to be used as an InputStream. The input source is a byte array.
ByteArrayInputStream class provides the following constructors.
ByteArrayInputStream(byte [] a)
This constructor accepts a byte array as a parameter.
ByteArrayInputStream(byte [] a, int off, int len)
This constructor takes an array of bytes, and two integer values, where off is the first byte to be read and len is the number of bytes to be read.
Once you have ByteArrayInputStream object in hand then there is a list of helper methods which can be used to read the stream or to do other operations on the stream.
public int read()
This method reads the next byte of data from the InputStream. Returns an int as the next byte of data. If it is the end of the file, then it returns -1.
public int read(byte[] r, int off, int len)
This method reads upto len number of bytes starting from off from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.
public int available()
Gives the number of bytes that can be read from this file input stream. Returns an int that gives the number of bytes to be read.
public void mark(int read)
This sets the current marked position in the stream. The parameter gives the maximum limit of bytes that can be read before the marked position becomes invalid.
public long skip(long n)
Skips ‘n’ number of bytes from the stream. This returns the actual number of bytes skipped.
Following is the example to demonstrate ByteArrayInputStream and ByteArrayOutputStream.
import java.io.*;
public class ByteStreamTest {

   public static void main(String args[])throws IOException {
      ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12);

      while( bOutput.size()!= 10 ) {
         // Gets the inputs from the user
         bOutput.write("hello".getBytes()); 
      }
      byte b [] = bOutput.toByteArray();
      System.out.println("Print the content");
      
      for(int x = 0 ; x < b.length; x++) {
         // printing the characters
         System.out.print((char)b[x]  + "   "); 
      }
      System.out.println("   ");
      
      int c;
      ByteArrayInputStream bInput = new ByteArrayInputStream(b);
      System.out.println("Converting characters to Upper case " );
      
      for(int y = 0 ; y < 1; y++) {
         while(( c = bInput.read())!= -1) {
            System.out.println(Character.toUpperCase((char)c));
         }
         bInput.reset(); 
      }
   }
}
Following is the sample run of the above program −
Print the content
h   e   l   l   o   h   e   l   l   o      
Converting characters to Upper case 
H
E
L
L
O
H
E
L
L
O


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
What’s New In Python 3.9 Dictionaries? | by Anupam Chugh | Towards Data Science

Python 3.9 is currently in beta and with a release scheduled in October 2020, there’s a lot to look forward to. For Python developers eagerly waiting for the update, there are a few interesting additions, be it new string methods, topological ordering, or type hinting.
But the one that stands out for me is the new union operator that provides a cleaner way to merge or update dictionaries. In the next sections, we’ll look at how the new union operators make manipulating dictionaries a whole lot easier and concise.
Dictionaries are a built-in Python data type used to hold mutable, insertion ordered collection of key-value pairs. Up until Python 3.8, we’d typically use the update method or the ** unpacking operator but the most trivial way to update a dictionary is by inserting a key-value pair in it as shown below:
d1 = {'a': 'Cat', 'b': 10}d1['type'] = 'animal'{'a': 'Cat', 'b': 10, 'type': 'animal'}
But this doesn’t take us very far when it comes to updating a dictionary with multiple new key-value pairs.
The update() method is clearly the better bet in such cases:
dict1 = {'a': 'Cat', 'b': 10}dict2 = {'c': 'Dog', 'd': 11}dict1.update(dict2)#prints {'a': 'Cat', 'b': 10, 'c': 'Dog', 'd': 11}
Though the above way works fine for updating a dictionary but for merging dictionaries, you need to fall back on the copy() method. This is because the update() method executes in-place and would modify the original dictionary. So, you’d have to create a clone of the first dictionary in order to merge without modifying as shown below:
d3 = d1.copy()d3.update(d2)
This looks fine, but it’s not pythonic. We can do better by using the double-asterisk operator ** to merge dictionaries in a single line of code.
dict4 = {**dict1, **dict2, **dict3}#ord3 = dict(d1, **d2)
While the above approach works and is certainly concise, however, there is a caveat. For a high-level language like Python which wins brownie points for its readability, the above unpacking operator can seem ugly to many developers.
No wonder, there’s are two new union operators in Python 3.9.
Python 3.9 introduces new clean union operators in the form of | and |+ for merging and updating dictionaries respectively.
For merging two dictionaries we use the operator like this:
d3 = d1 | d2
The above operator trims the copy() and update() methods in a neat way. Also, the operator brings a consistent behavior in Python as it’s already used for merging two sets.
At the same time, we can use the in-place merging or updating of dictionaries by using the |= operator. It works the same way as the augmented assignment operator +=.
d1 |= d2#equivalent tod1 = d1 | d2
In case, we have common keys in two or more dictionaries, the key-value from the second or last dictionary gets picked in the merge or update operations.
It’s important to note that the insertion order matters, as we can see above.
The new union operators that’ll roll out with Python 3.9 are a small but welcome addition. The good thing is, they’d work when merging a dictionary with iterables as well.
That’s it for this one. Thanks for reading.
How can we apply different borders to JButton in Java?

A JButton is a subclass of AbstractButton class and it can be used for adding platform-independent buttons in a Java Swing application. A JButon can generate an ActionListener interface when the user clicking on a button, it can also generate MouseListener when a user can do some actions from the mouse and KeyListener when a user can do some actions from the keyboard.
We can set different borders like LineBorder, BevelBorder, EtchcedBorder, EmptyBorder, TitledBorder, etc to JButton using the setBorder() method of JComponent class.
public void setBorder(Border border)
import javax.swing.*;
import java.awt.*;
public class JButtonBordersTest extends JFrame {
   private JButton button[];
   private JPanel panel;
   public JButtonBordersTest() {
      setTitle("JButton Borders");
      panel = new JPanel();
      panel.setLayout(new GridLayout(7, 1));
      button = new JButton[7];
      for(int count = 0; count < button.length; count++) {
         button[count] = new JButton("Button "+(count+1));
         panel.add(button[count]);
      }
      button[0].setBorder(BorderFactory.createLineBorder(Color.blue));
      button[1].setBorder(BorderFactory.createBevelBorder(0));
      button[2].setBorder(BorderFactory.createBevelBorder(1, Color.red, Color.blue));
      button[3].setBorder(BorderFactory.createBevelBorder(1, Color.green, Color.orange, Color.red, Color.blue));
      button[4].setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
      button[5].setBorder(BorderFactory.createEtchedBorder(0));
      button[6].setBorder(BorderFactory.createTitledBorder("Titled Border"));

      add(panel, BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JButtonBordersTest();
   }
}
Sort the words in lexicographical order in Java

The words are sorted in lexicographical order or dictionary order. This means that the words are alphabetically ordered based on their component alphabets. An example of this is given as follows.
The original order of the words is
Tom
Anne
Sally
John
The lexicographical order of the words is
Anne
John
Sally
Tom
A program that demonstrates this is given as follows.
 Live Demo
public class Example {
   public static void main(String[] args) {
      String[] words = { "Peach", "Orange", "Mango", "Cherry", "Apple" };
      int n = 5;
      System.out.println("The original order of the words is: ");
      for(int i = 0; i < n; i++) {
         System.out.println(words[i]);
      }
      for(int i = 0; i < n-1; ++i) {
         for (int j = i + 1; j < n; ++j) {
            if (words[i].compareTo(words[j]) > 0) {
               String temp = words[i];
               words[i] = words[j];
               words[j] = temp;
            }
         }
      }
      System.out.println("\nThe lexicographical order of the words is: ");
      for(int i = 0; i < n; i++) {
         System.out.println(words[i]);
      }
   }
}
The original order of the words is:
Peach
Orange
Mango
Cherry
Apple
The lexicographical order of the words is:
Apple
Cherry
Mango
Orange
Peach
Difference between HashTable and HashMap in Java

Following are the notable differences between HashTable and HashMap classes in Java.
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class Tester {
   public static void main(String args[]) {

      Map<String, String> map = new HashMap<String, String>();

      map.put("1", "One");
      map.put("2", "Two");
      map.put("3", "Three");
      map.put("5", "Five");
      map.put("6", "Six");

      System.out.println("HashMap: " + map);

      Map<String, String> map1 = new Hashtable<String, String>();
   
      map1.put("1", "One");
      map1.put("2", "Two");
      map1.put("3", "Three");
      map1.put("5", "Five");
      map1.put("6", "Six");

      System.out.println("HashTable: " + map1);
   }
}
HashMap: {1 = One, 2 = Two, 3 = Three, 5 = Five, 6 = Six}
HashTable: {6 = Six, 5 = Five, 3 = Three, 2 = Two, 1 = One}