code-rag-bench/online-tutorials huggingface dataset:
Ubuntu - Installing MySQL and Python

MySQL and Python are famous database and development software respectively. These are normally installed on Linux-based systems. Let’s see how we can get them installed on Ubuntu server environments.
The first thing to do is to find out what is the version of Python installed on the system. We can find this issuing the following command.
Python –v

Where the –v option specifies to show what is the version of Python installed. The following screenshot shows a sample of the output of the above command.
From the above output, we can see that the version of Python installed is version 2.7.
There is another way to see if Python is installed via the following commands.
Python –V

Python3 –V

The later command is used to see the version 3 of Python installed.
If we want to have the latest version of Python installed, then we need to issue the following statement.
sudo apt-get install python3

The above command will download the necessary packages for Python and have it installed.
To install MySQL, the following steps need to be followed.
Step 1 − Issue the apt-get command to ensure all operating system packages are up to date.
sudo apt-get update  

Step 2 − Once all the packages have been updated, it is time to get the packages for MySQL.
sudo apt-get install mysql-server

The above command will start the download of all the relevant packages for MySQL.
Once the download completes and the installation starts, the installer will first ask to configure a root password.
Step 3 − Enter the required password and click the OK button. It will also prompt to re-enter the password.
Step 4 − To see the MySQL process running, run the following command.
ps –ef | grep mysql

The following screenshot shows mysqld which is the daemon process for mysql running in the background.
Step 5 − To configure mysql, run the following command.
/usr/bin/mysql_secure_installation

It prompts to enter the root password which was entered during the installation process.
Step 6 − Enter the password and hit Enter.
Now, it prompts on whether we want to change the root password.
Step 7 − Enter ‘N’ for No and proceed.
Again, it prompts on whether we want to remove the Anonymous access.
Step 8 − When connecting from other machines on this database, it is advised to keep the default options as ‘N’ for both anonymous users and disallow root login remotely.
Step 9 − It is advised to provide the option as No for the options of Remove test database as well. We can enter ‘Y’ to reload the privileges table.
Finally, the configuration of MySQL will be complete.

    8 Lectures 
     31 mins

 Musab Zayadneh

    14 Lectures 
     1.5 hours 

 Satish

    26 Lectures 
     1.5 hours 

 YouAccel
 Print
 Add Notes
 Bookmark this page
LESS - Parametric Mixins

Parametric mixins use one or more parameters that extend functionality of LESS by taking arguments and its properties to customize the mixin output when mixed into another block.
For instance, consider a simple LESS code snippet −
.border(@width; @style; @color) {
   border: @width @style @color;
}

.myheader {
   .border(2px; dashed; green);
}
Here we are using the parametric mixin as .border with three parameters - width, style and color. Using these parameters, you can customize the mixin output with the passed parameters value.
The following table describes the different types of parametric mixins along with description.
Parameters can be separated using commas or semicolon.
Mixins provide parameter values instead of positions by using their names.
When a mixin is called, the @arguments include all the passed arguments.
Mixin takes variable number of arguments by using .....
Change the behavior of mixin by passing parameters to it.

    20 Lectures 
     1 hours 

 Anadi Sharma

    44 Lectures 
     7.5 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Zach Miller

    23 Lectures 
     1.5 hours 

 Zach Miller

    34 Lectures 
     4 hours 

 Syed Raza

    31 Lectures 
     3 hours 

 Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
C library function - setbuf()

The C library function void setbuf(FILE *stream, char *buffer) defines how a stream should be buffered. This function should be called once the file associated with the stream has already been opened, but before any input or output operation has taken place.
Following is the declaration for setbuf() function.
void setbuf(FILE *stream, char *buffer)
stream − This is the pointer to a FILE object that identifies an open stream.
stream − This is the pointer to a FILE object that identifies an open stream.
buffer − This is the user allocated buffer. This should have a length of at least BUFSIZ bytes, which is a macro constant to be used as the length of this array.
buffer − This is the user allocated buffer. This should have a length of at least BUFSIZ bytes, which is a macro constant to be used as the length of this array.
This function does not return any value.
The following example shows the usage of setbuf() function.
#include <stdio.h>

