code-rag-bench/online-tutorials huggingface dataset:
What are the differences between paint() method and repaint() method in Java?

paint(): This method holds instructions to paint this component. In Java Swing, we can change the paintComponent() method instead of paint() method as paint calls paintBorder(),
paintComponent() and paintChildren() methods. We cannot call this method directly instead we can call repaint().
repaint(): This method cannot be overridden. It controls the update() -> paint() cycle. We can call this method to get a component to repaint itself. If we have done anything to change the look of the component but not the size then we can call this method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class PaintRepaintTest extends JPanel implements MouseListener {
   private Vector v;
   public PaintRepaintTest() {
      v = new Vector();
      setBackground(Color.white);
      addMouseListener(this);
   }
   public void paint(Graphics g) { // paint() method
      super.paint(g);
      g.setColor(Color.black);
      Enumeration enumeration = v.elements();
      while(enumeration.hasMoreElements()) {
         Point p = (Point)(enumeration.nextElement());
         g.drawRect(p.x-20, p.y-20, 40, 40);
      }
   }
  public void mousePressed(MouseEvent me) {
      v.add(me.getPoint());
      repaint(); // call repaint() method
   }
   public void mouseClicked(MouseEvent me) {}
   public void mouseEntered(MouseEvent me) {}
   public void mouseExited(MouseEvent me) {}
   public void mouseReleased(MouseEvent me) {}
   public static void main(String args[]) {
      JFrame frame = new JFrame();
      frame.getContentPane().add(new PaintRepaintTest());
      frame.setTitle("PaintRepaint Test");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setSize(375, 250);
      frame.setVisible(true);
   }
}
In the above program, if we click on the screen able to draw squares. In the mousePressed() method, we can call the repaint() method.
HTML <th> colspan Attribute

The colspan attribute of the <th> element is used to set the number of columns a header cell should span.
Following is the syntax −
<th colspan="num">
Above, num is the count of columns a header cell should span.
Let us now see an example to implement the colspan attribute of the <th> element −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
   border: 2px solid green;
}
</style>
</head>
<body>
<h2>Product Expenses</h2>
<table>
   <tr>
      <th colspan="2">Expenses</th>
   </tr>
   <tr>
      <td>Product Development</td>
      <td>500000</td>
   </tr>
   <tr>
      <td>Marketing</td>
      <td>500000</td>
   </tr>
   <tr>
      <td>Services</td>
      <td>100000</td>
   </tr>
   <tr>
      <td>Support</td>
      <td>100000</td>
   </tr>
   <tr>
      <td>Maintenance</td>
      <td>100000</td>
   </tr>
   <tr>
      <td colspan="2">Total Budget = INR 1300000</td>
   </tr>
</table>
</body>
</html>
In the above example, we have set the column count to span the header cell −
<th colspan="2">Expenses</th>
The count is 2, therefore two columns will span the header cell.
Compute the value of Cauchy Quantile Function in R Programming - qcauchy() Function - GeeksforGeeks

25 Jun, 2020
qcauchy() function in R Language is used to calculate the value of cauchy quantile function. It also creates a density plot of cauchy quantile function.
Syntax: qcauchy(vec, scale)
Parameters:vec: x-values for cauchy functionscale: Scale for plotting
Example 1:
# R Program to compute value of# cauchy quantile function  # Creating vector for x-valuesx <- seq(0, 1, by = 0.2)  # Apply qcauchy() Functiony <- qcauchy(x, scale = 4)y
Output:
[1]      -Inf -5.505528 -1.299679  1.299679  5.505528       Inf

Example 2:
# R Program to compute value of# cauchy quantile function  # Creating vector for x-valuesx <- seq(0, 1, by = 0.02)  # Apply qcauchy() Functiony <- qcauchy(x, scale = 1)  # Plotting the graphplot(y)
Output:
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
Renaming and Deleting Files in Python

Python os module provides methods that help you perform file-processing operations, such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
The rename() method takes two arguments, the current filename and the new filename.
os.rename(current_file_name, new_file_name)
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
You can use the remove() method to delete files by supplying the name of the file to be deleted as the argument.
os.remove(file_name)

Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
# Delete file test2.txt
os.remove("text2.txt")
Find Exponential of a column in Pandas-Python - GeeksforGeeks

