code-rag-bench/online-tutorials huggingface dataset:
Python - Elements frequency in Tuple - GeeksforGeeks

04 Sep, 2021
Given a Tuple, find frequency of each element.
Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on..Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on..  
Method #1  Using defaultdict()
In this, we perform task of getting all elements and assigning frequency using defaultdict which maps each element with key and then frequency can be incremented.
Python3
# Python3 code to demonstrate working of# Elements frequency in Tuple# Using defaultdict()from collections import defaultdict # initializing tupletest_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4) # printing original tupleprint("The original tuple is : " + str(test_tup)) res = defaultdict(int)for ele in test_tup:         # incrementing frequency    res[ele] += 1 # printing resultprint("Tuple elements frequency is : " + str(dict(res)))
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
Method #2 : Using Counter()
This is straight forward way to solve this problem. In this, we just employ this function and it returns frequency of elements in container, in this case tuple.
Python3
# Python3 code to demonstrate working of# Elements frequency in Tuple# Using Counter()from collections import Counter # initializing tupletest_tup = (4, 5, 4, 5, 6, 6, 5, 5, 4) # printing original tupleprint("The original tuple is : " + str(test_tup)) # converting result back from defaultdict to dictres = dict(Counter(test_tup)) # printing resultprint("Tuple elements frequency is : " + str(res))
The original tuple is : (4, 5, 4, 5, 6, 6, 5, 5, 4)
Tuple elements frequency is : {4: 3, 5: 4, 6: 2}
sooda367
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python - Johnson SB Distribution in Statistics - GeeksforGeeks

10 Jan, 2020
scipy.stats.johnsonsb() is a Johnson SB 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 : Johnson SB continuous random variable
Code #1 : Creating Johnson SB continuous random variable
# importing library  from scipy.stats import johnsonsb      numargs = johnsonsb.numargs a, b = 4.32, 3.18rv = johnsonsb(a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D50286C8

Code #2 : Johnson SB continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = johnsonsb.rvs(a, b, scale = 2, size = 10) print ("Random Variates : \n", R)   # PDF R = johnsonsb.pdf(a, b, quantile, loc = 0, scale = 1) print ("\nProbability Distribution : \n", R)  
Output :
Random Variates : 
 [0.42212956 0.60876766 0.35494705 0.42892958 0.25316345 0.51872977
 0.2355019  0.44657975 0.54971277 0.36683771]

Probability Distribution : 
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]

Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.02040816 0.04081633 0.06122449 0.08163265 0.10204082
 0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898
 0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878
 0.36734694 0.3877551  0.40816327 0.42857143 0.44897959 0.46938776
 0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673
 0.6122449  0.63265306 0.65306122 0.67346939 0.69387755 0.71428571
 0.73469388 0.75510204 0.7755102  0.79591837 0.81632653 0.83673469
 0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367
 0.97959184 1.        ]
 
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np      x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = johnsonsb .pdf(x, 1, 3) y2 = johnsonsb .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
C++ Program for GCD of more than two (or array) numbers - GeeksforGeeks

04 Dec, 2018
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers.
gcd(a, b, c) = gcd(a, gcd(b, c)) 
             = gcd(gcd(a, b), c) 
             = gcd(gcd(a, c), b)

// C++ program to find GCD of two or// more numbers#include <bits/stdc++.h>using namespace std;  // Function to return gcd of a and bint gcd(int a, int b){    if (a == 0)        return b;    return gcd(b % a, a);}  // Function to find gcd of array of// numbersint findGCD(int arr[], int n){    int result = arr[0];    for (int i = 1; i < n; i++)        result = gcd(arr[i], result);      return result;}  // Driven codeint main(){    int arr[] = { 2, 4, 6, 8, 16 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << findGCD(arr, n) << endl;    return 0;}
2

Please refer complete article on GCD of more than two (or array) numbers for more details!
GCD-LCM
C++ Programs
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
HashSet spliterator() method in Java - GeeksforGeeks

