code-rag-bench/online-tutorials huggingface dataset:
Python Tweepy – Getting the location of a user

06 Dec, 2021
In this article we will see how we can get the location of a user. The location of the user account need not be the exact physical location of the user. As the user is free to change their location, the location of the account can even by a hypothetical place. The location attribute is optional and is Nullable.
Identifying the location in the GUI :
In the above mentioned profile, India is the location of the profile.
In order to get the location we have to do the following :
Identify the user ID or the screen name of the profile.Get the User object of the profile using the get_user() method with the user ID or the screen name.From this object, fetch the location attribute present in it.
Identify the user ID or the screen name of the profile.
Get the User object of the profile using the get_user() method with the user ID or the screen name.
From this object, fetch the location attribute present in it.
Example 1: Consider the following profile :We will use the user ID to fetch the user. The user ID of the above mentioned profile is 57741058.
Python3
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the userid = 57741058  # fetching the useruser = api.get_user(id)  # fetching the locationlocation = user.location  print("The location of the user is : " + location)
Output :
The location of the user is : India

Example 2: Consider the following profile :We will use the screen name to fetch the user. The screen name of the above mentioned profile is PracticeGfG. Here the location is not mentioned.
Python3
# the screen name of the userscreen_name = "PracticeGfG"  # fetching the useruser = api.get_user(screen_name)  # fetching the namename = user.name  if location == "":    print("The user has not mentioned their location.")else:    print("The location of the user is : " + location)
Output :
The user has not mentioned their location.

kashishsoda
Python-Tweepy
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Sympy Line.intersection() method

10 Feb, 2020
Syntax: Line.intersection(o)

Parameters:
 o: Point or LinearEntity

Returns:
 intersection: list of geometrical entities

Example #1:
# import sympy and Point, Linefrom sympy import Point, Line  p1, p2, p3 = Point(0, 0), Point(1, 1), Point(7, 7)l1 = Line(p1, p2)  # using intersection() methodshowIntersection = l1.intersection(p3)  print(showIntersection)
Output:
[Point2D(7, 7)]
Example #2:
# import sympy and Point, Line, Segmentfrom sympy import Point, Line, Segment  p1, p2, p3, p4 = Point(0, 0), Point(1, 1), Point(0, 5), Point(2, 6)l1 = Line(p1, p2)s1 = Segment(p3, p4)    # using intersection() methodshowIntersection = l1.intersection(s1)  print(showIntersection)
Output:
[]
Python SymPy-Geometry
SymPy
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
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
How to divide the row values by row sum in R matrix?

To divide matrix row values by row sum in R, we can follow the below steps −
First of all, create a matrix.
Then, use apply function to divide the matrix row values by row sum.
Let’s create a matrix as shown below −
 Live Demo
M<-matrix(sample(1:100,75),ncol=3)
M
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
[,1] [,2] [,3]
[1,] 29 69 82
[2,] 60 22 87
[3,] 86 49 16
[4,] 66 14 96
[5,] 19 92 13
[6,] 90 80 35
[7,] 32 3 30
[8,] 44 2 59
[9,] 24 54 97
[10,] 75 37 70
[11,] 31 58 38
[12,] 76 72 55
[13,] 94 81 95
[14,] 18 28 1
[15,] 78 33 61
[16,] 63 25 93
[17,] 4 47 46
[18,] 21 42 68
[19,] 71 57 62
[20,] 43 12 64
[21,] 40 73 99
[22,] 84 5 15
[23,] 39 56 27
[24,] 45 100 98
[25,] 88 11 7
Using apply function to divide the row values of M by row sum −
 Live Demo
M<-matrix(sample(1:100,75),ncol=3)
M_new<-t(apply(M,1, function(x) x/sum(x)))
M_new
[,1] [,2] [,3]
[1,] 0.16111111 0.38333333 0.45555556
[2,] 0.35502959 0.13017751 0.51479290
[3,] 0.56953642 0.32450331 0.10596026
[4,] 0.37500000 0.07954545 0.54545455
[5,] 0.15322581 0.74193548 0.10483871
[6,] 0.43902439 0.39024390 0.17073171
[7,] 0.49230769 0.04615385 0.46153846
[8,] 0.41904762 0.01904762 0.56190476
[9,] 0.13714286 0.30857143 0.55428571
[10,] 0.41208791 0.20329670 0.38461538
[11,] 0.24409449 0.45669291 0.29921260
[12,] 0.37438424 0.35467980 0.27093596
[13,] 0.34814815 0.30000000 0.35185185
[14,] 0.38297872 0.59574468 0.02127660
[15,] 0.45348837 0.19186047 0.35465116
[16,] 0.34806630 0.13812155 0.51381215
[17,] 0.04123711 0.48453608 0.47422680
[18,] 0.16030534 0.32061069 0.51908397
[19,] 0.37368421 0.30000000 0.32631579
[20,] 0.36134454 0.10084034 0.53781513
[21,] 0.18867925 0.34433962 0.46698113
[22,] 0.80769231 0.04807692 0.14423077
[23,] 0.31967213 0.45901639 0.22131148
[24,] 0.18518519 0.41152263 0.40329218
[25,] 0.83018868 0.10377358 0.06603774
CSS ::placeholder Selector - GeeksforGeeks