02 Jul, 2021
Let’s see how to find Exponential of a column in Pandas Dataframe. First, let’s create a Dataframe:
Python3
# importing pandas and# numpy librariesimport pandas as pdimport numpy as np  # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57],         ['Deepak', 10, 98.51], ['Soni', 4, 40.24],         ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name',                                     'University_Rank',                                     'University_Marks']) # displaying the data framedf
 
 
Output:
 
 
 The exponential of any column is found out by using numpy.exp() function. This function calculates the exponential of the input array/Series.
 
Syntax: numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None)  
Return: An array with exponential of all elements of input array/Series.  
 
Example 1: Finding exponential of the single column (integer values).
 
Python3
# importing pandas and# numpy librariesimport pandas as pdimport numpy as np  # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57],         ['Deepak', 10, 98.51], ['Soni', 4, 40.24],         ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name',                                     'University_Rank',                                     'University_Marks']) # finding the exponential value# of column using np.exp() functiondf['exp_value'] = np.exp(df['University_Rank']) # displaying the data framedf
 
 
Output:
 
 
Example 2: Finding exponential of the single column (Float values).
 
Python3
# importing pandas and# numpy librariesimport pandas as pdimport numpy as np  # creating and initializing a listvalues= [ ['Rohan', 5, 50.59], ['Elvish', 2, 90.57],         ['Deepak', 10, 98.51], ['Soni', 4, 40.24],         ['Radhika', 1, 99.05], ['Vansh', 15, 85.56] ] # creating a pandas dataframedf = pd.DataFrame(values, columns = ['Name',                                     'University_Rank',                                     'University_Marks']) # finding the exponential value# of column  using np.exp() functiondf['exp_value'] = np.exp(df['University_Marks']) # displaying the data framedf
 
 
Output:
 
 
surinderdawra388
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
ArrayList trimToSize() in Java with example - GeeksforGeeks

26 Nov, 2018
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list’s current size. This method is used to trim an ArrayList instance to the number of elements it contains.
Syntax:
trimToSize()
Parameter: It does not accepts any parameter.
Return Value: It does not returns any value. It trims the capacity of this ArrayList instance to the number of the element it contains.
Errors and Exceptions: It does not have any errors and exceptions.
Below program illustrate the trimTosize() method:
// Java code to demonstrate the working of// trimTosize() method in ArrayList  // for ArrayList functionsimport java.util.ArrayList;  public class GFG {    public static void main(String[] args)    {          // creating an Empty Integer ArrayList        ArrayList<Integer> arr = new ArrayList<Integer>(9);          // using add(), add 5 values        arr.add(2);        arr.add(4);        arr.add(5);        arr.add(6);        arr.add(11);          // trims the size to the number of elements        arr.trimToSize();          System.out.println("The List elements are:");          // prints all the elements        for (Integer number : arr) {            System.out.println("Number = " + number);        }    }}
Output:
The List elements are:
Number = 2
Number = 4
Number = 5
Number = 6
Number = 11

Java - util package
Java-ArrayList
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java
Collections in Java
Python | Pandas Series.clip() - GeeksforGeeks

11 Oct, 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.
Python Series.clip() is used to clip value below and above to passed Least and Max value. This method comes in use when doing operations like Signal processing. As we know there are only two values in Digital signal, either High or Low. Pandas Series.clip() can be used to restrict the value to a Specific Range.
Syntax: Series.clip(lower=None, upper=None, axis=None, inplace=False)
Parameters:lower: Sets Least value of range. Any values below this are made equal to lower.upper: Sets Max value of range. Any values above this are made equal to upper.axis: 0 or ‘index’ to apply method by rows and 1 or ‘columns’ to apply by columnsinplace: Make changes in the caller series itself. (Overwrite with new values)
Return type: Series with updated values
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
ExampleIn this example, the .clip() method is called on Age column of data. A minimum value of 22 is passed to lower parameter and 25 to upper parameter. The returned series is then stored in a new column ‘New Age’. Before doing any operations, Null rows were dropped using .dropna() to avoid errors.
# importing pandas module import pandas as pd   # importing regex moduleimport re    # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     # removing null values to avoid errors data.dropna(inplace = True)   # lower value of rangelower = 22  # upper value of rangeupper = 25  # passing values to new columndata["New Age"]= data["Age"].clip(lower = lower, upper = upper)  # displaydata
Output:As shown in the output image, the New Age column has least value of 22 and max value of 25. All values are restricted to this range. Values below 22 were made equal to 22 and values above 25 were made equal to 25.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Defaultdict in Python
LEX program to count the number of vowels and consonants in a given string - GeeksforGeeks