int main () {
   char buf[BUFSIZ];

   setbuf(stdout, buf);
   puts("This is tutorialspoint");

   fflush(stdout);
   return(0);
}
Let us compile and run the above program to produce the following result. Here program sends output to the STDOUT just before it comes out, otherwise it keeps buffering the output. You can also use fflush() function to flush the output.
This is tutorialspoint


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Java Generics - Type Inference

Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters.
Compiler generates unchecked conversion warning in-case type inference is not used.
Box<Integer> integerBox = new Box<>();

Where
Box − Box is a generic class.
Box − Box is a generic class.
<> − The diamond operator denotes type inference.
<> − The diamond operator denotes type inference.
Using diamond operator, compiler determines the type of the parameter. This operator is avalilable from Java SE 7 version onwards.
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      //type inference   
      Box<Integer> integerBox = new Box<>();
      //unchecked conversion warning
      Box<String> stringBox = new Box<String>();

      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));

      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.get());
   }
}

class Box<T> {
   private T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }   
}
This will produce the following result.
Integer Value :10
String Value :Hello World


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
C program that does not suspend when Ctrl+Z is pressed - GeeksforGeeks

26 Sep, 2017
Write a C program that doesn’t terminate when Ctrl+Z is pressed. It prints a message “Cannot be suspended using Ctrl+Z” and continues execution.
We can use Unix signal for this. When Ctrl+Z is pressed, SIGTSTP signal is generated.
SIGTSTP signal is sent to a process by its controlling terminal to request it to stop (terminal stop). We can catch this signal and run our own defined signal.The standard C library function signal() can be used to set up a handler for any of the above signals.
// C program that does not suspend when// Ctrl+Z is pressed#include <stdio.h>#include <signal.h>  // Signal Handler for SIGTSTPvoid sighandler(int sig_num){    // Reset handler to catch SIGTSTP next time    signal(SIGTSTP, sighandler);    printf("Cannot execute Ctrl+Z\n");}  int main(){    // Set the SIGTSTP (Ctrl-Z) signal handler    // to sigHandler    signal(SIGTSTP, sighandler);    while(1)    {    }    return 0;}
Output:
Cannot execute Ctrl+Z

This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
system-programming
C Language
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
PHP - DOM Parser Example

A HTML Dom parser written in PHP5.X versions. Dom Parser is very good at dealing with XML as well as HTML. Dom parser travels based on tree based and before access the data, it will load the data into dom object and it will update the data to the web browser. Below Example shows how to get access to the HTML data in web browser.
<?php 
   $html = ' 
      <head> 
         <title>Tutorialspoint</title>
      </head> 
   
      <body> 
         <h2>Course details</h2> 
      
         <table border = "0"> 
            <tbody> 
               <tr> 
                  <td>Android</td> 
                  <td>Gopal</td> 
                  <td>Sairam</td> 
               </tr> 
         
               <tr> 
                  <td>Hadoop</td> 
                  <td>Gopal</td> 
                  <td>Satish</td> 
               </tr> 
         
               <tr> 
                  <td>HTML</td> 
                  <td>Gopal</td> 
                  <td>Raju</td> 
               </tr> 
         
               <tr> 
                  <td>Web technologies</td> 
                  <td>Gopal</td> 
                  <td>Javed</td> 
               </tr> 
         
               <tr> 
                  <td>Graphic</td> 
                  <td>Gopal</td> 
                  <td>Satish</td> 
               </tr> 
         
               <tr> 
                  <td>Writer</td> 
                  <td>Kiran</td> 
                  <td>Amith</td> 
               </tr> 
         
               <tr> 
                  <td>Writer</td> 
                  <td>Kiran</td> 
                  <td>Vineeth</td> 
               </tr> 
            </tbody> 
         </table> 
      </body> 
   </html> 
   '; 
   /*** a new dom object ***/ 
   $dom = new domDocument; 
   
   /*** load the html into the object ***/ 
   $dom->loadHTML($html); 
   
   /*** discard white space ***/ 
   $dom->preserveWhiteSpace = false; 
   
   /*** the table by its tag name ***/ 
   $tables = $dom->getElementsByTagName('table'); 
   
   /*** get all rows from the table ***/ 
   $rows = $tables->item(0)->getElementsByTagName('tr'); 
   
   /*** loop over the table rows ***/ 
   foreach ($rows as $row) {
      /*** get each column by tag name ***/ 
      $cols = $row->getElementsByTagName('td'); 
      
      /*** echo the values ***/ 
      echo 'Designation: '.$cols->item(0)->nodeValue.'<br />'; 
      echo 'Manager: '.$cols->item(1)->nodeValue.'<br />'; 
      echo 'Team: '.$cols->item(2)->nodeValue; 
      echo '<hr />'; 
   }