10 Dec, 2018
The spliterator() method of HashSet returns a Spliterator with the same elements as HashSet. The returned Spliterator is late-binding and fail-fast Spliterator. A late-binding Spliterator binds to the source of elements means HashSet at the point of first traversal, first split, or first query for estimated size, rather than at the time the Spliterator is created. It can be used with Streams in Java 8. Also it can traverse elements individually and in bulk too. Spliterator is better way to traverse over element because it provides more control on elements.
Syntax:
public Spliterator<E> spliterator()
Returns: This method returns a Spliterator over the elements in HashSet.
Below programs illustrate spliterator() method of HashSet:
Example 1: To demonstrate spliterator() method on HashSet which contains a set of Numbers.
// Java Program Demonstrate spliterator()// method of HashSet  import java.util.*;public class GFG {      public static void main(String[] args)    {          // create an HashSet which going to        // contains a list of Numbers        HashSet<Integer> Numbers = new HashSet<Integer>();          // Add Number to list        Numbers.add(23);        Numbers.add(32);        Numbers.add(45);        Numbers.add(63);          // using spliterator() method        Spliterator<Integer> numbers = Numbers.spliterator();          // print result from Spliterator        System.out.println("list of Numbers:");          // forEachRemaining method of Spliterator        numbers.forEachRemaining((n) -> System.out.println(n));    }}
list of Numbers:
32
23
45
63

Example 2: To demonstrate spliterator() method on HashSet which contains set of Students Names.
// Java Program Demonstrate spliterator()// method of HashSet  import java.util.*;public class GFG {      public static void main(String[] args)    {          // create an HashSet which going to        // contains a list of string values        HashSet<String> students = new HashSet<String>();          // Add Strings to list        students.add("Ram");        students.add("Mohan");        students.add("Sohan");        students.add("Rabi");          // using spliterator() method        Spliterator<String> names = students.spliterator();          // print result from Spliterator        System.out.println("list of Students:");          // forEachRemaining method of Spliterator        names.forEachRemaining(            (n) -> System.out.println("Student Name: " + n));    }}
list of Students:
Student Name: Rabi
Student Name: Mohan
Student Name: Sohan
Student Name: Ram

Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html#spliterator–
Java - util package
java-basics
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
Node.js MySQL LENGTH() Function - GeeksforGeeks