27 Feb, 2020
Prerequisite: Flex (Fast lexical Analyzer Generator)
Given a string containing both vowels and consonants, write a LEX program to count the number of vowels and consonants in given string.
Examples:
Input: Hello everyone
Output: Number of vowels are: 6
        Number of consonants are: 7


Input: This is GeeksforGeeks
Output: Number of vowels are: 7
        Number of consonants are: 12

Approach-Approach is very simple. If any vowel is found increase vowel counter, if consonant is found increase consonant counter otherwise do nothing.
Below is the implementation:
%{    int vow_count=0;    int const_count =0;%}  %%[aeiouAEIOU] {vow_count++;}[a-zA-Z] {const_count++;}%%int yywrap(){}int main(){    printf("Enter the string of vowels and consonents:");    yylex();    printf("Number of vowels are:  %d\n", vow_count);    printf("Number of consonants are:  %d\n", const_count);    return 0;} 
Output:
ankita_chandra
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Symbol Table in Compiler
Code Optimization in Compiler Design
Intermediate Code Generation in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Introduction of Compiler Design
Types of Parsers in Compiler Design
Ambiguous Grammar
Difference between Compiler and Interpreter
Peephole Optimization in Compiler Design
S - attributed and L - attributed SDTs in Syntax directed translation
Program to find gravitational force between two objects - GeeksforGeeks

04 May, 2022
Introduction to Gravitational Force
We know that gravity is universal. According to Newton’s Law of Universal Gravitation, all objects attract each other with a force of gravitational attraction. According to this law, the force of gravitational attraction is directly dependent upon the masses of both objects and inversely proportional to the square of the distance that separates their centres. On removing the proportionality sign, we add G, the Universal Gravitational Constant. This can be reduced to the following equation: F= Gravitation force of attraction between two objects in newton(N)G=Universal Gravitational Constant()m1 and m2 = Mass of two objects(Kg)r= separation in meters(m) between the objects, as measured from their centres of mass.
Examples: 
Input: m1 = 20000000 kg
       m2 = 4000000 kg
       r = 15 m
Output : The Gravitational Force is:  23.73 N

Input: m1 = 5000000 kg
       m2 = 900000 kg
       r = 30 m
Output : The Gravitational Force is:  0.33 N
The approach is simple. We will just use the formula mentioned in the Introduction. 
C++
Python3
Javascript
// C++ code to find Gravitational Force#include <iostream>using namespace std; float round(float F){    float value = (int)(F * 100 + .5);    return (float)value / 100;} float force(double m1, double m2, double r){    float G;    G = 6.67 / 1e11;    float F;    F = (G * m1 * m2) / (r * r);         // Rounding to two digits after decimal    return round(F);} // Driver codeint main(){    float m1, m2, r;    m1 = 5000000;    m2 = 900000;    r = 30;         cout << "The Gravitational Force is: "         << force(m1, m2, r) << "N";         return 0;} // This code is contributed by parthagarwal1962000
# Python3 code to find Gravitational Forcedef force(m1, m2, r):    G = 6.673*(10**-11)    F = (G*m1*m2)/(r**2)     # Rounding to two digits after decimal    return round(F, 2) # Driver Codem1 = 5000000m2 = 900000r = 30print("The Gravitational Force is: ", force(m1, m2, r), "N")
<script>// JavaScript code to find Gravitational Forcefunction round (F){    var value = (F * 100 + .5);         return value / 100;    } function force(m1, m2, r){    var G;     G = 6.67 / 1e11;    var F;    F = (G * m1 * m2) / (r * r);                  // Rounding to two digits after decimal    return round(F);     } // Driver code    var m1, m2, r;    m1 = 5000000;    m2 = 900000;    r = 30;         document.write("The Gravitational Force is: " + force(m1, m2, r) +"N");     // This code is contributed by shivanisinghss2110</script>
Output: 
The Gravitational Force is:  0.33 N
 
ysachin2314
parthagarwal1962000
shivanisinghss2110
surinderdawra388
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constructors in Java
Exceptions in Java
Data Types
Inline Functions in C++
Pure Virtual Functions and Abstract Classes in C++
Difference between Abstract Class and Interface in Java
Destructors in C++
Python Exception Handling
Exception Handling in C++
Input and Output
Number of matches required to find the winner