?> 
It will produce the following result −

    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
How to increase the spacing between subplots in Matplotlib with subplot2grid?

To increase the spacing between subplots with subplot2grid, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Add a grid layout to place subplots within a figure.
Add a grid layout to place subplots within a figure.
Update the subplot parameters of the grid.
Update the subplot parameters of the grid.
Add a subplot to the current figure.
Add a subplot to the current figure.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

ax = plt.GridSpec(2, 2)
ax.update(wspace=0.5, hspace=0.5)

ax1 = plt.subplot(ax[0, :])
ax2 = plt.subplot(ax[1, 0])
ax3 = plt.subplot(ax[1, 1])

plt.show()
How to Solve Quadratic Equation using Python?

You can use the cmath module in order to solve Quadratic Equation using Python. This is because roots of quadratic equations might be complex in nature. If you have a quadratic equation of the form ax^2 + bx + c = 0, then,
import cmath
a = 12
b = 8
c = 1
# Discriminent
d = (b**2) - (4*a*c)
root1 = (-b - cmath.sqrt(d)) / (2 * a)
root2 = (-b + cmath.sqrt(d)) / (2 * a)
print(root1)
print(root2)
This will give the output
(-0.5+0j)
(-0.16666666666666666+0j)
Calendar Functions in Python -(monthrange(), prcal(), weekday()?)

We are going to explore different methods of calendar module in this tutorial. Let's see one by one.
The method calendar.monthrange(year, month) returns starting weekday number and number of days of the given month. It returns two values in a tuple. Let's see one example.
 Live Demo
# importing the calendar module
import calendar
# initializing year and month
year = 2019
month = 1
# getting the tuple of weekday and no. of days
weekday, no_of_days = calendar.monthrange(year, month)
print(f'Weekday number: {weekday}')
print(f'No. of days: {no_of_days}')
If you run the above code, you will get the following results.
Weekday number: 1
No. of days: 31
The method calendar.prcal(year) prints the calendar of the year without print function.
 Live Demo
# importing the calendar module
import calendar
# initializing year
year = 2019
# printing the calendar using prcal() method
calendar.prcal(year)
If you run the above program, you will get the following results.
The method calendar.weekday(year, month, day) takes three arguments and returns the weekday number.
 Live Demo
# importing the calendar module
import calendar
# initializing year, month and day
year = 2020
month = 1
day = 28
# getting weekday
print(calendar.weekday(year, month, day))
If you run the above code, you will get the following results.
1
If you have any doubts in the tutorial, mention them in the comment section.
GATE | GATE-CS-2016 (Set 2) | Question 14 - GeeksforGeeks

06 Oct, 2021
Consider the systems, each consisting of m linear equations in n variables.
I. If m < n, then all such systems have a solution
II. If m > n, then none of these systems has a solution
III. If m = n, then there exists a system which has a solution
Which one of the following is CORRECT?(A) I, II and III are true(B) Only II and III are true(C) Only III is true(D) None of them is trueAnswer: (C)Explanation:  
For ‘n’ variables, we need atleast ‘n’ linear equations in terms of the given  variable to find value of each variable. If no. of equations > no. of variables then also we can find the value of each variable.Here, m : No. of linear equations n : No. of variables For solution, m > or = n.
This solution is contributed by Mohit Gupta.
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersSystem of Linear Equation using rank of matrix with Sakshi Singhal | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0026:52 / 29:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hmtz4zIohNQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | Gate IT 2007 | Question 30
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2021 | Set 1 | Question 47
Java log1p() with example - GeeksforGeeks