21 Oct, 2021
The placeholder selector in the CSS pseudo-element is used to design the placeholder text by changing the text color and it allows to modify the style of the text.
The ::first-line pseudo-element is the only subset of CSS properties that is applicable & can be applied in a rule using ::placeholder in its selector. By default, the placeholder text appearance is a translucent or light gray color for most of the browsers.
Syntax:
::placeholder {
    // CSS property
}
We will understand the concept of ::placeholder selector & its implementation through the examples.
Example 1: This example illustrates the ::placeholder selector for changing the text color along with the background color for the placeholder text.
HTML
<!DOCTYPE html><html><head>    <title>::placeholder selector</title>    <style>    input::placeholder {        background-color: #fff;        margin: 10px;        padding: 5px;        color: Green;    }          h1 {        color: green;    }          body {        text-align: center;    }    </style></head>  <body>    <h1>Geeksforgeeks</h1>    <h2>::placeholder selector</h2>    <p>Name:        <input placeholder="GeeksforGeeks">    </p>  </body></html>
Output:
Example 2:  This example illustrates the ::placeholder selector for setting up the placeholder text with its attribute that identifies the hint which describes the expected value of an input field.
HTML
<!DOCTYPE html><html><head>    <title>::placeholder selector</title>    <style>    h1 {        color: green;    }          body {        text-align: center    }          input::placeholder {        background-color: white;        color: green;        text-align: center;    }    </style></head>  <body>    <h1>GeeksForGeeks</h1>    <h2>::placeholder Selector </h2>    <input type="text"            placeholder="Geeks">    <input type="text"            placeholder="Computer Science"> </body></html>
Output:
Supported Browser: The browser supported by ::placeholder selector are listed below:
Google Chrome 57.0, 4.0 -webkit-
Microsoft Edge 12.0 -webkit-, 10.0 -ms-
Firefox 51.0, 4.0 -moz-
Safari 10.1, 5.0 -webkit-
Opera 44.0, 15.0 -webkit-
bhaskargeeksforgeeks
CSS-Selectors
Picked
Technical Scripter 2018
CSS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
GATE | GATE-CS-2017 (Set 2) | Question 55 - GeeksforGeeks

28 Jun, 2021
Consider a binary code that consists only four valid codewords as given below.00000, 01011, 10101, 11110
Let minimum Hamming distance of code be p and maximum number of erroneous bits that can be corrected by the code be q. The value of p and q are:
(A) p = 3 and q = 1(B) p = 3 and q = 2(C) p = 4 and q = 1(D) p = 4 and q = 2Answer: (A)Explanation: We need to find minimum hamming distance(difference in their corresponding bit position)
00000, 01011, 10101, 11110

For two binary strings, hamming distance is number
of ones in XOR of the two strings.

Hamming distance of first and second is 3, so is 
for first and third. Hamming distance of first and
fourth is 4.

Hamming distance of second and third is 4, and 
second and fourth is 3.

Hamming distance of third and fourth is 3.

Thus a code with minimum Hamming distance d 
between its codewords can detect at most d-1
errors and can correct ⌊(d-1)/2⌋ errors.

Here d = 3. So number of errors that can be
corrected is 1.
Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
Why cannot we specify access modifiers inside an interface in C#?

Interface methods are contract with the outside world which specifies that class implementing this interface does a certain set of things.
Interface members are always public because the purpose of an interface is to enable other types to access a class or struct.
Interfaces can have access specifiers like protected or internal etc. Thus limiting 'the outside world' to a subset of 'the whole outside world'.
interface IInterface{
   void Save();
}
class Program{
   static void Main(){
      Console.ReadLine();
   }
}
The above example will compile properly without any errors
Prior to C# 8, interface members were public by default. In fact, if you put an access modifier on an interface member (including public), it would generate a compiler error.
interface IInterface{
   Public void Save();
}
class Program{
   static void Main(){
      Console.ReadLine();
   }
}
The above code throws compile time error in c# 7.0,but in c# 8.0 it compiles without any error
SQL Aliases

SQL aliases are used to give a table, or a column in a table, a temporary name.
Aliases are often used to make column names more readable.
An alias only exists for the duration of that query.
An alias is created with the AS keyword.
In this tutorial we will use the well-known Northwind sample database.
Below is a selection from the "Customers" table:
And a selection from the "Orders" table:
The following SQL statement creates two aliases, one for the CustomerID 
column and one for the CustomerName column:
The following SQL statement creates two aliases, one for the CustomerName 
column and one for the ContactName column. Note: It requires 
double quotation marks or square brackets if the alias name contains spaces:
The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode, 
City and Country):
Note: To get the SQL statement above to work in MySQL use the following:
Note: To get the SQL statement above to work in Oracle use the following:
The following SQL statement selects all the orders from the customer with 
CustomerID=4 (Around the Horn). We use the "Customers" and "Orders" tables, and 
give them the table aliases of "c" and "o" respectively (Here we use 
aliases to make the SQL shorter):
The following SQL statement is the same as above, but without aliases:
Aliases can be useful when:
There are more than one table involved in a query
Functions are used in the query
Column names are big or not very readable
Two or more columns are combined together
When displaying the Customers table,
make an ALIAS of the PostalCode column,
the column should be called Pno instead.
SELECT CustomerName,
Address,
PostalCode 
FROM Customers;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Java Program to sort an array in case-insensitive order