13 Apr, 2021
Given a number N which represent the number of players participating in Badminton match. The task is to determine the Number of matches required to determine the Winner. In each Match 1 player is knocked out.
Examples: 
Input:  N = 4
Output: Matches played = 3
(As after each match only N - 1 players left)

Input: N = 9
Output: Matches played = 8
Approach: Since, after each match one player is knocked out. So to get the winner, n-1 players should be knocked out and for which n-1 matches to be played.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function that will tell// no. of matches requiredint noOfMatches(int N){    return N - 1;} // Driver codeint main(){    int N = 8;     cout << "Matches played = " << noOfMatches(N);     return 0;}
// Java implementation of above approachimport java.io.*; class GFG{     // Function that will tell// no. of matches requiredstatic int noOfMatches(int N){    return N - 1;} // Driver codepublic static void main (String[] args){    int N = 8;    System.out.println ("Matches played = " +                          noOfMatches(N));}} // This code is contributed by jit_t
# Python 3 implementation of# above approach # Function that will tell# no. of matches requireddef noOfMatches(N) :     return N - 1 # Driver codeif __name__ == "__main__" :     N = 8     print("Matches played =",              noOfMatches(N)) # This code is contributed# by ANKITRAI1
//C# implementation of above approachusing System; public class GFG{              // Function that will tell// no. of matches requiredstatic int noOfMatches(int N){    return N - 1;} // Driver code         static public void Main (){    int N = 8;    Console.WriteLine("Matches played = " +                        noOfMatches(N));}} // This code is contributed by ajit
<?php// PHP implementation of above approach // Function that will tell// no. of matches requiredfunction noOfMatches($N){    return ($N - 1);} // Driver code$N = 8;echo "Matches played = ",         noOfMatches($N); // This code is contributed by akt_mit?>
<script> // Javascript implementation of above approach // Function that will tell// no. of matches requiredfunction noOfMatches(N){    return N - 1;} // Driver codevar N = 8; document.write("Matches played = " +               noOfMatches(N));                // This code is contributed by rutvik_56 </script>
Matches played = 7
 
jit_t
ankthon
rutvik_56
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
Operator Overloading in C++
Polymorphism in C++
Types of Operating Systems
Constructors in C++
Constructors in Java
Exceptions in Java
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Python | Pandas Period.year

06 Jan, 2019
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 Period.year attribute return an integer value representing the year the given period lies in.
Syntax : Period.year
Parameters : None
Return : year
Example #1: Use Period.year attribute to find the year the period lies in for the given Period object.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2,                  day = 21, hour = 8, minute = 21)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.year attribute to find the value of year
# return the year valueprd.year
Output :
As we can see in the output, the Period.year attribute has returned 2000 indicating that the given period lies in the year of 2000.
Example #2: Use Period.year attribute to find the year the period lies in for the given Period object.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='T', year = 2006, month = 10,                            hour = 15, minute = 49)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.year attribute to find the value of year
# return the yearprd.year
Output :As we can see in the output, the Period.year attribute has returned 2006 indicating that the given period lies in the year of 2006.
Pandas scalar-period
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
HTML | <img> alt Attribute

27 May, 2019
The <img> alt attribute is used to specify the alternate text for an image. It is useful when the image not displayed. It is used to give alternative information for an image.
Syntax:
<img alt="text">
Attribute Values: It contains single value text which specifies the alternative text for an image.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML img alt Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML img alt Attribute</h2>      <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"          alt="GeeksforGeeks logo">  </body>  </html>
Output:
Supported Browsers: The browser supported by HTML <img> alt Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to Upload Image into Database and Display it using PHP ?
How to Insert Form Data into Database using PHP ?
DOM (Document Object Model)
How to make elements float to center?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How do you run JavaScript script through the Terminal?
Node.js | fs.writeFileSync() Method
Difference between var, let and const keywords in JavaScript
React Native style Prop