31 Mar, 2018
The java.lang.Math.log1p() is one of the Java Math Library method which is used to return the natural logarithm of the sum of the arguments and 1.For the small values, the result of log1p(a) is much closer to the true result of ln(1 + a) than the floating-point evaluation of log(1.0 + a).There are various cases :
If the argument is positive double value, Math.log1p() method will return the logarithm of the given value.
If the argument is NaN or less than -1, Math.log1p() method will return NaN.
If the argument is positive infinity, Math.log1p() method will return the result as Positive Infinity
If the argument is negative one, Math.log1p() method will return Negative Infinity
f the argument is positive or negative zero, Math.log1p() method will return Zero
Syntax :
public static double log1p(double a)
Parameter :
a : User input
Return :
This method returns the value ln(x + 1), the natural log of x + 1.
Example :To show working of java.lang.Math.log1p() method.
// Java program to demonstrate working// of java.lang.Math.log1p() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double a = 23.45;        double b = -145.25;        double c = 1.0 / 0;        double d = -1;        double e = 0;           // positive double value as argument,        // output double value        System.out.println(Math.log1p(a));           // negative integer as argument,        // output NAN        System.out.println(Math.log1p(b));           // positive infinity as argument,        // output Positive Infinity        System.out.println(Math.log1p(c));          // negative one as argument,        // output Negative Infinity        System.out.println(Math.log1p(d));          // positive zero as argument,        // output Zero        System.out.println(Math.log1p(e));    }}
3.196630215920881
NaN
Infinity
-Infinity
0.0

java-math
Java
Java
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
PriorityQueue in Java
How to remove an element from ArrayList in Java?
What is the append method in Java?

The append(char c) method of the java.lang.StringBuffer appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence. The length of this sequence increases by 1.
 Live Demo
import java.lang.*;
public class StringBufferDemo {
   public static void main(String[] args) {
      StringBuffer buff = new StringBuffer("tuts ");
      System.out.println("buffer = " + buff);
     
      // appends the char argument as string to the string buffer.
      buff.append('A');
     
      // print the string buffer after appending
      System.out.println("After append = " + buff);
      buff = new StringBuffer("abcd ");
      System.out.println("buffer = " + buff);
     
      // appends the char argument as string to the string buffer.
      buff.append('!');
     
      // print the string buffer after appending
      System.out.println("After append = " + buff);
   }
}
buffer = tuts
After append = tuts A
buffer = abcd
After append = abcd !
C program to find the length of a string - GeeksforGeeks

24 Dec, 2021
Given a string str. The task is to find the length of the string. 
Examples:  
Input: str = "Geeks"
Output: Length of Str is : 5

Input: str = "GeeksforGeeks"
Output: Length of Str is : 13
 
In the below program, to find the length of the string str, first the string is taken as input from the user using scanf in , and then the length of Str is calculated using and using method .Below is the C program to find the length of the string.Example 1: Using loop to calculate the length of string. 
C
// C program to find the length of string#include <stdio.h>#include <string.h> int main(){    char Str[1000];    int i;     printf("Enter the String: ");    scanf("%s", Str);     for (i = 0; Str[i] != '\0'; ++i);     printf("Length of Str is %d", i);     return 0;}
Enter the String: Geeks
Length of Str is 5
 
Example 2: Using strlen() to find the length of the string. 
C
// C program to find the length of// string using strlen function#include <stdio.h>#include <string.h> int main(){    char Str[1000];    int i;     printf("Enter the String: ");    scanf("%s", Str);     printf("Length of Str is %ld", strlen(Str));     return 0;}
Enter the String: Geeks
Length of Str is 5
 
lokeshramdondapati
C-String-Question
school-programming
C Language
C Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Strings in C
Arrow operator -> in C/C++ with Examples
C Program to read contents of Whole File
Header files in C/C++ and its uses
Basics of File Handling in C
sciPy stats.cumfreq() function | Python - GeeksforGeeks

15 Jan, 2022
scipy.stats.cumfreq(a, numbins, defaultreallimits, weights) works using the histogram function and calculates the cumulative frequency histogram. It includes cumulative frequency binned values, width of each bin, lower real limit, extra points. 
Parameters : arr : [array_like] input array. numbins : [int] number of bins to use for the histogram. [Default = 10] defaultlimits : (lower, upper) range of the histogram. weights : [array_like] weights for each array element. Results : – cumulative frequency binned values – width of each bin – lower real limit – extra points. 
Code #1: 
Python3
# cumulative frequencyfrom scipy import statsimport numpy as np    arr1 = [1, 3, 27, 2, 5, 13] print ("Array element : ", arr1, "\n")   a, b, c, d = stats.cumfreq(arr1, numbins = 4)   print ("cumulative frequency : ", a)print ("Lower Limit : ", b)print ("bin size : ", c)print ("extra-points : ", d)
Array element :  [1, 3, 27, 2, 5, 13] 