An array can be sorted in case-insensitive order using the java.util.Arrays.sort() method. Also the java.text.Collator class is required as Collator.getInstance() is used to obtain the Collator object for the required locale.
A program that demonstrates this is given as follows −
 Live Demo
import java.text.Collator;
import java.util.Arrays;
public class Demo {
   public static void main(String args[]) {
      String[] arr = new String[] { "apple", "mango", "Banana", "Melon", "orange" };
      System.out.print("The unsorted array is: ");
      System.out.println(Arrays.toString(arr));
      Arrays.sort(arr, Collator.getInstance());
      System.out.print("The sorted array in case-insensitive order is: ");
      System.out.println(Arrays.toString(arr));
   }
}
The unsorted array is: [apple, mango, Banana, Melon, orange]
The sorted array in case-insensitive order is: [apple, Banana, mango, Melon, orange]
Now let us understand the above program.
First the array arr[] is defined. Then the unsorted array is printed. A code snippet which demonstrates this is as follows −
String[] arr = new String[] { "apple", "mango", "Banana", "Melon", "orange" };
System.out.print("The unsorted array is: ");
System.out.println(Arrays.toString(arr));
The Arrays.sort(arr, Collator.getInstance()) method is used to sort the array in a case-insensitive order. Then the sorted array is displayed. A code snippet which demonstrates this is as follows −
Arrays.sort(arr, Collator.getInstance())
System.out.print("The sorted array in case-insensitive order is: ");
System.out.println(Arrays.toString(arr));
Creating a Priority Queue using Javascript

Our class will have the following functions −
enqueue(element): Function to add an element in the queue.
dequeue(): Function that removes an element from the queue.
peek(): Returns the element from the front of the queue.
isFull(): Checks if we reached the element limit on the queue.
isEmpty(): checks if the queue is empty.
clear(): Remove all elements.
display(): display all contents of the array
Let's start by defining a simple class with a constructor that takes the max size of the queue and a helper function that'll help us when we implement the other functions for this class. We'll also have to define another structure as part of the PriorityQueue class prototype that'll have the priority and data about each node. As we implemented stacks, we'll implement Priority Queue using Arrays as well. 
class PriorityQueue {
   constructor(maxSize) {
      // Set default max size if not provided
      if (isNaN(maxSize)) {
         maxSize = 10;
      }
      this.maxSize = maxSize;
      // Init an array that'll contain the queue values.
      this.container = [];
   }
   // Helper function to display all values while developing
   display() {
      console.log(this.container);
   }
   // Checks if queue is empty
   isEmpty() {
      return this.container.length === 0;
   }
   // checks if queue is full
   isFull() {
      return this.container.length >= this.maxSize;
   }
}
// Create an inner class that we'll use to create new nodes in the queue
// Each element has some data and a priority
PriorityQueue.prototype.Element = class {
   constructor (data, priority) {
      this.data = data; this.priority = priority;
   }
}
We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty.
The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly.
The isEmpty function checks if the size of the container is 0.
These will be helpful when we define other operations. The functions we define from this point onwards will all go into the PriorityQueue class.
How to find the index of an item in a C# list in a single step?