28 Apr, 2021
In React Native, we can style our application using JavaScript. All of the core components accept a prop named style. The style names and values usually match how CSS works on the web, except names are written using camel casing.
The style prop can be a plain old JavaScript object. We can also pass an array of styles.
Syntax:
<component_tag style={styles.bigBlue}>...</component_tag>
OR
<component_tag style={[styles.bigBlue, styles.red]}>...</component_tag>
Now let’s start with the implementation:
Step 1: Open your terminal and install expo-cli by the following command.npm install -g expo-cli
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
Step 2: Now create a project by the following command.expo init myapp
Step 2: Now create a project by the following command.
expo init myapp
Step 3: Now go into your project folder i.e. myappcd myapp
Step 3: Now go into your project folder i.e. myapp
cd myapp
Project Structure:
Example: Now let’s style any text or any component by using the style prop. Here we will set the background-color green to make the button center.
App.js
import React from 'react';import { StyleSheet,        Text,        View,        Button,        Alert        } from 'react-native';  export default function App() {  // Alert functionconst alert = ()=>{    Alert.alert(    "GeeksforGeeks",    "A Computer Science Portal",    [        {        text: "Cancel",        },        {        text: "Agree",        }    ]    );}  return (    <View style={styles.container}>      <Button title={"Register"} onPress={alert}/>    </View>);}  const styles = StyleSheet.create({container: {    flex: 1,    backgroundColor: 'green',    alignItems: 'center',    justifyContent: 'center',},});
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again. 
Reference: https://reactnative.dev/docs/style
Picked
React-Native
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
How to float three div side by side using CSS?
Design a Tribute Page using HTML & CSS
Roadmap to Learn JavaScript For Beginners
Custom Field Validations in Django Forms

16 Mar, 2021
This article revolves around how to add custom validation to a particular field. For example to add validation of an email to a CharField by specifying a particular format. There can be multiple ways on how to achieve custom validation. In this article, we are going to show it from the form itself so that you need not manipulate it elsewhere.
A validator is a callable that takes a value and raises a ValidationError if it doesn’t meet criteria. Validators can be useful for re-using validation logic between different types of fields.
Django Custom Field Validation Explanation for Django Forms
Illustration of validators using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
To use built-in Validators in your forms field, import validators in forms.py like this.
Python3
from django import formsfrom django.core import validators  class StuForm(forms.Form):  name = forms.CharField(    validators =[validators.MaxLengthValidator(10)])
call built-in MaxLengthValidators from validators, it raises validation error if the length of the value is greater than limit_value.
How to create our custom validators in django ?
So we are going to create our own custom validators.
Example 1 :-
We will create a validator, if name is not start with s it will raise a an error.
forms.py
Python3
from django import forms  def start_with_s(value):  if value[0]!='s':    raise forms.ValidationError("Name should start with s")    class StuForm(forms.Form):  name = forms.CharField(    validators =[start_with_s])
Pass the function in validators.
We write a logic if a name doesn’t start with ‘s’ it raise an error and wrap in function.
Example 2 :-
We will create a validator for a mobile number field
Python3
from django import forms  def mobile_no(value):  mobile = str(value)  if len(mobile) != 10:    raise forms.ValidationError("Mobile Number Should 10 digit")    class StuForm(forms.Form):  mob = forms.IntegerField(    validators =[mobile_no])
We write a logic of mobile number validator it raise an error and wrap in function
Django-forms
Python Django
Python Framework
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
HTTP headers | Content-Location - GeeksforGeeks

07 Nov, 2019
The HTTP Content-Location header is an entity-header that gives another location for the data that is returned and also tells how to access the resource by indicating the direct URL. Its usage is often confused with another HTTP Header which is Location. The main difference between them is that Location gives the URL of the resource where the redirection of the page happens while HTTP Content-Location is used to indicate the URL of a transmitted resource.
Syntax:
Content-Location: <url>
Directives: This header accepts a single directive mentioned above and described below:
<url>:This directive holds the relative or absolute URL that gives access to a resource.
Examples:
In this example, index.html is the URL which indicated the location of the content.Content-Location: /index.html
Content-Location: /index.html
In this example, teddy.xml is the URL which indicates the location of the content.Content-Location: /teddy.xmlTo check this Content-Location in action go to Inspect Element -> Network check the response header for Content-Location like below.Supported Browsers: The browsers are compatible with the HTTP Content-Location header are listed below:Google ChromeInternet ExplorerOperaFirefoxSafariMy Personal Notes
arrow_drop_upSave
Content-Location: /teddy.xml
To check this Content-Location in action go to Inspect Element -> Network check the response header for Content-Location like below.
Supported Browsers: The browsers are compatible with the HTTP Content-Location header are listed below:
Google Chrome
Internet Explorer
Opera
Firefox
Safari
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to apply style to parent if it has child with CSS?
AWK - Workflow

To become an expert AWK programmer, you need to know its internals. AWK follows a simple workflow − Read, Execute, and Repeat. The following diagram depicts the workflow of AWK −
AWK reads a line from the input stream (file, pipe, or stdin) and stores it in memory.
All AWK commands are applied sequentially on the input. By default AWK execute commands on every line. We can restrict this by providing patterns.
This process repeats until the file reaches its end.
Let us now understand the program structure of AWK.
The syntax of the BEGIN block is as follows −
Syntax
BEGIN {awk-commands}

The BEGIN block gets executed at program start-up. It executes only once. This is good place to initialize variables. BEGIN is an AWK keyword and hence it must be in upper-case. Please note that this block is optional.
The syntax of the body block is as follows −
Syntax
/pattern/ {awk-commands}

The body block applies AWK commands on every input line. By default, AWK executes commands on every line. We can restrict this by providing patterns. Note that there are no keywords for the Body block.
The syntax of the END block is as follows −
Syntax
END {awk-commands}

The END block executes at the end of the program. END is an AWK keyword and hence it must be in upper-case. Please note that this block is optional.
Let us create a file marks.txt which contains the serial number, name of the student, subject name, and number of marks obtained.
1)  Amit    Physics  80
2)  Rahul   Maths    90
3)  Shyam   Biology  87
4)  Kedar   English  85
5)  Hari    History  89