cumulative frequency :  [ 4.  5.  5.  6.]
Lower Limit :  -3.33333333333
bin size :  8.66666666667
extra-points :  0
 
Code #2: 
Python3
# cumulative frequencyfrom scipy import statsimport numpy as np    arr1 = [1, 3, 27, 2, 5, 13] print ("Array element : ", arr1, "\n")   a, b, c, d = stats.cumfreq(arr1, numbins = 4,              weights = [.1, .2, .1, .3, 1, 6])   print ("cumfreqs : ", a)print ("lowlim : ", b)print ("binsize : ", c)print ("extrapoints : ", d)
Array element :  [1, 3, 27, 2, 5, 13] 

cumfreqs :  [ 1.6  7.6  7.6  7.7]
lowlim :  -3.33333333333
binsize :  8.66666666667
extrapoints :  0
 
surindertarika1234
ruhelaa48
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python MariaDB - Update Query using PyMySQL - GeeksforGeeks

14 Oct, 2020
MariaDB is an open-source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python.
In this article, we will look into the process of using the UPDATE query on a table of the database using pymysql.  The update is used to change the existing values in a database. By using the update statement a specific value can be corrected or updated. It only affects the data and not the structure of the table. The basic advantage provided by this command is that it keeps the table accurate.
Syntax :
UPDATE tablename
SET column_nmae = "new value"
WHERE conditions;

The following programs will help you understand this better.
Example 1 : 
Python3
import pymysql  # Create a connection object# IP address of the MySQL database serverHost = "localhost"    # User name of the database serverUser = "user"         # Password for the database userPassword = ""             database = "GFG"  conn  = pymysql.connect(host=Host, user=User, password=Password, database)  # Create a cursor objectcur  = conn.cursor()    query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'"  cur.execute(query)  #To commit the changesconn.commit() conn.close()
Output :
Before:After
In the above program,  We update Broad Band price from 1200 to 1400.
Example 2 :
Python3
import pymysql  # Create a connection objectconn  = pymysql.connect('localhost', 'user',                        'password', 'database')  # Create a cursor objectcur  = conn.cursor()    query = f"update PRODUCT set PRODUCT_ID = 'A123' WHERE \price = 14782 AND PRODUCT_TYPE = 'Voice'"  cur.execute(query)  # To commit the changesconn.commit()       conn.close()
Output :
BeforeAfter
In the above program,  We update PRODUCT_ID  to A123 WHERE price = 14782 AND PRODUCT_TYPE = ‘Voice’.
Python-MariaDB
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
PHP | JsonSerializable jsonSerialize() Function - GeeksforGeeks

27 Sep, 2019
The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function.
Syntax:
mixed JsonSerializable::jsonSerialize( void )
Parameters: This function does not accept any parameters.
Return Value: This function returns the data which is serialized by json_encode() function.
Below programs illustrate the JsonSerializable::jsonSerialize() function in PHP:
Program 1:
<?php class vector implements JsonSerializable {     public function __construct(array $arr) {         $this->array = $arr;     }       public function jsonSerialize() {         return $this->array;     } }   // Declare an array $arr = [1, 2, 3, 4, 5];   echo("JSON elements:\n");   // Convert the array element into JSONecho json_encode(new vector($arr), JSON_PRETTY_PRINT);   ?> 
JSON elements:
[
    1,
    2,
    3,
    4,
    5
]

Program 2:
<?php class vector implements JsonSerializable {     public function __construct(array $arr) {         $this->array = $arr;     }       public function jsonSerialize() {         return $this->array;     } }   // Declare an array $arr = [    "x" => "geeks",     "y" => "for",    "z" => "geeks"];   echo("Convert the array element into JSON:\n");   // Convert the array element into JSONecho json_encode(new vector($arr), JSON_PRETTY_PRINT);   ?> 
Convert the array element into JSON:
{
    "x": "geeks",
    "y": "for",
    "z": "geeks"
}

Reference: https://www.php.net/manual/en/jsonserializable.jsonserialize.php
JSON
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to insert DATE into a MySQL column value using Java?