To get the index of an item in a single line, use the FindIndex() and Contains() method.
int index = myList.FindIndex(a => a.Contains("Tennis"));
Above, we got the index of an element using the FindIndex(), which is assisted by Contains method for that specific element.
Here is the complete code −
 Live Demo
using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      List < string > myList = new List < string > () {
         "Football",
         "Soccer",
         "Tennis",
      };

      // finding index
      int index = myList.FindIndex(a => a.Contains("Tennis"));

      // displaying index
      Console.WriteLine("List Item Tennis Found at index: " + index);
   }
}
List Item Tennis Found at index: 2
Check for Valid hex code - JavaScript

A string can be considered as a valid hex code if it contains no characters other than the 0-9 and a-f alphabets
For example −
'3423ad' is a valid hex code
'4234es' is an invalid hex code
We are required to write a JavaScript function that takes in a string and checks whether its a valid hex code or not.
Following is the code −
const str1 = '4234es';
const str2 = '3423ad';
const isHexValid = str => {
   const legend = '0123456789abcdef';
   for(let i = 0; i < str.length; i++){
      if(legend.includes(str[i])){
         continue;
      };
      return false;
   };
   return true;
};
console.log(isHexValid(str1));
console.log(isHexValid(str2));
Following is the output in the console −
false
true
Class Binding in Angular 8

23 Sep, 2020
Class binding in Angular makes it very easy to set the class property of a view element. We can set or remove the CSS class names from an element’s class attribute with the help of class binding.
We bind a class of a DOM element to a field that is a defined property in our Typescript Code. Its syntax is like that of property binding.
Syntax:
<element [class] = "typescript_property">

Approach:
Define a property element in the app.component.ts file.
In the app.component.html file, set the class of the HTML element by assigning the property value to the app.component.ts file’s element.
Example 1: Setting the class element using class binding.
app.component.html
HTML
<h1 [class] = "geeky">  GeeksforGeeks</h1>Upper Heading's class is : "{{ g[0].className }}"
app.component.ts
Javascript
import { Component, OnInit } from '@angular/core';  @Component({    selector: 'app-root',    templateUrl: './app.component.html'})export class AppComponent {    geeky = "GeekClass";    g = document.getElementsByClassName(this.geeky);}
Output:
Example 2: setting the class element using a function.
app.component.html
HTML
<h1 [class] = "setClass()">  GeeksforGeeks</h1>Upper Heading's class is : "{{ g[0].className }}"
app.component.ts
Javascript
import { Component, OnInit } from '@angular/core';  @Component({    selector: 'app-root',    templateUrl: './app.component.html'})export class AppComponent {    setClass() {        return "GeeksforGeeks";    }    g = document.getElementsByClassName(this.setClass());}
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to bundle an Angular app for production?
How to create button dynamically with click event in Angular ?
Difference between One-way Binding and Two-way Binding
How to detect click event outside Angular component ?
Define ng-if, ng-show and ng-hide
How to insert spaces/tabs in text using HTML/CSS?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
Python program to check if a word is a noun

11 Dec, 2020
Given a word, the task is to write a Python program to find if the word is a noun or not using Python.
Examples:
Input: India
Output: India is noun.

Input: Writing
Output: Writing is not a noun.
There are various libraries that can be used to solve this problem.
Approach 1: PoS tagging using NLTK
Python3
# import required modulesimport nltknltk.download('averaged_perceptron_tagger')  # taking input text as Indiatext = "India"ans = nltk.pos_tag()  # ans returns a list of tupleval = ans[0][1]  # checking if it is a noun or notif(val == 'NN' or val == 'NNS' or val == 'NNPS' or val == 'NNP'):    print(text, " is a noun.")else:    print(text, " is not a noun.")
Output: 
India is a noun.
Approach 2: PoS tagging using Spacy
Python3
# import required modulesimport spacynlp = spacy.load("en_core_web_sm")  # taking inputtext = "Writing"  # returns a document of objectdoc = nlp(text)  # checking if it is a noun or notif(doc[0].tag_ == 'NNP'):    print(text, " is a noun.")else:    print(text, " is not a noun.")
Output: 
Writing is not a noun.
Python string-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
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
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How To Reorder Boxplots in R with ggplot2?