Let us now display the file contents with header by using AWK script.
Example
[jerry]$ awk 'BEGIN{printf "Sr No\tName\tSub\tMarks\n"} {print}' marks.txt
When this code is executed, it produces the following result −
Output
Sr No Name Sub Marks
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89

At the start, AWK prints the header from the BEGIN block. Then in the body block, it reads a line from a file and executes AWK's print command which just prints the contents on the standard output stream. This process repeats until file reaches the end.
 Print
 Add Notes
 Bookmark this page
Design and Analysis Max Cliques

In an undirected graph, a clique is a complete sub-graph of the given graph. Complete sub-graph means, all the vertices of this sub-graph is connected to all other vertices of this sub-graph.
The Max-Clique problem is the computational problem of finding maximum clique of the graph. Max clique is used in many real-world problems.
Let us consider a social networking application, where vertices represent people’s profile and the edges represent mutual acquaintance in a graph. In this graph, a clique represents a subset of people who all know each other.
To find a maximum clique, one can systematically inspect all subsets, but this sort of brute-force search is too time-consuming for networks comprising more than a few dozen vertices.
Algorithm: Max-Clique (G, n, k) 
S := Φ 
for i = 1 to k do 
   t := choice (1...n)  
   if t Є S then 
      return failure 
   S := S ∪ t  
for all pairs (i, j) such that i Є S and j Є S and i ≠ j do 
   if (i, j) is not a edge of the graph then  
      return failure 
return success 

Max-Clique problem is a non-deterministic algorithm. In this algorithm, first we try to determine a set of k distinct vertices and then we try to test whether these vertices form a complete graph.
There is no polynomial time deterministic algorithm to solve this problem. This problem is NP-Complete.
Take a look at the following graph. Here, the sub-graph containing vertices 2, 3, 4 and 6 forms a complete graph. Hence, this sub-graph is a clique. As this is the maximum complete sub-graph of the provided graph, it’s a 4-Clique.

    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Handling Browser Authentication using Selenium

We can handle browser authentication with Selenium webdriver. We have to pass the credentials appended with the URL. The username and password must be added with the format: https://username:password@URL. Let us make an attempt to handle the below browser authentication.
Once the User Name and Password are entered correctly and the OK button is clicked, we are navigated to the actual page with the text Congratulations! You must have the proper credentials.
https://username:password@URL
https://admin:admin@the−internet.herokuapp.com/basic_auth
Here, the username and password value is admin.
URL is www.the−internet.herokuapp.com/basic_auth
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class BrwAuthnPopup{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String a = "admin";
      // appending username, password with URL
      String s = "https://" + a + ":" + a + "@" +
      "the-internet.herokuapp.com/basic_auth";
      driver.get(s);
      // identify text
      String m = driver.findElement(By.cssSelector("p")).getText();
      System.out.println("Text is: " + m);
      driver.close();
   }
}
numpy.asanyarray() in Python - GeeksforGeeks