For this, you can use PreparedStatement from Java. Let us first create a table wherein one of the columns is ArrivalDate with DATE type −
mysql> create table DemoTable(
   PassengerId int,
   PassengerName varchar(40),
   ArrivalDate date
);
Query OK, 0 rows affected (0.82 sec)
The JAVA code is as follows to insert date −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertDateFromJava {
   public static void main(String[] args) {
      Connection con = null;
      PreparedStatement ps = null;
      try {
         java.util.Date javaDate = new java.util.Date();
         java.sql.Date mySQLDate = new java.sql.Date(javaDate.getTime());
         con = DriverManager.getConnection("jdbc :mysql ://localhost :3306/web?useSSL=false", "root","123456");
         String query = "insert into DemoTable(PassengerId,PassengerName,ArrivalDate) values(?,?,?) ";
         ps = con.prepareStatement(query);
         ps.setInt(1, 101);
         ps.setString(2, "Adam");
         ps.setDate(3, mySQLDate);
         ps.executeUpdate();
         System.out.println("Record is inserted with current Date......");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
This will produce the following output of Java −
Record is inserted with current Date......
Following is the screenshot of the output −
Let us check the records of the table again −
mysql> select * from DemoTable;
This will produce the following output −
+-------------+---------------+-------------+
| PassengerId | PassengerName | ArrivalDate |
+-------------+---------------+-------------+
|         101 | Adam          | 2019-09-07  |
+-------------+---------------+-------------+
1 row in set (0.00 sec)
The screenshot is as follows −
How to find only Monday's date with Python?

You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday). Finally add one week to this date using a timedelta object and voila you get the next monday's date.
import datetime
today = datetime.date.today()
next_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)
print(next_monday)
This will give the output −
2018-01-08
Extracting email addresses using regular expressions in Python

Email addresses are pretty complex and do not have a standard being followed all over the world which makes it difficult to identify an email in a regex. The RFC 5322 specifies the format of an email address. We'll use this format to extract email addresses from the text.
For example, for a given input string −
Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com
We should get the output −
john.doe@somecompany.co.uk
jane_doe124@gmail.com
We can use the following regex for exatraction −
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+
We can extract the email addresses using the find all method from re module. For example,
import re

my_str = "Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com"
emails = re.findall("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)", my_str)

for mail in an email:
print(mail)
This will give the output −
john.doe@somecompany.co.uk
jane_doe124@gmail.com
Rotate a List in Java

To rotate a list in Java, let us first create a List and add elements −
List < Integer > list = new ArrayList < Integer > ();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
list.add(25);
list.add(30);
list.add(35);
list.add(40);
list.add(45);
Now, rotate the list −
Collections.reverse(list);
 Live Demo
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String args[]) {
      List<Integer>list = new ArrayList<Integer>();
      list.add(5);
      list.add(10);
      list.add(15);
      list.add(20);
      list.add(25);
      list.add(30);
      list.add(35);
      list.add(40);
      list.add(45);
      System.out.println("Initial list = "+list);
      Collections.reverse(list);
      System.out.println("List after rotation = "+list);
   }
}
Initial list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
List after rotation = [45, 40, 35, 30, 25, 20, 15, 10, 5]
How to Add Superscripts and Subscripts to Plots in R?

28 Nov, 2021
Plots can be used to create and display numerical values or data points. The x and y axes labels or titles are used to depict the labels to the plot data. These labels can create either subscript or superscript symbols within them. This can be done using various base R methods : 
The superscripts can be added to the x or y axes labels or titles of the plot. These can be added using the ^ operator which is appended to the character string created in the plot() method. The superscript operator can be created using the expression method. 
Syntax:
expression(str^val)
Parameters : 
str – The character string to create
val – The value to raise the character string by
Example:
Here we are going to create a plot with numbers from 1 to 6 with power of 2 as an expression.The string “Numbers” is combined with a subscript ^2 formatted with ^ symbol. 
R
# creating numbersnumb < - 1: 6  # creating the x axis labels# creating a plotplot(numb, xlab=expression("Numbers" ^ 2))
Output:
The subscripts can be added to the x or y axes labels or titles of the plot. These can be added using the [] operator which is appended to the character string created in the plot() method. The subscript operator can be created using the expression method.
Syntax:
expression(str[val])
Parameters :
str – The character string to create
val – The value to create the subscript the character string by
Example:
Here we are going to plot an expression [2] with the given numbers.The string “Numbers” is combined with a subscript [2] enclosed in braces.
R
# creating numbersnumb < - 1: 6  # creating the x axis labels# creating a plotplot(numb, xlab=expression("Numbers"[2]))
Output:
A combination of subscripts or superscripts can be appended to the plot strings using the ^ or [] operators. The * sign is appended each time the character string breaks into a part. 
Example:
Here we are plot an expression log”[a]*”10′′^2 for the integers 1 to 6. The string “log” is combined with the subscript [a] and then combined with the string “10” along with the superscript 2 formatted with ^ symbol. 
R
# creating numbersnumb < - 1: 6  # creating the x axis labels# creating a plotplot(numb, xlab=expression("log"[a]*"10" ^ 2))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js | app.get() Request Function