17 Oct, 2021
In this article, we will discuss how to reorder the boxplot with ggplot2 in R Programming Language.
To reorder the boxplot we will use reorder() function of ggplot2.
Syntax: ggplot(sample_data, aes(x=reorder(name,value),y=value))
By default, ggplot2 orders the groups in alphabetical order. But for better visualization of data sometimes we need to reorder them in increasing and decreasing order. This is where the reorder() function comes into play. We use reorder() function, when we specify x-axis variable inside the aesthetics function aes(). Reorder() function sorts the carriers by mean values of x-axis variable by default.
In this example, the boxplot has been reordered using reorder() function. All the points of boxplots are arranged in increasing order of mean of their x-axis value. 
R
# load library tidyverselibrary(tidyverse)  # Diamonds dataset is provided by R natively# we will use that same dataset for our plot# basic boxplot# reorder plot using reorder() function# reorder function reorders plot according to # mean of variableggplot(diamonds, aes(x=reorder(cut,price), y=price)) +    # geom_boxplot is used to plot the boxplot  geom_boxplot()
Output:
Here, in this boxplot, all the boxes are arranged in increasing order of mean of value price due to the use of the reorder() function.
To reorder the data in descending order, we pass the -ve value as an argument to reorder() function. This reorders the plot according to decreasing order of the mean value of data passed as a parameter.
R
# load library tidyverselibrary(tidyverse)  # Diamonds dataset is provided by R natively# we will use that same dataset for our plot# basic boxplot# reorder plot using reorder() function# reorder function reorders plot according to mean of variable# Add -ve sign in price to get result in descending orderggplot(diamonds, aes(x=reorder(cut, -price), y=price)) +    # geom_boxplot is used to plot the boxplot  geom_boxplot() 
Output:
Here, in this boxplot, all the boxes are arranged in decreasing order of mean of value price due to the use of the reorder() function.
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Arithmetic Operators

29 Aug, 2020
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication and division.
There are 7 arithmetic operators in Python :
AdditionSubtractionMultiplicationDivisionModulusExponentiationFloor division
Addition
Subtraction
Multiplication
Division
Modulus
Exponentiation
Floor division
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.Example :
val1 = 2val2 = 3  # using the addition operatorres = val1 + val2print(res)
Output :
5
2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second value from the first value.Example :
val1 = 2val2 = 3  # using the subtraction operatorres = val1 - val2print(res)
Output :
-1
3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product of 2 values.Example :
val1 = 2val2 = 3  # using the multiplication operatorres = val1 * val2print(res)
Output :
6
4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first operand is divided by the second.Example :
val1 = 3val2 = 2  # using the division operatorres = val1 / val2print(res)
Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when first operand is divided by the second.Example :
val1 = 3val2 = 2  # using the modulus operatorres = val1 % val2print(res)
Output :
1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first operand to power of second.Example :
val1 = 2val2 = 3  # using the exponentiation operatorres = val1 ** val2print(res)
Output :
8
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the quotient when first operand is divided by the second.Example :
val1 = 3val2 = 2  # using the floor divisionres = val1 // val2print(res)
Output :
1
Below is the summary of all the 7 operators :
python-basics
Python-Operators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
matplotlib.patches.Rectangle in Python

27 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.patches.Rectangle class is used to rectangle patch to a plot with lower left at xy = (x, y) with specified width, height and rotation angle.
Syntax: class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)
Parameters:
xy: Lower left point to start the rectangle plotting
width : width of the rectangle
height: Height of the rectangle.
angle: Angle of rotation of the rectangle.
The below table has a list of valid kwargs;
Example 1:
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectangle    # The imageX = np.arange(16).reshape(4, 4)  # highlight some feature in the# middle boxes.fig = plt.figure()  ax = fig.add_subplot(111)ax.imshow(X, cmap = plt.cm.gray,          interpolation ='nearest')ax.add_patch( Rectangle((0.5, 0.5),                        2, 2,                        fc ='none',                         ec ='g',                        lw = 10) )  plt.show()
Output:Example 2:
import matplotlibimport matplotlib.pyplot as plt    fig = plt.figure()ax = fig.add_subplot(111)  rect1 = matplotlib.patches.Rectangle((-200, -100),                                     400, 200,                                     color ='green')  rect2 = matplotlib.patches.Rectangle((0, 150),                                     300, 20,                                     color ='pink')  rect3 = matplotlib.patches.Rectangle((-300, -50),                                     40, 200,                                     color ='yellow')  ax.add_patch(rect1)ax.add_patch(rect2)ax.add_patch(rect3)  plt.xlim([-400, 400])plt.ylim([-400, 400])  plt.show()
Output:
Matplotlib patches-class
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Enumerate() in Python
Python Dictionary
Python OOPs Concepts
Different ways to create Pandas Dataframe
Convert integer to string in Python
Convert string to integer in Python
Python infinity
Matplotlib.pyplot.title() in Python
How to set input type date in dd-mm-yyyy format using HTML ?
How to set the opacity of background image in CSS ?