28 May, 2019
numpy.asanyarray()function is used when we want to convert input to an array but it pass ndarray subclasses through. Input can be scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays.
Syntax : numpy.asanyarray(arr, dtype=None, order=None)
Parameters :arr : [array_like] Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.dtype : [data-type, optional] By default, the data-type is inferred from the input data.order : Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to ‘C’.
Return : [ndarray or an ndarray subclass] Array interpretation of arr. If arr is ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.
Code #1 : List to array
# Python program explaining# numpy.asanyarray() function  import numpy as geekmy_list = [1, 3, 5, 7, 9]  print ("Input  list : ", my_list)       out_arr = geek.asanyarray(my_list)print ("output array from input list : ", out_arr) 
Output :
Input  list :  [1, 3, 5, 7, 9]
output array from input list :  [1 3 5 7 9]

 Code #2 : Tuple to array
# Python program explaining# numpy.asanyarray() function  import numpy as geek  my_tuple = ([1, 3, 9], [8, 2, 6])   print ("Input  tuple : ", my_tuple)    out_arr = geek.asanyarray(my_tuple) print ("output array from input tuple : ", out_arr) 
Output :
Input  tuple :  ([1, 3, 9], [8, 2, 6])
output array from input tuple :  [[1 3 9]
 [8 2 6]]

 Code #3 : Scalar to array
# Python program explaining# numpy.asanyarray() function  import numpy as geek  my_scalar = 12   print ("Input  scalar : ", my_scalar)    out_arr = geek.asanyarray(my_scalar) print ("output array from input scalar : ", out_arr) print(type(out_arr))
Output :
Input  scalar :  12
output array from input scalar :  12
class 'numpy.ndarray'

SujithSagar
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
PHP | ArrayObject count() Function - GeeksforGeeks

27 Sep, 2019
The ArrayObject::count() function is an inbuilt function in PHP which is used to get the number of public properties in the ArrayObject.
Syntax:
int ArrayObject::count( void )
Parameters: This function does not accept any parameters.
Return Value: This function returns the number of public properties in the ArrayObject.
Below programs illustrate the ArrayObject::count() function in PHP:
Program 1:
<?php // PHP program to illustrate the // ArrayObject::count() function   // Declare an array and convert it// into array object$arrObject = new ArrayObject(    array('Geeks', 'for', 'Geeks'));   // Use ArrayObject::count() function// to count the number of public// properties in the ArrayObject$count = $arrObject->count();   print_r($count);   ?> 
3

Program 2:
<?php // PHP program to illustrate the // ArrayObject::count() function   // Declare an associative array$arr = array(    "a" => "Welcome",    "b" => "to",     "c" => "GeeksforGeeks");   // Create into array object $arrObject = new ArrayObject($arr);   // Use ArrayObject::count() function// to count the number of public// properties in the ArrayObject$count = $arrObject->count();   print_r($count);   ?> 
3

Reference: https://www.php.net/manual/en/arrayobject.count.php
PHP-ArrayObject
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database 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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Remove json element - JavaScript?

Let’s say the following is our JSON string −
var details =
[
   {
      customerName: "Chris",
      customerAge: 32
   },
   {
      customerName: "David",
      customerAge: 26
   },
   {
      customerName: "Bob",
      customerAge: 29
   },
   {
      customerName: "Carol",
      customerAge: 25
   }
]
To remove JSON element, use the delete keyword in JavaScript.
Following is the complete code to remove JSON element −
var details =
[
   {
      customerName: "Chris",
      customerAge: 32
   },
   {
      customerName: "David",
      customerAge: 26
   },
   {
      customerName: "Bob",
      customerAge: 29
   },
   {
      customerName: "Carol",
      customerAge: 25
   }
]
delete details[0].customerAge;
console.log(details);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo211.js −
PS C:\Users\Amit\JavaScript-code> node demo211.js
[
   { customerName: 'Chris' },
   { customerName: 'David', customerAge: 26 },
   { customerName: 'Bob', customerAge: 29 },
   { customerName: 'Carol', customerAge: 25 }
]
What does built-in class attribute __doc__ do  in Python?

All functions have a built-in attribute __doc__, which returns the doc string defined in the function source code.
def foo():
    """ This is an example of how a doc_string looks like.
          This string gives useful information about the function being defined.
    """
    pass
print foo.__doc__
 Let's see how this would look like when we print it
This is an example of how a doc_string looks like.
          This string gives useful information about the function being defined.