07 Mar, 2022
The app.get() function routes the HTTP GET Requests to the path which is being specified with the specified callback functions. Basically it is intended for binding the middleware to your application.Syntax:  
app.get( path, callback )
Parameters:  
path: It is the path for which the middleware function is being called.  callback: They can be a middleware function or series/array of middleware functions.  
path: It is the path for which the middleware function is being called.  
callback: They can be a middleware function or series/array of middleware functions.  
Installation of express module:  
You can visit the link to Install express module. You can install this package by using this command.  
You can visit the link to Install express module. You can install this package by using this command.  
npm install express
After installing express module, you can check your express version in command prompt using the command.  
After installing express module, you can check your express version in command prompt using the command.  
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.  
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.  
node index.js
Filename: index.js  
javascript
var express = require('express');var app = express();var PORT = 3000;  app.get('/', (req, res) => {  res.send("GET Request Called")})  app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);}); 
Steps to run the program:  
The project structure will look like this:  
The project structure will look like this:  
Make sure you have installed express module using following command:  
Make sure you have installed express module using following command:  
npm install express
Run index.js file using below command:  
Run index.js file using below command:  
node index.js
Output:  
Output:  
Server listening on PORT 3000
 Now make GET request to http://localhost:3000/ and you will get the following output:  
 
Now make GET request to http://localhost:3000/ and you will get the following output:  
GET Request Called
 
 
 
simmytarika5
kapoorchiranjeev
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | pattern Attribute