26 Mar, 2021
In this article, we are going to see how to set the opacity of a background image in CSS. Opacity can be defined as the quality of lacking transparency. It can be used to define the amount of content to be visible.
Approach: We can use the opacity property in CSS which is used to change the opacity of an element. The value of the property can be set in a range of 0 to 1, where “0” is fully transparent and “1” is opaque. Any decimal value can be used in between to set the opacity accordingly.
Syntax:
opacity: value;
Example: In this example, we will set a background image to the <div> and use the opacity property to set the opacity of this image. The opacity is set to 0.2 so that the background is made transparent and the text on top of the image is clearly visible.
HTML
<!DOCTYPE html><html>  <head>    <title>        How to change opacity of        background image in CSS ?    </title>      <style>        #GFG {            height: 100vh;            display: flex;            align-items: center;            justify-content: center;        }          #GFG::before {            content: "";            position: absolute;            top: 0px;            right: 0px;            bottom: 0px;            left: 0px;              /* Specify the background image to be used */            background-image: url('https://media.geeksforgeeks.org/wp-content/uploads/20210313130410/exbg.png');            background-size: cover;              /* Specify the background image */            opacity: 0.2;        }    </style></head>  <body>    <div id="GFG">        <h2>Background image with opacity</h2>    </div></body>  </html>
Output:
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
Python EasyGUI – Showing Image in a Button Box

05 Sep, 2020
In this article we will see how we can add or show image in the button box. Button box is used to display a window having multiple buttons in EasyGUI, it can be used where there is condition to select one among lot of buttons for example buttons in lift at a time user can opt only one option, below is how the normal button box looks like
When we invoke the buttonbox function (or other functions that display a button box, such as msgbox, indexbox, ynbox, etc.), we can specify the keyword argument image=img where img is the filename of an image. The file can be .gif. Usually, we can use other images such as .png.
In order to do this we will use buttonbox method
Syntax : buttonbox(text, title, image=img, choices=button_list)
Argument : It takes 4 arguments, first string i.e text to be displayed, second string i.e title of the window and third and forth is keyword argument which is image source and the button choices
Return : It returns the text of the button that the user selected
Example :In this we will create a button box with a image, and user will be allowed to select any button and message will appear according to the message, below is the implementation
# importing easygui modulefrom easygui import *  # message to be displayedtext = "Message to be displayed on the window GfG"  # window titletitle = "Window Title GfG"  # button listbutton_list = []  # button 1button1 = "Average"  # second buttonbutton2 = "Good"  # third buttonbutton3 = "Very Good"  # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3)  img = "gfg.png"  # creating a button boxoutput = buttonbox(text, title, image = img, choices = button_list)  # title for the message boxtitle = "Message Box"  # message message = "You selected : " + output  # creating a message box msg = msgbox(message, title)
Output :
Another Example :
# importing easygui modulefrom easygui import *  # message to be displayedtext = "How much do you like the image given below"  # window titletitle = "Window Title GfG"  # button listbutton_list = []  # button 1button1 = "Average"  # second buttonbutton2 = "Good"  # third buttonbutton3 = "Very Good"  # appending button to the button listbutton_list.append(button1)button_list.append(button2)button_list.append(button3)  # a image of a dogimg = "dog_image.png"  # creating a button boxoutput = buttonbox(text, title, image = img, choices = button_list)  # title for the message boxtitle = "Message Box"  # message message = "You selected : " + output  # creating a message box msg = msgbox(message, title)
Output :
Python-EasyGUI
Python-gui
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
How can I find non-ASCII characters in MySQL?

Non ASCII characters are characters such as the pound symbol(£), trademark symbol, plusminus
symbol etc. To find the non-ASCII characters from the table, the following steps are required −
First a table is created with the help of the create command which is given as follows −
mysql> CREATE table NonASciiDemo
-> (
-> NonAScii varchar(100)
-> );
Query OK, 0 rows affected (0.61 sec)
After that the records are inserted into the table with the help of the insert command which is as
follows −
mysql> INSERT into NonASciiDemo values('-,-');
Query OK, 1 row affected (0.18 sec)

mysql> INSERT into NonASciiDemo values('  ');
Query OK, 1 row affected (0.23 sec)

mysql> INSERT into NonASciiDemo values('£');
Query OK, 1 row affected (0.30 sec)

mysql> INSERT into NonASciiDemo values('123abcd£');
Query OK, 1 row affected (0.24 sec)
Four records are inserted into the table as shown above in which two records contain non ASCII
characters and two records contain ASCII characters.
To display allthe records, select command is used as follows −
SELECT * from NonASciiDemo;