JavaScript | RegExp [0-9] Expression - GeeksforGeeks

22 Apr, 2019
The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits.
Syntax:
/[0-9]/ 
or
new RegExp("[0-9]")
Syntax with modifiers:
/[0-9]/g 
or
new RegExp("[0-9]", "g")
Example 1: This example searches the digits between [0-4] in the whole string.
<!DOCTYPE html><html>  <head>    <title>        JavaScript RegExp [0-9] Expression    </title></head>  <body style="text-align:center">          <h1 style="color:green">        GeeksforGeeks    </h1>          <h2>RegExp [0-9] Expression</h2>          <p>Input String: 1234567890</p>          <button onclick="geek()">        Click it!    </button>          <p id="app"></p>          <script>        function geek() {            var str1 = "123456790";            var regex4 = /[0-4]/g;            var match4 = str1.match(regex4);              document.getElementById("app").innerHTML =                     "Found " + match4.length                     + " matches: " + match4;        }    </script></body>  </html>                    
Output:Before Clicking the button:After Clicking the button:
Example 2: This example searches the digits between [0-9] in the whole string and replaces the characters with hash(#).
<!DOCTYPE html><html>  <head>    <title>        JavaScript RegExp [0-9] Expression    </title></head>  <body style="text-align:center">          <h1 style="color:green">        GeeksforGeeks    </h1>          <h2>RegExp [0-9] Expression</h2>          <p>Input String: 128@$%</p>          <button onclick="geek()">        Click it!    </button>          <p id="app"></p>          <script>        function geek() {            var str1 = "128@$%";                     var replacement = "#";            var regex4 = new RegExp("[0-9]", "g");            var match4 = str1.replace(regex4, replacement);              document.getElementById("app").innerHTML =                " New string: " + match4;        }    </script></body>  </html>                    
Output:Before Clicking the button:After Clicking the button:
Supported Browsers: The browsers supported by RegExp [0-9] Expression are listed below:
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
JavaScript-RegExp
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to detect browser or tab closing in JavaScript ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Array Basics Shell Scripting | Set 2 (Using Loops) - GeeksforGeeks

10 Jul, 2018
It is recommended to go through Array Basics Shell Scripting | Set-1IntroductionSuppose you want to repeat a particular task so many times then it is a better to use loops. Mostly all languages provides the concept of loops. In Bourne Shell there are two types of loops i.e for loop andwhile loop.
To Print the Static Array in Bash
1. By Using while-loop
${#arr[@]} is used to find the size of Array.
# !/bin/bash# To declare static Array arr=(1 12 31 4 5)i=0  # Loop upto size of array# starting from index, i=0while [ $i -lt ${#arr[@]} ]do    # To print index, ith    # element    echo ${arr[$i]}          # Increment the i = i + 1    i=`expr $i + 1`done
Output:
1
2
3
4
5
2. By Using for-loop
# !/bin/bash# To declare static Array arr=(1 2 3 4 5)  # loops iterate through a # set of values until the# list (arr) is exhaustedfor i in "${arr[@]}"do    # access each element     # as $i    echo $idone
Output:
1
2
3
4
5
To Read the array elements at run time and then Print the Array.
1. Using While-loop
# !/bin/bash# To input array at run# time by using while-loop  # echo -n is used to print# message without new lineecho -n "Enter the Total numbers :"read necho "Enter numbers :"i=0  # Read upto the size of # given array starting from# index, i=0while [ $i -lt $n ]do    # To input from user    read a[$i]      # Increment the i = i + 1    i=`expr $i + 1`done  # To print array values # starting from index, i=0echo "Output :"i=0  while [ $i -lt $n ]do    echo ${a[$i]}      # To increment index    # by 1, i=i+1     i=`expr $i + 1`done
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
2. Using for-loop
# !/bin/bash# To input array at run # time by using for-loop  echo -n "Enter the Total numbers :"read necho "Enter numbers:"i=0  # Read upto the size of # given array starting # from index, i=0while [ $i -lt $n ]do    # To input from user    read a[$i]      # To increment index     # by 1, i=i+1    i=`expr $i + 1`done  # Print the array starting# from index, i=0echo "Output :"  for i in "${a[@]}"do    # access each element as $i    echo $i done
Output:
Enter the Total numbers :3
Enter numbers :
1
3
5
Output :
1
3
5
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
scp command in Linux with Examples
echo command in Linux with Examples