07 Dec, 2021
This attribute is used to specify the regular expression on which the input element value is checked. This attribute works with the following input types: text, password, date, search, email, etc. Use the Global title attribute to describe the pattern for helping the user.
Syntax:
<input pattern = "regular_exp">
Element: This attribute is associated with <input> element only.
Attribute: This attribute specifies the regular expression.
Example:
<!DOCTYPE html><html>    <head>        <title>pattern attribute</title>        <style>            body {                text-align:center;            }            h1 {                color:green;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>pattern attribute</h2>        <form action="#">            Password: <input type="text" name="Password"            pattern="[A-Za-z]{3}" title="3 letter Password">        <input type="submit">        </form>    </body></html>                    
Output:
Supported Browsers: The browser supported by pattern attribute are listed below:
Google Chrome 5.0 and above
Internet Explorer 10.0 and above
Firefox 4.0 and above
Opera 9.6 and above
hritikbhatnagar2182
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Get current timestamp using Python

01 Aug, 2020
A timestamp is a sequence of characters or encoded information used to find when a particular event occurred, generally giving the date and time of the day, accurate to a small fraction of a second. In this article, we will learn how to Get current timestamp in Python.
There are different ways to get current timestamp in Python, We can use functions from modules time, datetime and calendar.
1. Using module time :The time module provides various time-related functions. The function time, return the time in seconds since the epoch as a floating point number. epoch is defined as the point where the time starts and is platform dependent.
Syntax: time.time()
Parameters: NA
Return: floating point number expressed in seconds.
# using time moduleimport time  # ts stores the time in secondsts = time.time()  # print the current timestampprint(ts)
Output:
1594819641.9622827
 2. Using module datetime :The datetime module provides classes for manipulating dates and times.While date and time arithmetic is supported, the target of the implementation is on efficient attribute extraction for output formatting and manipulation. The function datetime.datetime.now which return number of seconds since the epoch.
Syntax: datetime.now()
Parameters: tz (time zone) which is optional.
Return: the current local date and time.
# using datetime moduleimport datetime;  # ct stores current timect = datetime.datetime.now()print("current time:-", ct)  # ts store timestamp of current timets = ct.timestamp()print("timestamp:-", ts)
Output:
current time:- 2020-07-15 14:30:26.159446
timestamp:- 1594823426.159446
 3. Using module calendar :We can also get timestamp by combining multiple functions from multiple modules. In this we we’ll use function calendar.timegm to convert tuple representing current time.
Syntax: calendar.timegm(tuple)
Parameters: takes a time tuple such as returned by the gmtime() function in the time module.
Return: the corresponding Unix timestamp value.
# using calendar module# using time moduleimport calendar;import time;  # gmt stores current gmtimegmt = time.gmtime()print("gmt:-", gmt)  # ts stores timestampts = calendar.timegm(gmt)print("timestamp:-", ts)
Output:
gmt:- time.struct_time(tm_year=2020, tm_mon=7, tm_mday=15, tm_hour=19, tm_min=21, tm_sec=6, tm_wday=2, tm_yday=197, tm_isdst=0)timestamp:- 1594840866
Picked
Python Pandas-Timestamp
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript: Balancing parentheses

Given a string that consists of only two types of characters: "(" and ")". We are required to write a function that takes in one such string and balances the parentheses by inserting either a "(" or a ")" as many times as necessary.
The function should then return the minimum number of insertions made in the string to balance it. For example −
If the string is −
const str = '()))';
Then the output should be 2, because by prepending '((', we can balance the string.
Following is the code −
const str = '()))';
const balanceParanthesis = str => {
   let paren = [];
   for (let i = 0; i < str.length; i++) {
      if (str[i] === "(") {
         paren.push(str[i]);
      } else if (str[i] === ")") {
         if (paren[paren.length - 1] === "("){
            paren.pop();
         }else {
            paren.push("#");
         };
      };
   }
   return paren.length;
}
console.log(balanceParanthesis(str));
This will produce the following output on console −
2
CSS Selectors

A CSS selector selects the HTML element(s) you 
want to style.
CSS selectors are used to "find" (or select) the HTML elements you 
want to style.
We can divide CSS selectors into five categories:
Simple selectors (select elements based on name, id, class)
Combinator selectors (select  
  elements based on a specific relationship between them)
Pseudo-class selectors (select elements based on a certain state)
Pseudo-elements selectors (select 
  and style a part of an element)
Attribute selectors (select elements based on 
  an attribute or attribute value)
This page will explain the most basic CSS selectors.
The element selector selects HTML elements based on the element name.
Here, all <p> elements on the page will be 
center-aligned, with a red text color: 
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is 
used to 
select one unique element!
To select an element with a specific id, write a hash (#) character, followed by 
the id of the element.
The CSS rule below will be applied to the HTML element with id="para1": 
Note: An id name cannot start with a number!
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the 
class name.
In this example all HTML elements with class="center" will be red and center-aligned: 
You can also specify that only specific HTML elements should be affected by a class.
In this example only <p> elements with class="center" will be 
red and center-aligned: 
HTML elements 
can also refer to more than one class.
In this example the <p> element will be styled according to class="center" 
and to class="large": 
Note: A class name cannot start with a number!
The universal selector (*) selects all HTML 
elements on the page.
The CSS rule below will affect every HTML element on the page: 
The grouping selector selects all the HTML elements with the same style 
definitions.
Look at the following CSS code (the h1, h2, and p elements have the same 
style definitions):
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
In this example we have grouped the selectors from the code above: 
Set the color of all <p> elements to red.
<style>
 {
   red;
}
</style>

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.
Validating email and password - JavaScript

Suppose, we have this dummy array that contains the login info of two of many users of a social networking platform −
const array = [{
   email: 'usman@gmail.com',
   password: '123'
 },
 {
   email: 'ali@gmail.com',
   password: '123'
 }
];
We are required to write a JavaScript function that takes in an email string and a password string.
The function should return a boolean based on the fact whether or not the user exists in the database.
Following is the code −
const array = [{
   email: 'usman@gmail.com',
   password: '123'
}, {
   email: 'ali@gmail.com',
   password: '123'
}];
const matchCredentials = (email, password) => {
   const match = array.find(el => {
      return el.email === email && el.password === password;
   });
   return !!match;
};
console.log(matchCredentials('usman@gmail.com', '123'));
console.log(matchCredentials('usman@gmail.com', '1423'));
This will produce the following output on console −
true
false