The following is the output
+----------+
| NonAScii |
+----------+
| -,-      |
|          |
| £        |
| 123abcd£ |
+----------+
4 rows in set (0.00 sec)
The syntax to find the non ASCII characters is given as follows −
SELECT * FROM yourTableName WHERE NOT HEX(yourColumnName) REGEXP '^([0-7][0-
9A-F])*$';
The query to get the non ASCII characters using the above syntax is given as follows −
mysql> SELECT * FROM NonASciiDemo WHERE NOT HEX(NonAScii) REGEXP '^([0-7][0-9AF])*$';

The following is the output of the above query −
+----------+
| NonAScii |
+----------+
| £        |
| 123abcd£ |
+----------+
2 rows in set (0.00 sec)
Puppeteer - Device Emulation

We can run tests with mobile configurations in Puppeteer and check the responsive property of a webpage. The list of devices that the Puppeteer supports can be obtained from the Chrome DevTools. Right-click on a page opened in the Chrome browser, then select Inspect.
Then, click on the Toggle Device Toolbar.
Click on the dropdown - Responsive to get the list of devices.
To emulate a device, we have to use the method emulate() and the device to be emulated is passed as a parameter to this method. The syntax for this method is as follows −
const m = puppeteer.devices['iPhone X']
//emulate iPhoneX
await page.emulate(m)

Let us emulate the device iPhone X using the emulate function in Puppeteer.
To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −
Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).
The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.
Right-click on the folder where the node_modules folder is created, then click on the New file button.
Step 2 − Enter a filename, say testcase1.js.
Step 3 − Add the below code within the testcase1.js file created.
//Puppeteer library
const puppeteer = require('puppeteer')
//launch browser in headed mode
puppeteer.launch({headless:false}).then(async browser => {
   //browser new page
   const page = await browser.newPage()
   //set device to iPhone X
   const m = puppeteer.devices['iPhone X']
   //emulate iPhoneX
   await page.emulate(m)
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //capture screenshot of emulated device
   await page.screenshot({ path: 'iPhoneDevice.png'})
   //browser close
   await browser.close()
})
Step 4 − Execute the code with the command given below −
node <filename>

So in our example, we shall run the following command −
node testcase1.js

After the command has been successfully executed, a new file called the iPhoneDevice.png gets created within the page directory. It contains the captured screenshot of the emulated webpage for the iPhone X device.
 Print
 Add Notes
 Bookmark this page
scipy stats.cauchy() | Python - GeeksforGeeks

20 Mar, 2019
scipy.stats.cauchy() is an cauchy continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : cauchy continuous random variable
Code #1 : Creating cauchy continuous random variable
# importing scipyfrom scipy.stats import cauchy  numargs = cauchy.numargs[] = [0.6, ] * numargsrv = cauchy()  print ("RV : \n", rv) 
Output :
RV : 
 <scipy.stats._distn_infrastructure.rv_frozen object at 0x000002948548C6D8>

Code #2 : cauchy random variates and probability distribution function.
import numpy as npquantile = np.arange (0.01, 1, 0.1)  import numpy as npimport matplotlib.pyplot as plt  distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print("Distribution : \n", distribution)  plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Random Variates : 
 [ 2.73388202  4.88389383 -4.89271415  4.63864536 -0.36933865  1.51521875
  1.43853452 -0.69619917 -0.68358229  4.13179831]

Probability Distribution : 
 [0.31827806 0.31450438 0.30486533 0.29040223 0.27250226 0.25260685
 0.23198738 0.21162814 0.19220451 0.17412061]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt  distribution = np.linspace(0, np.minimum(rv.dist.b, 5))print("Distribution : \n", distribution)  plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Distribution : 
Distribution : 
 [0.         0.10204082 0.20408163 0.30612245 0.40816327 0.51020408
 0.6122449  0.71428571 0.81632653 0.91836735 1.02040816 1.12244898
 1.2244898  1.32653061 1.42857143 1.53061224 1.63265306 1.73469388
 1.83673469 1.93877551 2.04081633 2.14285714 2.24489796 2.34693878
 2.44897959 2.55102041 2.65306122 2.75510204 2.85714286 2.95918367
 3.06122449 3.16326531 3.26530612 3.36734694 3.46938776 3.57142857
 3.67346939 3.7755102  3.87755102 3.97959184 4.08163265 4.18367347
 4.28571429 4.3877551  4.48979592 4.59183673 4.69387755 4.79591837
 4.89795918 5.        ]
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as pltimport numpy as np  x = np.linspace(0, 1.0, 100)  # Varying positional argumentsy1 = cauchy.pdf(x, 2.75, 2.75)y2 = cauchy.pdf(x, 3.25, 3.25)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
sum() function in Python
random.getstate() in Python - GeeksforGeeks

