code-rag-bench/online-tutorials huggingface dataset:
C++ If ... Else

C++ supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
You can use these conditions to perform different actions for different decisions.
C++ has the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
Use the if statement to specify a block of 
C++ code to be executed if a condition is true.
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 
18. If the condition is true, print some text:
We can also test variables:
In the example above we use two variables, x and y, 
to test whether x is greater than y 
(using the > operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that "x is greater than y".
Print "Hello World" if x is greater than y.
int x = 50;
int y = 10;
 (x  y) {
  cout << "Hello World";
}

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.
SymPy - sympify() function

The sympify() function is used to convert any arbitrary expression such that it can be used as a SymPy expression. Normal Python objects such as integer objects are converted in SymPy. Integer, etc.., strings are also converted to SymPy expressions.
>>> expr="x**2+3*x+2" 
>>> expr1=sympify(expr) 
>>> expr1 
>>> expr1.subs(x,2)

The above code snippet gives the following output −
12
Any Python object can be converted in SymPy object. However, since the conversion internally uses eval() function, unsanitized expression should not be used, else SympifyError is raised.
>>> sympify("x***2")
---------------------------------------------------------------------------

SympifyError: Sympify of expression 'could not parse 'x***2'' failed, because of exception being raised.
The sympify() function takes following arguments: * strict: default is False. If set to True, only the types for which an explicit conversion has been defined are converted. Otherwise, SympifyError is raised. * evaluate: If set to False, arithmetic and operators will be converted into their SymPy equivalents without evaluating expression.
>>> sympify("10/5+4/2")

The above code snippet gives the following output −
4
>>> sympify("10/5+4/2", evaluate=False)

The above code snippet gives the following output −
105+42
 Print
 Add Notes
 Bookmark this page
JavaScript Object - prototype

The prototype property allows you to add properties and methods to any object (Number, Boolean, String and Date etc.).
Note − Prototype is a global property which is available with almost all the objects.
Its syntax is as follows −
object.prototype.name = value

Try the following example.
<html>
   <head>
      <title>User-defined objects</title>      
      <script type = "text/javascript">
         function book(title, author) {
            this.title = title; 
            this.author  = author;
         }
      </script>      
   </head>
   <body>      
      <script type = "text/javascript">
         var myBook = new book("Perl", "Mohtashim");
         book.prototype.price = null;
         myBook.price = 100;
         
         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>     
   </body>
</html>
Book title is : Perl
Book author is : Mohtashim
Book price is : 100


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Python | Iterate through value lists dictionary

26 Jul, 2019
While working with dictionary, we can have a case in which we need to iterate through the lists, which are in the keys of dictionaries. This kind of problem can occur in web development domain. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehensionList comprehension can be used to perform this particular task. It is just the shorthand to the conventional nested loops. we iterate for each key’s list and store the result.
# Python3 code to demonstrate working of# Iterating through value lists dictionary# Using list comprehension  # Initialize dictionarytest_dict = {'gfg' : [1, 2], 'is' : [4, 5], 'best' : [7, 8]}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Using list comprehension# Iterating through value lists dictionaryres = [[i for i in test_dict[x]] for x in test_dict.keys()]      # printing result print("The list values of keys are : " + str(res))
The original dictionary : {‘best’: [7, 8], ‘is’: [4, 5], ‘gfg’: [1, 2]}The list values of keys are : [[7, 8], [4, 5], [1, 2]]
 
Method #2 : Using from_iterable() + product() + items()The combination of above functions can be used to perform this particular task. The from_iterable() can be used to reduce inner loop and items function is used to extract key value pairs in the dictionary.
# Python3 code to demonstrate working of# Iterating through value lists dictionary# Using from_iterable() + product() + items()import itertools  # Initialize dictionarytest_dict = {'gfg' : [1, 2], 'is' : [4, 5], 'best' : [7, 8]}  # printing original dictionaryprint("The original dictionary : " +  str(test_dict))  # Iterating through value lists dictionary# Using from_iterable() + product() + items()res = []for key, value in (        itertools.chain.from_iterable(            [itertools.product((k, ), v) for k, v in test_dict.items()])):                res.append(value)      # printing result print("The list values of keys are : " + str(res))
The original dictionary : {‘best’: [7, 8], ‘is’: [4, 5], ‘gfg’: [1, 2]}The list values of keys are : [7, 8, 1, 2, 4, 5]
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | bezier() function

08 Apr, 2019
The bezier() function in p5.js is used to draw cubic Bezier curve on the screen. These curves are defined by a series of anchor and control points.
Syntax:
bezier( x1, y1, x2, y2, x3, y3, x4, y4 )
or
bezier( x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4 )

Parameters: The function accepts twelve parameters as mentioned above and described below:
x1 This parameter stores the x-coordinate for the first anchor point
y1 This parameter stores the y-coordinate for the first anchor point
x2 This parameter stores x-coordinate for the first control point
y2 This parameter stores y-coordinate for the first control point
x3 This parameter stores x-coordinate for the second control point
y3 This parameter stores y-coordinate for the second control point
x4 This parameter stores x-coordinate for the second anchor point
y4 This parameter stores y-coordinate for the second anchor point
z1 This parameter stores z-coordinate for the first anchor point
z2 This parameter stores z-coordinate for the first control point
z3 This parameter stores z-coordinate for the second control point
z4 This parameter stores z-coordinate for the second anchor point
Below programs illustrate the bezier() function in p5.js:
Example 1: This example uses bezier() function to draw a bezier() curve.
function setup() {      // Create canvas size     createCanvas(150, 110);}   function draw() {      // Set the background color    background(220);          noFill();          // Set the stroke color    stroke(0, 0, 0);          // Bezier function 8 parameters     // except z-coordinate    bezier(85, 20, 10, 10, 160, 90, 50, 80);}
Example 2: This example uses bezier() function with all parameters to draw a bezier() curve.
function setup() {        // Create canvas size    createCanvas(150, 150);}  function draw() {      // Set the background color    background(0, 0, 0);          noFill();          // Set the stroke color    stroke(255);          // Bezier function with all 12 parameters    bezier(150, 150, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0);}
Reference: https://p5js.org/reference/#/p5/bezier
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Subplots in Matplotlib with Python? - GeeksforGeeks

12 Nov, 2020
Prerequisite: Matplotlib 
In this article, we will learn how to add markers to a Graph Plot using Matplotlib with Python. For that one must be familiar with the following concepts: 
Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It was introduced by John Hunter within the year 2002.
Subplots : The matplotlib.pyplot.subplots() method provides a way to plot multiple plots on a single figure. Given the number of rows and columns, it returns a tuple (fig, ax), giving a single figure fig with an array of axes ax.
Import packages
Import or create some data
Create subplot objects.
Draw a plot with it.
Example 1:
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # making subplots objectsfig, ax = plt.subplots(3, 3)  # draw graphfor i in ax:    for j in i:        j.plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))  plt.show()
Output :
Example 2 :
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # making subplots objectsfig, ax = plt.subplots(2, 2)  # draw graphax[0][0].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))ax[0][1].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))ax[1][0].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))ax[1][1].plot(np.random.randint(0, 5, 5), np.random.randint(0, 5, 5))  plt.show()
Output :
Example 3 :
Python3
# importing packagesimport matplotlib.pyplot as pltimport numpy as np  # making subplots objectsfig, ax = plt.subplots(2, 2)  # create datax = np.linspace(0, 10, 1000)  # draw graphax[0, 0].plot(x, np.sin(x), 'r-.')ax[0, 1].plot(x, np.cos(x), 'g--')ax[1, 0].plot(x, np.tan(x), 'y-')ax[1, 1].plot(x, np.sinc(x), 'c.-')  plt.show()
Output :
Python-matplotlib
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
How to create Loading Screen in ReactJS ? - GeeksforGeeks

31 Oct, 2021
In this article, we are going to learn how we can create Loading Screen in ReactJs. A loading screen is a picture shown by a computer program, often a video game, while the program is loading or initializing.
React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies.
Approach: To create our loading screen we are going to use the react-loading package because it is powerful, lightweight, and fully customizable. After that, we will add different types of loading screens on our homepage using the installed package.
 
Create ReactJS Application: You can create a new ReactJs project using the below command:
npx create-react-app gfg
Install the required package: Now we will install the react-loading package using the below command:
npm i react-loading
Project Structure: It will look like this.
Adding Loading Screen: In this example, we are going to add the react-loading on the homepage of our app using the package that we installed. For this, add the below content in the App.js file.
Javascript
import React from "react";import ReactLoading from "react-loading";  export default function Loading() {  return (    <div>      <h2>Loading in ReactJs - GeeksforGeeks</h2>      <ReactLoading type="balls" color="#0000FF"         height={100} width={50} />      <ReactLoading type="bars" color="#0000FF"        height={100} width={50} />      <ReactLoading type="bubbles" color="#0000FF"        height={100} width={50} />      <ReactLoading type="cubes" color="#0000FF"        height={100} width={50} />      <ReactLoading type="cylon" color="#0000FF"         height={100} width={50} />      <ReactLoading type="spin" color="#0000FF"        height={100} width={50} />      <ReactLoading type="spokes" color="#0000FF"        height={100} width={50} />      <ReactLoading        type="spinningBubbles"        color="#0000FF"        height={100}        width={50}      />    </div>  );}
Explanation: In the above example first, we are importing the ReactLoading component from the react-loading package. After that, we are using our ReactLoading component to add different types of loading screens. We can set the type, color, height, and width of the loading screen.
Steps to run the application: Run the below command in the terminal to run the app.
npm start
React-Questions
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
How to pass data from one component to other component in ReactJS ?
ReactJS Functional Components
strings.Title() Function in Golang With Examples - GeeksforGeeks

19 Apr, 2020
strings.Title() Function returns a copy of string s with all Unicode letters of string whose begin words mapped to their Unicode title case. This method belongs to the strings package.
Syntax:
func Title(s string) string

It returns the string.
Example 1:
// Golang program to illustrate the strings.Title() function  package main  import (    "fmt"    "strings")  // Main functionfunc main() {    fmt.Println(strings.Title("geeks for geeks"))}
Output:
Geeks For Geeks

Example 2:
// Golang program to illustrate the strings.Title() function  package main  import (    "fmt"    "strings")  // Main functionfunc main() {    fmt.Println(strings.Title("computer science portal"))}
Output:
Computer Science Portal

Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang
How to Connect Scatterplot Points With Line in Matplotlib? - GeeksforGeeks

23 Dec, 2020
Prerequisite: Scatterplot using Seaborn in Python
Scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. And matplotlib is very efficient for making 2D plots from data in arrays. In this article, we are going to see how to connect scatter plot points with lines in matplotlib.
Approach:
Import module.
Determined X and Y coordinate for plot scatter plot points.
Plot scatterplot.
Plot matplotlib.pyplot with the same X and Y coordinate.
Below is the implementation:
Example 1:
Python3
# import moduleimport numpy as npimport matplotlib.pyplot as plt  # initialize x and y coordinatesx = [0.1, 0.2, 0.3, 0.4, 0.5]y = [6.2, -8.4, 8.5, 9.2, -6.3]  # set the title of a plotplt.title("Connected Scatterplot points with lines")  # plot scatter plot with x and y dataplt.scatter(x, y)  # plot with x and y dataplt.plot(x, y)
Output:
Example 2:
Python3
# import moduleimport numpy as npimport matplotlib.pyplot as plt  # initialize x and y coordinatesx = [1, 2, 3]y = [1, 2, 3]  # set the title of a plotplt.title("Connected Scatterplot points with lines")  # plotting scatter and pyplotplt.scatter(x, y)plt.plot(x, y)
Output:
Example 3: 
We can also connect scatter plot points with lines without using seaborn.scatterplot. We will use only pyplot to connect the scatter points with lines.
Python3
# import moduleimport numpy as npimport matplotlib.pyplot as plt  # initialize x and y coordinatesx = [0.1, 0.2, 0.3, 0.4, 0.5]y = [6.2, -8.4, 8.5, 9.2, -6.3]  plt.title("Connected Scatterplot points with line")plt.plot(x, y, marker="*")plt.show()
Output:
Python-matplotlib
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
C++ Pointers vs Arrays

Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing.  Consider the following program −
#include <iostream>
 
using namespace std;
const int MAX = 3;
 
int main () {
   int  var[MAX] = {10, 100, 200};
   int  *ptr;
 
   // let us have array address in pointer.
   ptr = var;
   
   for (int i = 0; i < MAX; i++) {
      cout << "Address of var[" << i << "] = ";
      cout << ptr << endl;
 
      cout << "Value of var[" << i << "] = ";
      cout << *ptr << endl;
 
      // point to the next location
      ptr++;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces result something as follows −
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200

However, pointers and arrays are not completely interchangeable. For example, consider the following program −
#include <iostream>
 
using namespace std;
const int MAX = 3;
 
int main () {
   int  var[MAX] = {10, 100, 200};
 
   for (int i = 0; i < MAX; i++) {
      *var = i;    // This is a correct syntax
      var++;       // This is incorrect.
   }
   
   return 0;
}
It is perfectly acceptable to apply the pointer operator * to var but it is illegal to modify var value. The reason for this is that var is a constant that points to the beginning of an array and can not be used as l-value.
Because an array name generates a pointer constant, it can still be used in pointer-style expressions, as long as it is not modified. For example, the following is a valid statement that assigns var[2] the value 500 −
*(var + 2) = 500;

Above statement is valid and will compile successfully because var is not changed.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
PHP 7 - Spaceship Operator

In PHP 7, a new feature, spaceship operator has been introduced. It is used to compare two expressions. It returns -1, 0 or 1 when first expression is respectively less than, equal to, or greater than second expression.
<?php
   //integer comparison
   print( 1 <=> 1);print("<br/>");
   print( 1 <=> 2);print("<br/>");
   print( 2 <=> 1);print("<br/>");
   print("<br/>");
   //float comparison
   print( 1.5 <=> 1.5);print("<br/>");
   print( 1.5 <=> 2.5);print("<br/>");
   print( 2.5 <=> 1.5);print("<br/>");
   print("<br/>");
   //string comparison
   print( "a" <=> "a");print("<br/>");
   print( "a" <=> "b");print("<br/>");
   print( "b" <=> "a");print("<br/>");
?>
It produces the following browser output −
0
-1
1

0
-1
1

0
-1
1


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
CSS Height, Width and Max-width

The CSS height and width properties are used to set the 
height and width of an element.
The CSS max-width property is used to set the maximum width of an element.
The height and width properties are used to set the 
height and width of an element.
The height and width properties do not include padding, borders, or margins. 
It sets the height/width of the area inside the padding, border, and margin of 
the element.
The height and width properties 
may have the following values:
auto - This is default. The browser 
calculates the height and width
length - Defines the height/width in px, cm 
etc.
% - Defines the height/width in percent of 
the containing block
initial - Sets the height/width to its 
default value
inherit - The height/width will be 
  inherited from its parent value
Set the height and width of a <div> element:

Try it Yourself »

Set the height and width of another <div> element:

Try it Yourself »

Note: Remember that the height and width properties do not include padding, borders, 
or margins! They set the height/width of the area inside the padding, border, 
and margin of the element!
The max-width property is used to set the maximum width of an element.
The max-width can be specified in length values, like px, cm, etc., or in percent (%) of the 
containing block, or set to none (this is 
default. Means that there is no maximum width).
The problem with the <div> above occurs when the browser window is smaller than the width of 
the element (500px). The browser then adds a horizontal scrollbar to the page.
Using max-width instead, in this situation, will improve the browser's handling of small windows.
Tip: Drag the browser window to smaller than 500px wide, to see the difference between 
the two divs!
Note: If you for some reason use both the
width property and the
max-width property on the same element, and the value of the
width property is larger than the
max-width property; the
max-width property will be used (and the
width property will be ignored).
This <div> element has a height of 100 pixels and a 
max-width of 500 pixels: 

Try it Yourself »

Set the height and width of elements
This example demonstrates how to set the height and width of different elements.
Set the height and width of an image using percent
This example demonstrates how to set the height and width of an image using a percent value.
Set min-width and max-width of an element
This example demonstrates how to set a minimum width and a maximum width of an element using a pixel value.
Set min-height and max-height of an element
This example demonstrates how to set a minimum height and a maximum height of an element using a pixel value.
Set the height of the <h1> element to "100px".
<style>
h1 {
  : 100px;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <p>This is a paragraph</p>
</body>

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.
How can I return 0 for NULL in MySQL?

We can return 0 for NULL in MySQL with the help of IFNULL() method. The syntax of IFNULL() is as follows.
IFNULL(YOUREXPRESSION,0);
Let us see an example. First, we will create a table.
mysql> create table NullDemoWithZero
   -> (
   -> id varchar(200)
   -> );
Query OK, 0 rows affected (0.65 sec)
After creating a table, let us insert some records in the table using the INSERT command. The query is as follows −
mysql> insert into NullDemoWithZero values();
Query OK, 1 row affected (0.16 sec)

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

mysql>  insert into NullDemoWithZero values('442');
Query OK, 1 row affected (0.10 sec)

mysql>  insert into NullDemoWithZero values('333');
Query OK, 1 row affected (0.13 sec)

mysql> insert into NullDemoWithZero values();
Query OK, 1 row affected (0.15 sec)

mysql>
mysql> insert into NullDemoWithZero values();
Query OK, 1 row affected (0.17 sec)
Display all records with the help of SELECT statement. The query is as follows.
mysql> select *from NullDemoWithZero;
The following is the output.
+------+
| id   |
+------+
| NULL |
| 123  |
| 442  |
| 333  |
| NULL |
| NULL |
+------+
6 rows in set (0.00 sec)

Look at the sample output above, there are many NULL values. Now, I am going to write a syntax that returns 0, if there is NULL value in the table. The following is the syntax.
select IFNULL(yourColumnName, 0) from yourTableName;
Apply the above syntax to get 0 if any row has NULL value. The query is as follows.
mysql> select IFNULL(id, 0) from NullDemoWithZero;
The following is the output that returns 0 for every NULL.
+---------------+
| IFNULL(id, 0) |
+---------------+
| 0             |
| 123           |
| 442           |
| 333           |
| 0             |
| 0             |
+---------------+
6 rows in set (0.00 sec)
How to play sound file in a web-page in the background?

The HTML <audio> element is used to add audio to web page. To play sound file in the background on a web page, use the <embed>...</embed> element. Also, use the autoplay attribute. This will run music in the background whenever the page loads.
Set the width and height in a way the player hides on the web page. The loop attribute is added to specify whether the audio will start over again.
You can try to run the following code to play a sound file in a web page in the background
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML background music</title>
   </head>
   <body>
      <p>The music is running in the background.</p>
      <p>(Song: Kalimba which is provided as a Sample Music in Windows)</p>
      <embed src="/html/Kalimba.mp3" loop="true" autostart="true" width="2"
         height="0">
   </body>
</html>
Searching from a comma separated MySQL column?

To search from a comma-separated column, use the FIND_IN_SET() method. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Value varchar(20)
   -> );
Query OK, 0 rows affected (0.47 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('41,14,94');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('64,84,94');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('44,74,103,104');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('904,1004,1444,1544');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('4,144,174');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------------------+
| Value              |
+--------------------+
| 41,14,94           |
| 64,84,94           |
| 44,74,103,104      |
| 904,1004,1444,1544 |
| 4,144,174          |
+--------------------+
5 rows in set (0.00 sec)
Here is the query to search from a comma-separated MySQL column −
mysql> select *from DemoTable where find_in_set('4',Value);
This will produce the following output −
+-----------+
| Value     |
+-----------+
| 4,144,174 |
+-----------+
1 row in set (0.00 sec)
Introduction to Seaborn – Python

03 Jun, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated to the data structures from pandas.Seaborn aims to make visualization the central part of exploring and understanding data. It provides dataset-oriented APIs, so that we can switch between different visual representations for same variables for better understanding of dataset.
Plots are basically used for visualizing the relationship between variables. Those variables can be either be completely numerical or a category like a group, class or division. Seaborn divides plot into the below categories –  
Relational plots: This plot is used to understand the relation between two variables.
Categorical plots: This plot deals with categorical variables and how they can be visualized.
Distribution plots: This plot is used for examining univariate and bivariate distributions
Regression plots: The regression plots in seaborn are primarily intended to add a visual guide that helps to emphasize patterns in a dataset during exploratory data analyses.
Matrix plots: A matrix plot is an array of scatterplots.
Multi-plot grids: It is an useful approach is to draw multiple instances of the same plot on different subsets of the dataset.
For python environment : 
pip install seaborn

For conda environment : 
conda install seaborn

Python 3.6+ 
numpy (>= 1.13.3) 
scipy (>= 1.0.1)
pandas (>= 0.22.0)
matplotlib (>= 2.1.2) 
statsmodel (>= 0.8.0)
Dist plot :  Seaborn dist plot  is used to plot a histogram, with some other variations like kdeplot and rugplot. 
Python3
# Importing librariesimport numpy as npimport seaborn as sns    # Selecting style as white,# dark, whitegrid, darkgrid # or tickssns.set(style="white")  # Generate a random univariate # datasetrs = np.random.RandomState(10)d = rs.normal(size=100)  # Plot a simple histogram and kde # with binsize determined automaticallysns.distplot(d, kde=True, color="m")
Output: 
Line plot : The line plot is one of the most basic plot in seaborn library.  This plot is mainly used to visualize the data in form of some time series, i.e. in continuous manner. 
Python3
import seaborn as sns    sns.set(style="dark")fmri = sns.load_dataset("fmri")  # Plot the responses for different\# events and regionssns.lineplot(x="timepoint",             y="signal",             hue="region",             style="event",             data=fmri)
Output : 
Lmplot :  The lmplot is another most basic plot. It shows a line representing a linear regression model along with data points on the 2D-space and x and y can be set as the horizontal and vertical labels respectively. 
Python3
import seaborn as sns  sns.set(style="ticks")  # Loading the datasetdf = sns.load_dataset("anscombe")  # Show the results of a linear regressionsns.lmplot(x="x", y="y", data=df)
Output : 
 
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Handling the Divide by Zero Exception in C++

In this tutorial, we will be discussing how to handle the divide by Zero exception in C++.
Division by zero is an undefined entity in mathematics, and we need to handle it properly while programming so that it doesn’t return at error at the user end.
 Live Demo
#include <iostream>
#include <stdexcept>
using namespace std;
//handling divide by zero
float Division(float num, float den){
   if (den == 0) {
      throw runtime_error("Math error: Attempted to divide by Zero\n");
   }
   return (num / den);
}
int main(){
   float numerator, denominator, result;
   numerator = 12.5;
   denominator = 0;
   try {
      result = Division(numerator, denominator);
      cout << "The quotient is " << result << endl;
   }
   catch (runtime_error& e) {
      cout << "Exception occurred" << endl << e.what();
   }
}
Exception occurred
Math error: Attempted to divide by Zero
 Live Demo
#include <iostream>
#include <stdexcept>
using namespace std;
//user defined class for handling exception
class Exception : public runtime_error {
   public:
   Exception()
   : runtime_error("Math error: Attempted to divide by Zero\n") {
   }
};
float Division(float num, float den){
   if (den == 0)
   throw Exception();
   return (num / den);

}
int main(){
   float numerator, denominator, result;
   numerator = 12.5;
   denominator = 0;
   //trying block calls the Division function
   try {
      result = Division(numerator, denominator);
      cout << "The quotient is " << result << endl;
   }
   catch (Exception& e) {
      cout << "Exception occurred" << endl << e.what();
   }
}
Exception occurred
Math error: Attempted to divide by Zero
 Live Demo
#include <iostream>
#include <stdexcept>
using namespace std;
//defining function to handle exception
float CheckDenominator(float den){
   if (den == 0) {
      throw runtime_error("Math error: Attempted to divide by zero\n");
   }
   else
      return den;
}
float Division(float num, float den){
   return (num / CheckDenominator(den));
}
int main(){
   float numerator, denominator, result;
   numerator = 12.5;
   denominator = 0;
   try {
      result = Division(numerator, denominator);
      cout << "The quotient is " << result << endl;
   }
   catch (runtime_error& e) {
      cout << "Exception occurred" << endl << e.what();
   }
}
Exception occurred
Math error: Attempted to divide by zero
Python | Pandas.factorize()

27 Sep, 2018
pandas.factorize() method helps to get the numeric representation of an array by identifying distinct values. This method is available as both pandas.factorize() and Series.factorize().
Parameters:values : 1D sequence.sort : [bool, Default is False] Sort uniques and shuffle labels.na_sentinel : [ int, default -1] Missing Values to mark ‘not found’.
Return: Numeric representation of array
Code: Explaining the working of factorize() method
# importing librariesimport numpy as npimport pandas as pdfrom pandas.api.types import CategoricalDtype  labels, uniques = pd.factorize(['b', 'd', 'd', 'c', 'a', 'c', 'a', 'b'])  print("Numeric Representation : \n", labels)print("Unique Values : \n", uniques)
# sorting the numericslabel1, unique1 = pd.factorize(['b', 'd', 'd', 'c', 'a', 'c', 'a', 'b'],                                                            sort = True)  print("\n\nNumeric Representation : \n", label1)print("Unique Values : \n", unique1)
# Missing values indicatedlabel2, unique2 = pd.factorize(['b', None, 'd', 'c', None, 'a', ],                                               na_sentinel = -101)  print("\n\nNumeric Representation : \n", label2)print("Unique Values : \n", unique2)
# When factorizing pandas object; unique will differ a = pd.Categorical(['a', 'a', 'c'], categories =['a', 'b', 'c'])  label3, unique3 = pd.factorize(a)  print("\n\nNumeric Representation : \n", label3)print("Unique Values : \n", unique3)
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Sierpinski Carpet

06 Nov, 2018
The Sierpinski Carpet is a plane fractal curve i.e. a curve that is homeomorphic to a subspace of plane. It was first described by Waclaw Sierpinski in 1916. In these type of fractals, a shape is divided into a smaller copy of itself, removing some of the new copies and leaving the remaining copies in specific order to form new shapes of fractals.
How is it constructed?The Sierpinski Carpet starts with a square. This square is divided into nine equal parts. The centremost smaller square is removed from the original larger square. The remaining square pieces are then again divided into nine equal parts and the centermost square from each square is removed. On repeating this process, a beautiful pattern of Sierpinski Carpet is observed.
Suppose we start with a black square.We divide it into 9 equal pieces and remove the center square.On further repeating the process, it results in something like this. We can visualize this phenomenon in details in this video.
Let us see what its code looks like :
# importing necessary modulesimport numpy as npfrom PIL import Image  # total number of times the process will be repeatedtotal = 7  # size of the imagesize = 3**total  # creating an imagesquare = np.empty([size, size, 3], dtype = np.uint8)color = np.array([255, 255, 255], dtype = np.uint8)  # filling it blacksquare.fill(0)  for i in range(0, total + 1):    stepdown = 3**(total - i)    for x in range(0, 3**i):                  # checking for the centremost square        if x % 3 == 1:            for y in range(0, 3**i):                if y % 3 == 1:                                          # changing its color                    square[y * stepdown:(y + 1)*stepdown, x * stepdown:(x + 1)*stepdown] = color  # saving the image producedsave_file = "sierpinski.jpg"Image.fromarray(square).save(save_file)  # displaying it in consolei = Image.open("sierpinski.jpg")i.show()
Output :
This is the Sierpinski Carpet after 7 repetitions. You can get its code for other languages on rosettacode.
Fractal
Image-Processing
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
PHP | fwrite( ) Function

19 Jun, 2018
The fwrite() function in PHP is an inbuilt function which is used to write to an open file. The fwrite() function stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file, string and the length which has to be written are sent as parameters to the fwrite() function and it returns the number of bytes written on success, or FALSE on failure.
Syntax:
fwrite(file, string, length)
Parameters: The fwrite() function in PHP accepts three parameters.
file : It is a mandatory parameter which specifies the file.string : It is a mandatory parameter which specifies the string to be written.length : It is an optional parameter which specifies the maximum number of bytes to be written.
file : It is a mandatory parameter which specifies the file.
string : It is a mandatory parameter which specifies the string to be written.
length : It is an optional parameter which specifies the maximum number of bytes to be written.
Return Value: It returns the number of bytes written on success, or False on failure.
Exceptions:
Both binary data, like images and character data, can be written with this function since fwrite() is binary-safe.If writing operation is performed twice to the file pointer, then the data will be appended to the end of the file content.
Both binary data, like images and character data, can be written with this function since fwrite() is binary-safe.
If writing operation is performed twice to the file pointer, then the data will be appended to the end of the file content.
Examples:
Input : $myfile = fopen("gfg.txt", "w");
        echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");
        fclose($myfile);
Output : 36

Input : $myfile = fopen("gfg.txt", "w");
        echo fwrite($myfile, "PhP is Simple to Learn!");
        echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");
        fclose($myfile);
Output : 23
         59

Below programs illustrate the fwrite() function:
Program 1:
<?php// Opening a file$myfile = fopen("gfg.txt", "w");  // writing content to a file using fwrite()echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");  // closing the filefclose($myfile);?>
Output:
36

Program 2:
<?php// Opening a file$myfile = fopen("gfg.txt", "w");  // writing content to a file using fwrite()echo fwrite($myfile, "PhP is Simple to Learn!");echo fwrite($myfile, "Geeksforgeeks is a portal for geeks!");  // closing the filefclose($myfile);?>
Output:
23
59

Reference : http://php.net/manual/en/function.fwrite.php
PHP-file-handling
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
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 ?
matplotlib.pyplot.pause() in Python

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The pause() function in pyplot module of matplotlib library is used to pause for interval seconds.
Syntax:
matplotlib.pyplot.pause(interval)

Parameters: This method does not accepts any parameters.
Return value: This method does not returns any value.
Below examples illustrate the matplotlib.pyplot.pause() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt   np.random.seed(19)data = np.random.random((5, 10, 10))     for i in range(len(data)):    plt.cla()    plt.title('matplotlib.pyplot.pause() function Example\n\n Window {}'.format(i), fontweight ="bold")    plt.imshow(data[i])    plt.pause(0.1)
Output:
Example #2:
# Implementation of matplotlib functionfrom mpl_toolkits.mplot3d import axes3dimport matplotlib.pyplot as plt   fig = plt.figure()ax = fig.add_subplot(111, projection ='3d')   X, Y, Z = axes3d.get_test_data(0.1)ax.plot_wireframe(X, Y, Z, rstride = 5, cstride = 5)   for angle in range(0, 360):    ax.view_init(30, angle)    plt.draw()    plt.pause(.001)    ax.set_title('matplotlib.pyplot.pause() function Example', fontweight ="bold")
Output:
Python-matplotlib
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
Python String lower() Method

05 Jul, 2022
Python String lower() method converts all uppercase characters in a string into lowercase characters and returns it. In this article, we will cover how to convert uppercase to lowercase in Python. 
Here we will also cover casefold and swapcase function to lower our string.
Syntax: string.lower()
Parameters: The lower() method doesn’t take any parameters. 
Returns: Returns a lowercase string of the given string
String with only alphabetic characters 
Python3
text = 'GeEks FOR geeKS' print("Original String:")print(text) # lower() function to convert# string to lower_caseprint("\nConverted String:")print(text.lower())
Output: 
Original String:
GeEks FOR geeKS

Converted string:
geeks for geeks
String with Alphanumeric Characters 
Python3
text = 'G3Ek5 F0R gE3K5' print("Original String:")print(text) # lower() function to convert# string to lower_caseprint("\nConverted String:")print(text.lower())
Output: 
Original String:
G3Ek5 F0R gE3K5

Converted String:
g3ek5 f0r ge3k5
One of the common applications of the lower() method is to check if the two strings are the same or not.
Python3
text2 = 'gEeKS fOR GeeKs' # Comparison of strings using# lower() methodif(text1.lower() == text2.lower()):    print("Strings are same")else:    print("Strings are not same")
Output: 
Strings are same
Convert uppercase to lowercase in python using swapcase function.
Python3
s = 'GEEKSFORGEEKS'print(s.swapcase())
Output:
geeksforgeeks
Convert uppercase to lowercase in python using casefold function.
Python3
s = 'GEEKSFORGEEKS'print(s.casefold())
Output:
geeksforgeeks
AmiyaRanjanRout
gabaa406
surajkumarguptaintern
python-string
Python-string-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Shut-Down Virus for Windows?

22 Mar, 2021
As the name of the virus is clear we are here trying to Create a simple shout-down Virus that is not harmful to the data that is saved in the computer this type of virus automatically restarts the PC when the user Login/Start the PC. This virus Automatically shout-down the PC till the time it is programmed by the programmer and not able to do any work to the user of that PC. This type of Virus simply makes discomfort to the user and the work of the user must get hampered lot by this kind of virus, For preparation, we didn’t have to download any specific software we can start doing the Coding in Notepad and save the file as .bat Extension. For the Creation of the Virus Follow these Steps are as follows :
Step 1: Press the Window + R Button from the Keyboard.
Step 2: The Run Dialog book will Open in front of the user.
Step 3: Type Notepad in the Dialog Box and press Enter.
Now Notepad Window will Open in front of the User as shown below:
Step 4: Add the following code in the Notepad as shown:
shutdown -s -t <no. of time you want to shut down the Computer> c "<Message you want to show in the Screen of the user>"
Step 5: After adding all the code, save the File with the name of your choice, but remember to save the file with .bat Extension anywhere on the Computer.
The Virus is Successfully Created by you but it is important to note that this will only work when it is open by the user.
A message will be displayed in front of the user which is set by the Programmer. After Activating this virus the PC will Automatically Shut-Down till the time set in the Program by the Programmer. To resolve the shut-down issue of the Computer you will have to do the following things:
Connect the HDD in the External mode into another PC and try to find the Virus Program file and Delete that file from the HDD. This will also resolve the problem but this will only work when you got the correct file that is causing this problem. No. Antivirus will be able to find this file on the PC.
 Reinstall the window in the Infected PC. 
 
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.