07 Oct, 2021
LENGTH() Function is a Builtin function in MySQL which is used to get length of given string in bytes.
Syntax:
LENGTH(input_string)
Parameters: LENGTH() function accepts a single parameter as mentioned above and described below.
input_string: We will get number of characters of this string
Return Value: LENGTH() function returns length of given string in bytes.
Modules:
mysql: To handle MySQL Connection and Queries
npm install mysql
SQL publishers Table Preview:
Example 1:
Javascript
const mysql = require("mysql");  let db_con = mysql.createConnection({  host: "localhost",  user: "root",  password: "",  database: "gfg_db",});  db_con.connect((err) => {  if (err) {    console.log("Database Connection Failed !!!", err);    return;  }    console.log("We are connected to gfg_db database");    // here is the query  let query = `SELECT LENGTH('Geeks for Geeks') AS length_in_bytes`;    db_con.query(query, (err, rows) => {    if (err) throw err;      console.log(rows);  });});
Output:
Example 2:
Javascript
const mysql = require("mysql");  let db_con = mysql.createConnection({  host: "localhost",  user: "root",  password: "",  database: "gfg_db",});  db_con.connect((err) => {  if (err) {    console.log("Database Connection Failed !!!", err);    return;  }    console.log("We are connected to gfg_db database");    // here is the query  let query = `SELECT name, LENGTH(name) AS length_in_bytes FROM publishers`;    db_con.query(query, (err, rows) => {    if (err) throw err;      console.log(rows);  });});
Output:
NodeJS-MySQL
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect Node.js with React.js ?
Node.js Export Module
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Remove elements from a JavaScript Array
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
Difference between var, let and const keywords in JavaScript
numpy.intersect1d() function in Python - GeeksforGeeks

17 May, 2020
numpy.intersect1d() function find the intersection of two arrays and return the sorted, unique values that are in both of the input arrays.
Syntax: numpy.intersect1d(arr1, arr2, assume_unique = False, return_indices = False)
Parameters :arr1, arr2 : [array_like] Input arrays.assume_unique : [bool] If True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.return_indices : [bool] If True, the indices which correspond to the intersection of the two arrays are returned. The first instance of a value is used if there are multiple. Default is False.
Return : [ndarray] Sorted 1D array of common and unique elements.
Code #1 :
# Python program explaining# numpy.intersect1d() function     # importing numpy as geek import numpy as geek     arr1 = geek.array([1, 1, 2, 3, 4])arr2 = geek.array([2, 1, 4, 6])    gfg = geek.intersect1d(arr1, arr2)    print (gfg)
Output :
[1 2 4]

 Code #2 :
# Python program explaining# numpy.intersect1d() function     # importing numpy as geek import numpy as geek     arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]arr2 = [1, 3, 5, 7, 9]    gfg = geek.intersect1d(arr1, arr2)    print (gfg)
Output :
[1 3 5 7 9]

Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
Check if element exists in list in Python
Create a Pandas DataFrame from Lists
sum() function in Python
Managing Instance Attributes in Python | by Sadrach Pierre, Ph.D. | Towards Data Science

Often times in the implementation of a python class, it would be useful if we could easily add extra processing to getting and/or setting an instance attribute. For example, it would be useful to be able to perform type checking or some other form of validating during getting/setting instance attributes. In this post, we will discuss how to manage instance attributes in python.
Let’s get started!
Suppose we have a class called ‘Cars’ with an attribute called ‘car_brand’:
class Car:    def __init__(self, car_brand):       self.car_brand = car_brand
Let’s initialize a car class instance as a ‘Tesla’:
car1 = Car('Tesla')print("Car brand:", car1.car_brand)
While this works fine, if we initialize an instance with a bad input value for ‘car_brand’, there is no data validation or type checking. For example, if we initialize a car instance with a car brand value of the number 500:
car2 = Car(500)print("Car brand:", car2.car_brand)
we should have a way of validating the type of this instance attribute. We can customize access to attributes by defining the ‘car_brand’ attribute as a ‘property’:
class Car:    ...    @property    def car_brand(self):        return self._car_brand
Defining ‘car_brand’ as a ‘property’ allows us to attach setter and deleter functions to our ‘car_brand’ property. Let’s add a setter method to our ‘car_brand’ attribute that raises an error if the instance is initialized with a value that is not a string:
class Car:    ...    #setter function    @car_brand.setter    def car_brand(self, value):        if not isinstance(value, str):            raise TypeError('Expected a string')        self._car_brand = value
Let’s define our instance again, with our integer input 500:
car2 = Car(500)print("Car brand:", car2.car_brand)
Another instance management operation to consider is the deletion of instance attributes. If we look at our initial instance:
car1 = Car('Tesla')print("Car brand:", car1.car_brand)
We can easily delete the attribute value:
car1 = Car('Tesla')print("Car brand:", car1.car_brand)del car1.car_brandprint("Car brand:", car1.car_brand)
We can add a deleter function that raises an error upon attempted deletion:
class Car:    ...    #deleter function    @car_brand.deleter    def car_brand(self):        raise AttributeError("Can't delete attribute")
Let’s try to set and delete the attribute value once again:
car1 = Car('Tesla')print("Car brand:", car1.car_brand)del car1.car_brand
I’ll stop here but feel free to play around with the code yourself.
To summarize, in this post we discussed how to manage instance attributes in python classes. We showed that by defining a class attribute as a ‘property’ we can attach setter and deleter functions that help us manage the access of attributes. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
What is type conversion in java?

Java provides various datatypes to store various data values. It provides 7 primitive datatypes (stores single values) as listed below −
boolean − Stores 1-bit value representing true or, false.
byte − Stores twos compliment integer up to 8 bits.
char − Stores a Unicode character value up to 16 bits.
short − Stores an integer value upto 16 bits.
int − Stores an integer value upto 32 bits.
long − Stores an integer value upto 64 bits.
float − Stores a floating point value upto 32bits.
double − Stores a floating point value up to 64 bits.
Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and, Narrowing.
Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other.
public class WideningExample {
   public static void main(String args[]){
      char ch = 'C';
      int i = ch;
      System.out.println(i);
   }
}
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion is not done automatically, you need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be compatible with each other.
import java.util.Scanner;
public class NarrowingExample {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int i = sc.nextInt();
      char ch = (char) i;
      System.out.println("Character value of the given integer: "+ch);
   }
}
Enter an integer value:
67
Character value of the given integer: C
Top-level script environment in Python (__main__)

A module object is characterized by various attributes. Attribute names are prefixed and post-fixed by double underscore __. The most important attribute of module is __name__. When Python is running as a top level executable code, i.e. when read from standard input, a script, or from an interactive prompt the __name__ attribute is set to '__main__'.
>>> __name__
'__main__'
From within a script also, we find a value of __name__ attribute is set to '__main__'. Execute the following script.
'module docstring'
print ('name of module:',__name__)
Output
name of module: __main__
However, for an imported module this attribute is set to name of the Python script. For hello.py module
>>> import hello
>>> hello.__name__
hello
As seen earlier, the value of __name__ is set to __main__ for top-level module. However, for the imported module it is set to name of a file. Run following script (moduletest.py)
import hello
print ('name of top level module:', __name__)
print ('name of imported module:', hello.__name__)
Output
name of top level module: __main__
name of imported module: hello
A Python script containing function may also have a certain executable code. Hence if we import it its code will be run automatically. We have this script messages.py with two functions. In executable part user input is provided as an argument to thanks() function.
def welcome(name):
print ("Hi {}. Welcome to TutorialsPoint".format(name))
return
def thanks(name):
print ("Thank you {}. See you again".format(name))
name = input('enter name:')
thanks(name)
Obviously when we run messages.py output shows a thanks message as below.
enter name:Ajit
Thank you Ajit. See you again
We have a moduletest.py script as below.
import messages
print ('name of top level module:', __name__)
print ('name of imported module:', messages.__name__)
Now we if we run the moduletest.py script, We'll find that the input statement and call to welcome() will be executed.
c:\python37>python moduletest.py
Output
enter name:Kishan
Thank you Kishan. See you again
enter name:milind
Hi milind. Welcome to TutorialsPoint
This is an output of both the scripts. But want to import function from messages module but not the executable code in it.
This is where the fact that value of __name__attribute of top-level script is __main__ is useful. Change messages.py script such that it executes input and function call statement only if __name__ is equal to __main__.
"docstring of messages module"
def welcome(name):
print ("Hi {}. Welcome to TutorialsPoint".format(name))
return
def thanks(name):
print ("Thank you {}. See you again".format(name))
if __name__=='__main__':
name = input('enter name')
thanks(name)
Use above technique whenever you want a module that can be executed as well as imported. The moduletest.py doesn't require any changes. An executable part in messages module won't run now.
enter name: milind
Hi milind. Welcome to TutorialsPoint
Note that this doesn't prevent you from running messages.py script independently.
Java Regex - PatternSyntaxException Class

The java.util.regex.PatternSyntaxException class represents a unchecked exception thrown to indicate a syntax error in a regular-expression pattern.
Following is the declaration for java.util.regex.PatternSyntaxException class −
public class PatternSyntaxException
   extends IllegalArgumentException

Constructs a new instance of this class.
Retrieves the description of the error.
Retrieves the error index.
Returns a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.
Retrieves the erroneous regular-expression pattern.
This class inherits methods from the following classes −
Java.lang.Throwable
Java.lang.Object
The following example shows the usage of java.util.regex.Pattern.PatternSyntaxException class methods.
package com.tutorialspoint;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class PatternSyntaxExceptionDemo {
   private static String REGEX = "[";
   private static String INPUT = "The dog says meow " + "All dogs say meow.";
   private static String REPLACE = "cat";

   public static void main(String[] args) {
      try{
         Pattern pattern = Pattern.compile(REGEX);
         
         // get a matcher object
         Matcher matcher = pattern.matcher(INPUT); 
         INPUT = matcher.replaceAll(REPLACE);
      } catch(PatternSyntaxException e){
         System.out.println("PatternSyntaxException: ");
         System.out.println("Description: "+ e.getDescription());
         System.out.println("Index: "+ e.getIndex());
         System.out.println("Message: "+ e.getMessage());
         System.out.println("Pattern: "+ e.getPattern());
      }
   }
}
Let us compile and run the above program, this will produce the following result −
PatternSyntaxException: 
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [

 Print
 Add Notes
 Bookmark this page
C++ Program to Check Whether a character is Vowel or Consonant

Vowels are the alphabets a, e, i, o, u. All the rest of the alphabets are known as consonants.
The program to check if a character is a vowel or consonant is as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   char c = 'a';
   if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
   cout <<c<< " is a Vowel" << endl;
   else
   cout <<c<< " is a Consonant" << endl;
   return 0;
}
a is a Vowel
In the above program, an if statement is used to find if the character is a, e, i, o or u. If it is any of these, it is a vowel. Otherwise, it is a consonant.
This is shown in the below code snippet.
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
cout <<c<< " is a Vowel" << endl;
else
cout <<c<< " is a Consonant" << endl;
The above program checks only for lower case characters. So, a program that checks for upper case as well as lower case characters is as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   char c = 'B';
   if (c == 'a' || c == 'e' || c == 'i' ||
   c == 'o' || c == 'u' || c == 'A' ||
   c == 'E' || c == 'I' || c == 'O' || c == 'U')
   cout <<c<< " is a Vowel" << endl;
   else
   cout <<c<< " is a Consonant" << endl;
   return 0;
}
B is a Consonant
In the above program, an if statement is used to find if the character is a, e, i, o or u (both in upper case as well as lower case).. If it is any of these, it is a vowel. Otherwise, it is a consonant.
if (c == 'a' || c == 'e' || c == 'i' ||
c == 'o' || c == 'u' || c == 'A' ||
c == 'E' || c == 'I' || c == 'O' || c == 'U')
cout <<c<< " is a Vowel" << endl;
else
cout <<c<< " is a Consonant" << endl;
How to change image on hover with CSS ? - GeeksforGeeks

26 Nov, 2020
The approach of this article is to change an image when the user hovering the mouse over it. This task can be simply done by using the CSS background-image property in combination with the :hover pseudo-class to replace or change the image on mouseover. 
Example:
HTML
<!DOCTYPE html><html lang="en">  <head>    <title>        How to Change Image on         Hover in CSS    </title>          <style>        .sudo {            width: 230px;            height: 195px;            margin: 50px;            background-image: url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png");        }          .sudo:hover {            background-image: url("https://media.geeksforgeeks.org/wp-content/uploads/rk.png");        }    </style></head>  <body>    <h2>GeeksForGeeks</h2>      <h2>        How to change image on         hover with CSS    </h2>      <div class="sudo"></div></body>  </html>
Output:
Before hovering the mouse over the image:
After hovering the mouse over the image: 
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
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 web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to get element-wise true division of an array using Numpy? - GeeksforGeeks

02 Sep, 2020
True Division in Python3 returns a floating result containing the remainder of the division. To get the true division of an array, NumPy library has a function numpy.true_divide(x1, x2). This function gives us the value of true division done on the arrays passed in the function. To get the element-wise division we need to enter the first parameter as an array and the second parameter as a single element.
Syntax: np.true_divide(x1,x2) Parameters:
x1: The dividend array
x2: divisor (can be an array or an element)
Return: If inputs are scalar then scalar; otherwise array with arr1 / arr2(element- wise) i.e. true division
Now, let’s see an example:
Example 1: 
Python3
# import libraryimport numpy as np  # create 1d-arrayx = np.arange(5)  print("Original array:",       x)  # apply true division # on each array elementrslt = np.true_divide(x, 4)  print("After the element-wise division:",       rslt)
Output :
Original array: [0 1 2 3 4]
After the element-wise division: [0.   0.25 0.5  0.75 1.  ]
Example 2: 
Python3
# import libraryimport numpy as np  # create a 1d-arrayx = np.arange(10)  print("Original array:",       x)  # apply true division # on each array elementrslt = np.true_divide(x, 3)  print("After the element-wise division:",      rslt)
Output:
Original array: [0 1 2 3 4 5 6 7 8 9]After the element-wise division: [0. 0.33333333 0.66666667 1. 1.33333333 1.666666672. 2.33333333 2.66666667 3. ]
Python numpy-Mathematical Function
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?
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()
How to display a specific field in array using $project in MongoDB and ignore other fields?

To display a specific field, use $project along with $unwind. To ignore a field, set to 0. Let us create a collection with documents −
> db.demo731.insertOne({ "ProductInformation": [ { ProductId:"Product-1", ProductPrice:80 }, { ProductId:"Product-2", ProductPrice:45 }, { ProductId:"Product-3", ProductPrice:50 } ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eac5efd56e85a39df5f6341")
}
Display all documents from a collection with the help of find() method −
> db.demo731.find();
This will produce the following output −
{ "_id" : ObjectId("5eac5efd56e85a39df5f6341"), "ProductInformation" : [ { "ProductId" : "Product-1", "ProductPrice" : 80 }, { "ProductId" : "Product-2", "ProductPrice" : 45 }, { "ProductId" : "Product-3", "ProductPrice" : 50 } ] }
Following is the query to display a specific field in array using $project in MongoDB −
> db.demo731.aggregate([
...    { $unwind: "$ProductInformation" },
...    { $match: { "ProductInformation.ProductPrice": 80} },
...    { $project: {_id: 0,"ProductInformation.ProductPrice":0}}
... ])
This will produce the following output −
{ "ProductInformation" : { "ProductId" : "Product-1" } }
How to use an HTML tag inside HTML table?

With HTML, you can easily add HTML tag inside a table. The tag should open and close inside the <td> tag. For example, adding a paragraph <p>...</> tag or even a list tag i.e. <ul>...<ul>.
You can try to run the following code to use an HTML tag <ul>...</ul> inside HTML table
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td { border: 1px solid black; width: 400px; }
      </style>
   </head>
   <body>
      <h1> Total Points</h1>
      <table>
         <tr>
            <th>Technologies</th>
            <th>Points</th>
         </tr>
         <tr>
            <td>Programming Languages
               <ul>
                  <li>C++</li>
                  <li>Java</li>
                  <li>C</li>
               </ul>
            </td>
            <td>100</td>
         </tr>
         <tr>
            <td>Database
               <ul>
                  <li>MySQL</li>
                 <li>Oracle</li>
                 <li>CouchDB</li>
              </ul>
           </td>
           <td>50</td>
        </tr>
     </table>
   </body>
</html>
How to add comments in MySQL Code?

We can add comments in MySQL with the help of # symbol. Whenever we write # symbol before any sentence, the whole line will be ignored by MySQL.
MySQL supports three type of comments −
1. With the help of # symbol
mysql> create table CommentDemo
   -> (
   -> id int   #Id is an integer type
   -> );
Query OK, 0 rows affected (0.65 sec
Above, we have set the comment as
#Id is an integer type

2. With the help of -- symbol
mysql> create table CommentDemo2
   -> (
   -> id int -- id is an integer type
   -> );
Query OK, 0 rows affected (0.49 sec)
Above, we have set the comment as −
- id is an integer type

3. With the help of /*  */ symbol
This is for multiple line comments, same as C or C++ language.
mysql> create table CommentDemo3
   -> (
   -> /*id is an integer type */
   -> id int
   -> );
Query OK, 0 rows affected (0.52 sec)
Above, we have set multi-line comment as
/*id is an integer type */
How to change the orientation and font size of x-axis labels using ggplot2 in R?

This can be done by using theme argument in ggplot2
> df <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])),
y=rnorm(10,0.5))
> df
        x            y
1 long text label a -0.8080940
2 long text label b 0.2164785
3 long text label c 0.4694148
4 long text label d 0.7878956
5 long text label e -0.1836776
6 long text label f 0.7916155
7 long text label g 1.3170755
8 long text label h 0.4002917
9 long text label i 0.6890988
10 long text label j 0.6077572
Plot is created as follows −
> library(ggplot2)
> ggplot(df, aes(x=x, y=y)) + geom_point() +
   theme(text = element_text(size=20),
      axis.text.x = element_text(angle=90, hjust=1))
How to Save Output of Command in a File in Linux?

17 Mar, 2021
When we run a command on a terminal on Linux it generates some output of that command. Sometimes we need the output result of the commands. Today we are going to see how to save the output of the command.
We can use the redirections operators to save the output of commands into files. Redirection operators redirect the output of a command to the file instead of the output terminal. 
There are two main redirection operators in Linux:
>
>>
Example 1:
The first operator is “>” which is used to redirect the output of a command to the file, but this operator erases all existing data in that file and overwrites the command output, 
Let’s see one example of > redirection operator:
In the above image, we can see that the previous content of the output.txt file gets erased and the output of the ls command is written into the file.
Example 2:
Now let’s see about the second redirection operator is >>. Using this operator we can append the output of the command to the file. It does not erase any previous content of the file. 
Let’s see the example of >> operator
In the above image, we can see that the output of the command is appended to the output.txt file without erasing the content stored in that file.
If the file mentioned after the Redirection operator in not exist then it will create automatically.
When we use the redirection operator the output is going to the file only the redirection operator does not print it on the terminal. To see the output on the terminal and also save it into the file we can use the tee command. It sends the output of the file as well as to the terminal.
First, let’s see how to use the tee operator using the pipeline. Following is the syntax of using the tee operator:
command | tee outfile.txt
Now let’s see one example of the tee command:
We can see in the above image the output is redirected to the terminal as well as the output.txt file.
To append the output of the command to the file use the –a option with the tee command. Here is the syntax of the command:
command | tee outfile.txt
Now Let’s see one example of this command
In this image, we can see that the output of cowsay command is stored in the output.txt file without erasing the existing data of the file.
linux-command
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerator each_with_object function

06 Jan, 2020
The each_with_object function in Ruby is used to Iterate the given object’s each element.
Syntax: A.each_with_object({})Here, A is the initialised object.
Parameters: This function does not accept any parameters.
Returns: the new set of values.
Example 1:
# Calling the .each_with_object function on an array object[:gfg, :geeks, :geek].each_with_object({}) do |item, hash|  # Converting the array elements into its uppercase  hash[item] = item.to_s.upcaseend
Output:
{:gfg=>"GFG", :geeks=>"GEEKS", :geek=>"GEEK"}
Example 2:
# Calling the .each_with_object function on a hash{ foo: 2, bar: 4, jazz: 6 }.each_with_object({}) do |(key, value), hash|  # Getting the square of the hash's value  hash[key] = value**2end
Output:
{:foo=>4, :bar=>16, :jazz=>36}

Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array sample() function
Instance Variables in Ruby
Ruby | String empty? Method
Ruby | String concat Method
Ruby | unless Statement and unless Modifier
Ruby | Hash key() function
Ruby Integer times function with example
Ruby | Operators
Lambda Function - Ruby
Ruby | String reverse Method
SELECT increment counter in MySQL?

To select increment counter in MySQL, first you need to declare and initialize a variable. The syntax is as follows −
set @anyVariableName=0;
select yourColumnName,
@anyVariableName:=@anyVariableName+1 as anyVariableName
from yourTableName;
To understand the above syntax and set an increment counter, let us first create a table. The query to create a table is as follows.
mysql> create table incrementCounterDemo
-> (
-> Name varchar(100)
-> );
Query OK, 0 rows affected (1.01 sec)
Insert some records in the table using insert command. The query is as follows.
mysql> insert into incrementCounterDemo values('John');
Query OK, 1 row affected (0.18 sec)

mysql> insert into incrementCounterDemo values('Carol');
Query OK, 1 row affected (0.20 sec)

mysql> insert into incrementCounterDemo values('David');
Query OK, 1 row affected (0.14 sec)

mysql> insert into incrementCounterDemo values('Mike');
Query OK, 1 row affected (0.21 sec)

mysql> insert into incrementCounterDemo values('Bob');
Query OK, 1 row affected (0.12 sec)

mysql> insert into incrementCounterDemo values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from incrementCounterDemo;
The following is the output.
+-------+
| Name  |
+-------+
| John  |
| Carol |
| David |
| Mike  |
| Bob   |
| Sam   |
+-------+
6 rows in set (0.00 sec)
mysql> set @counter=0;
Query OK, 0 rows affected (0.00 sec)
Now select the increment counter.
mysql> select Name,
-> @counter:=@counter+1 as IncrementingValuebyOne
-> from incrementCounterDemo;
The following is the output.
+-------+------------------------+
| Name  | IncrementingValuebyOne |
+-------+------------------------+
| John  | 1                      |
| Carol | 2                      |
| David | 3                      |
| Mike  | 4                      |
| Bob   | 5                      |
| Sam   | 6                      |
+-------+------------------------+
6 rows in set (0.00 sec)
Vue.js v-once Directive

14 Jul, 2020
The v-once directive is a Vue.js directive that is used to avoid unwanted re-renders of an element. It treats the element as a static content after rendering it once for the first time. This improves performance as it does not have to be rendered again. First, we will create a div element with the id of choice. The v-once directive is then applied to this element to make it render only once.
Syntax:
v-once
Parameters: This function does not accept any parameter.
Example: This example uses Vue.js to show the working of the data with v-once.
<!DOCTYPE html><html>  <head>    <title>        VueJS v-once Directive    </title>      <!-- Load Vuejs -->    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">    </script></head>  <body>    <div style="text-align: center;              width: 600px;">        <h1 style="color: green;">            GeeksforGeeks        </h1>          <b>            VueJS | v-once directive        </b>    </div>      <div id="canvas" style=        "border: 1px solid #000000;        width: 600px; height: 200px;">        <div id="app" style="text-align: center;                padding-top: 40px;">            <h1 v-once>{{ data }}</h1>        </div>    </div>    <script>        var app = new Vue({            el: '#app',            data: {                data: 'GeeksforGeeks'            }        })    </script></body>  </html>
Output:
Vue.JS
JavaScript
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
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to get the same value from another array and assign to object of arrays?

12 Mar, 2021
To get the same value from another array and insert it into an object of the array we need to.
Compare each and every element of two arraysReturn the matched elementAdd the element or object into the object of array
Compare each and every element of two arrays
Return the matched element
Add the element or object into the object of array
Before jumping into the code, you can read the following articles. It will help you to understand it better, 
Array forEach() method
Array push() method
Array includes() method
Array filter() method
ES6 Arrow function
Method 1: Using forEach() and push(), includes() method of array.
Javascript
<script>  // Define first array  let arr1 = [1, 2, 3, 4, 5, 77, 876, 453];    // Define second array  let arr2 = [1, 2, 45, 4, 231, 453];    // Create a empty object of array  let result = [];     // Checked the matched element between two   // array and add into result array  arr1.forEach( val => arr2.includes(val) && result.push(val) );    // Print the result on console  console.log( result );</script>
Output:
 1, 2, 4, 453
Method 2: filter(), push() and includes() of array.
Javascript
<script>  // Define first array  let arr1 = [1, 2, 3, 4, 5, 77, 876, 453];    // Define second array  let arr2 = [1, 2, 45, 4, 231, 453];      / Checked the matched element between two array  // and add into the result array  let result = arr1.filter(val => arr2.includes(val) );      // Print the result on console  console.log( result );  </script>
Output:
 1, 2, 4, 453
javascript-array
JavaScript-Questions
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Cartesian product of string elements

22 Apr, 2020
Sometimes, while working with Python strings, we can have problem that we have data in string which is comma or any delim separated. We might want to perform cartesian product with other similar strings to get all possible pairs of data. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + split()This task can be performed using list comprehension. In this, we perform the task of extracting individual elements using split(). The task of list comprehension is to form pairs.
# Python3 code to demonstrate working of # Cartesian product of string elements# Using split() + list comprehension  # initializing stringstest_str1 = "gfg, is, best"test_str2 = "for, all, geeks"  # printing original stringsprint("The original string 1 is : " + test_str1)print("The original string 2 is : " + test_str2)  # Cartesian product of string elements# Using split() + list comprehensionres = [sub1 + sub2 for sub1 in test_str1.split(", ") for sub2 in test_str2.split(", ")]                      # printing result print("Cartesian product list : " + str(res)) 
The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']

 
Method #2 : Using List comprehension + product()The combination of above functions can be used to perform this task. In this, we employ product() in place of nested comprehension to perform the task of pairing.
# Python3 code to demonstrate working of # Cartesian product of string elements# Using product() + list comprehensionfrom itertools import product  # initializing stringstest_str1 = "gfg, is, best"test_str2 = "for, all, geeks"  # printing original stringsprint("The original string 1 is : " + test_str1)print("The original string 2 is : " + test_str2)  # Cartesian product of string elements# Using product() + list comprehensionres = [sub1 + sub2 for sub1, sub2 in product(test_str1.split(", "), test_str2.split(", "))]                      # printing result print("Cartesian product list : " + str(res)) 
The original string 1 is : gfg, is, best
The original string 2 is : for, all, geeks
Cartesian product list : ['gfgfor', 'gfgall', 'gfggeeks', 'isfor', 'isall', 'isgeeks', 'bestfor', 'bestall', 'bestgeeks']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2015 (Set 1) | Question 65

28 Jun, 2021
Consider a LAN with four nodes S1, S2, S3 and S4. Time is divided into fixed-size slots, and a node can begin its transmission only at the beginning of a slot. A collision is said to have occurred if more than one node transmit in the same slot. The probabilities of generation of a frame in a time slot by S1, S2, S3 and S4 are 0.1, 0.2, 0.3 and 0.4, respectively. The probability of sending a frame in the first slot without any collision by any of these four stations is _________.(A) 0.462(B) 0.711(C) 0.5(D) 0.652Answer: (A)Explanation:
The probability of sending a frame in the first slot 
without any collision by any of these four stations is
sum of following 4 probabilities

Probability that S1 sends a frame and no one else does + 
Probability thatS2 sends a frame and no one else does +
Probability thatS3 sends a frame and no one else does +
Probability thatS4 sends a frame and no one else does

= 0.1 * (1 - 0.2) * (1 - 0.3) *(1 - 0.4) + 
  (1 -0.1) * 0.2 * (1 - 0.3) *(1 - 0.4) + 
  (1 -0.1) * (1 - 0.2) * 0.3 *(1 - 0.4) + 
  (1 -0.1) * (1 - 0.2) * (1 - 0.3) * 0.4

= 0.4404 
Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find largest sum of non-adjacent elements of a list in Python

Suppose we have a list of numbers called nums, we will define a function that returns the
largest sum of non-adjacent numbers. Here the numbers can be 0 or negative.
So, if the input is like [3, 5, 7, 3, 6], then the output will be 16, as we can take 3, 7, and 6 to get
16.
To solve this, we will follow these steps−
if size of nums <= 2, thenreturn maximum of nums
if size of nums <= 2, then
return maximum of nums
return maximum of nums
noTake := 0
noTake := 0
take := nums[0]
take := nums[0]
for i in range 1 to size of nums, dotake := noTake + nums[i]noTake := maximum of noTake and take
for i in range 1 to size of nums, do
take := noTake + nums[i]
take := noTake + nums[i]
noTake := maximum of noTake and take
noTake := maximum of noTake and take
return maximum of noTake and take
return maximum of noTake and take
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      if len(nums) <= 2:
         return max(nums)
      noTake = 0
      take = nums[0]
      for i in range(1, len(nums)):
         take, noTake = noTake + nums[i], max(noTake, take)
         return max(noTake, take)
ob = Solution()
nums = [3, 5, 7, 3, 6]
print(ob.solve(nums))
[3, 5, 7, 3, 6]
16