27 Jul, 2021
random() module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. 
The getstate() method of the random module returns an object with the current internal state of the random number generator. This object can be passed to the setstate() method to restore the state. There are no parameters passed in this method.Example 1: 
Python3
import random  # remember this statestate = random.getstate() # print 10 random numbersprint(random.sample(range(20), k = 10)) # restore staterandom.setstate(state) # print same first 5 random numbers# as aboveprint(random.sample(range(20), k = 5))
Output: 
[16, 1, 0, 11, 19, 3, 7, 5, 10, 13]
[16, 1, 0, 11, 19]
Example 2:  
Python3
import random    list1 = [1, 2, 3, 4, 5, 6]      # Get the statestate = random.getstate() # prints a random value from the listprint(random.choice(list1))   # Set the staterandom.setstate(state) # prints the same random value# from the listprint(random.choice(list1))
Output: 
3
3
 
akshaysingh98088
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe
Python | Thresholding techniques using OpenCV | Set-3 (Otsu Thresholding) - GeeksforGeeks

29 May, 2019
In the previous posts, Simple Thresholding and Adaptive Thresholding were explained. In Simple Thresholding, the global value of threshold was used which remained constant throughout. In Adaptive thresholding, the threshold value is calculated for smaller regions with different threshold values for different regions with respect to the change in lighting.
In Otsu Thresholding, a value of the threshold isn’t chosen but is determined automatically. A bimodal image (two distinct image values) is considered. The histogram generated contains two peaks. So, a generic condition would be to choose a threshold value that lies in the middle of both the histogram peak values.
We use the Traditional cv2.threshold function and use cv2.THRESH_OTSU as an extra flag.
Syntax: cv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)
Parameters:-> source: Input Image array (must be in Grayscale).-> thresholdValue: Value of Threshold below and above which pixel values will change accordingly.-> maxVal: Maximum value that can be assigned to a pixel.-> thresholdingTechnique: The type of thresholding to be applied.
Below is the Python code explaining Otsu Thresholding Technique –
# Python program to illustrate# Otsu thresholding type on an image  # organizing importsimport cv2         import numpy as np      # path to input image is specified and# image is loaded with imread commandimage1 = cv2.imread('input1.jpg')  # cv2.cvtColor is applied over the# image input with applied parameters# to convert the image in grayscaleimg = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)  # applying Otsu thresholding# as an extra flag in binary # thresholding     ret, thresh1 = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY +                                             cv2.THRESH_OTSU)       # the window showing output image         # with the corresponding thresholding         # techniques applied to the input image    cv2.imshow('Otsu Threshold', thresh1)                # De-allocate any associated memory usage         if cv2.waitKey(0) & 0xff == 27:    cv2.destroyAllWindows()     
Input:
Output:
The calculation accepts that the picture contains two classes of pixels following foreground and background pixels, it at that point ascertains the ideal limit isolating the two classes with the goal that their consolidated spread is insignificant.
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Dart Programming - Substring Method

Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive.
substring(int startIndex, [ int endIndex ])

startIndex − the index to start extracting from(inclusive).
startIndex − the index to start extracting from(inclusive).
endIndex − the index to stop extracting (exclusive).
endIndex − the index to stop extracting (exclusive).
Note − Indexes are zero based, i.e., the first character will have the index 0 and so on.
Returns a string.
void main() { 
   String str1 = "Hello World"; 
   print("New String: ${str1.substring(6)}"); 
   
   // from index 6 to the last index 
   print("New String: ${str1.substring(2,6)}"); 
   
   // from index 2 to the 6th index 
} 
It will produce the following output −.
New String: World 
New String: llo 


    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 create SVG graphics using JavaScript?

All modern browsers support SVG and you can easily create it using JavaScript. Google Chrome and Firefox both support SVG.
With JavaScript, create a blank SVG document object model (DOM). Using attributes, create a shape like a circle or a rectangle.
var mySvg = "http://www.w3.org/2000/svg";
var myDoc = evt.target.ownerDocument;

var myShape = svgDocument.createElementNS(mySvg, "circle");

myShape.setAttributeNS(null, "cx", 40);
myShape.setAttributeNS(null, "cy", 40);
myShape.setAttributeNS(null, "r", 30);

myShape.setAttributeNS(null, "fill", "yellow");