code-rag-bench/online-tutorials huggingface dataset:
What is the difference between global and local variables in Python?

A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.
In the given code
q = "I love coffee" # global variable
def f():
    p = "Me Tarzan, You Jane." # local variable
    print p
 f()
print q
The output is as follows
Me Tarzan, You Jane.
I love coffee
In the given code, p is a local variable, local to the function f(). q is a global variable accessible anywhere in the module.
PostgreSQL - DROP Table

The PostgreSQL DROP TABLE statement is used to remove a table definition and all associated data, indexes, rules, triggers, and constraints for that table.
Basic syntax of DROP TABLE statement is as follows −
DROP TABLE table_name;

We had created the tables DEPARTMENT and COMPANY in the previous chapter. First, verify these tables (use \d to list the tables) −
testdb-# \d
This would produce the following result −
           List of relations
 Schema |    Name    | Type  |  Owner
--------+------------+-------+----------
 public | company    | table | postgres
 public | department | table | postgres
(2 rows)

This means DEPARTMENT and COMPANY tables are present. So let us drop them as follows −
testdb=# drop table department, company;
This would produce the following result −
DROP TABLE
testdb=# \d
relations found.
testdb=# 

The message returned DROP TABLE indicates that drop command is executed successfully.

    23 Lectures 
     1.5 hours 

 John Elder

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    126 Lectures 
     10.5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     5 hours 

 Karthikeya T

    5 Lectures 
     51 mins

 Vinay Kumar

    5 Lectures 
     52 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
Python print() function - GeeksforGeeks

09 Feb, 2022
The python print() function as the name suggests is used to print a python object(s) in Python as standard output.
Syntax: print(object(s), sep, end, file, flush)
Parameters:
Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into strings.
sep: It is an optional parameter used to define the separation among different objects to be printed. By default an empty string(“”) is used as a separator.
end: It is an optional parameter used to set the string that is to be printed at the end. The default value for this is set as line feed(“\n”).
file: It is an optional parameter used when writing on or over a file. By default,, it is set to produce standard output as part of sys.stdout.
flush: It is an optional boolean parameter to set either a flushed or buffered output. If set True, it takes flushed else it takes buffered. By default, it is set to False.
Python3
# sample python objectslist = [1,2,3]tuple = ("A","B")string = "Geeksforgeeks" # printing the objectsprint(list,tuple,string)
Output:
[1, 2, 3] ('A', 'B') Geeksforgeeks
Python3
# sample python objectslist = [1,2,3]tuple = ("A","B")string = "Geeksforgeeks" # printing the objectsprint(list,tuple,string, sep="<<..>>")
Output:
[1, 2, 3]<<..>>('A', 'B')<<..>>Geeksforgeeks
Python3
# sample python objectslist = [1,2,3]tuple = ("A","B")string = "Geeksforgeeks" # printing the objectsprint(list,tuple,string, end="<<..>>")
Output:
[1, 2, 3] ('A', 'B') Geeksforgeeks<<..>>
For this, we will also be using the Python open() function and then print its contents. We already have the following text file saved in our system with the name geeksforgeeks.txt.
To read and print this content we will use the below code:
Python3
# open and read the file my_file = open("geeksforgeeks.txt","r")   # print the contents of the fileprint(my_file.read())
Output:
Python3
# Python code for printing to stderr # importing the package# for sys.stderrimport sys # variablesCompany = "Geeksofrgeeks.org"Location = "Noida"Email = "contact@geeksforgeeks.org" # print to stderrprint(Company, Location, Email, file=sys.stderr)
Output:
Geeksofrgeeks.org Noida contact@geeksforgeeks.org
sooda367
adnanirshad158
gabaa406
simmytarika5
Picked
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
Conversion characters for time in Java

The following are the conversion characters for date-time.
The following is an example.
 Live Demo
import java.util.Calendar;
public class Demo {
   public static void main( String args[] ) {
      Calendar cal = Calendar.getInstance();
      // date
      System.out.printf("Date....\n");
      System.out.printf( "%1$tA, %1$tB %1$td, %1$tY\n", cal );
      System.out.printf( "%1$ta, %1$tb %1$te, %1$ty\n", cal );
      // time
      System.out.printf("\nTime....\n");
      System.out.printf( "%1$tH:%1$tM:%1$tS\n", cal );
      System.out.printf( "%1$tZ %1$tI:%1$tM:%1$tS", cal );
   }
}
Date....
Monday, November 26, 2018
Mon, Nov 26, 18
Time....
12:41:28
UTC 12:41:28
Find number of days between two given dates in C++

In this problem, we are given two arrays date1[] and date2 consisting of 3 integers which denote the DD-MM-YYYY of daes. Our task is to find the number of days between two given dates.
Let’s take an example to understand the problem,
date1[] = {13, 3, 2021}, date2[] = {24, 5, 2023}
802
The difference is 2 years , 2 months (3 - 5) and 11 days.
2*356 + (30 + 31) + 11 = 802
A simple solution to the problem is by looping, starting from the start date date1 to date2 counting the number of days. And returning the value. This approach is ok, but a more efficient approach can be there.
A more efficient approach to the problem is by counting the total number of days till both the dates date1[] and date2[]. And then the absolute difference between both gives the result.
To count the number of days till both date1[] from 01/01/0000.
Number of days till the first day of the year date1[2]
Number of days = 365*(years) + no. of leap year
For a number of days till the 1st day of the month. Count from month array.
Number of days = monthDays[date[1]].
monthDays will store the total number of days till the 1st date of the month.
Number of days.
Sum of all these gives the count of days till date date1[]. The difference between the counts is the result.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
const int monthDays[12] = { 31, 59, 90, 120, 151, 181, 212, 243,
273, 304, 334, 365 };
int countLeapYearDays(int d[]){
   int years = d[2];
   if (d[1] <= 2)
      years--;
   return ( (years / 4) - (years / 100) + (years / 400) );
}
int countNoOfDays(int date1[], int date2[]){
   long int dayCount1 = (date1[2] * 365);
   dayCount1 += monthDays[date1[1]];
   dayCount1 += date1[0];
   dayCount1 += countLeapYearDays(date1);
   long int dayCount2 = (date2[2] * 365);
   dayCount2 += monthDays[date2[1]];
   dayCount2 += date2[0];
   dayCount2 += countLeapYearDays(date2);
   return ( abs(dayCount1 - dayCount2) );
}
int main(){
   int date1[3] = {13, 3, 2021};
   int date2[3] = {24, 5, 2023};
   cout<<"The number of days between two dates is "<<countNoOfDays(date1, date2);
   return 0;
}
The number of days between two dates is 802
Java - xxxValue() Method

The method converts the value of the Number Object that invokes the method to the primitive data type that is returned from the method.
Here is a separate method for each primitive data type −
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()

Here is the detail of parameters −
All these are default methods and accepts no parameter.
This method returns the primitive data type that is given in the signature.
This method returns the primitive data type that is given in the signature.
public class Test { 

   public static void main(String args[]) {
      Integer x = 5;
      
      // Returns byte primitive data type
      System.out.println( x.byteValue() );

      // Returns double primitive data type
      System.out.println(x.doubleValue());

      // Returns long primitive data type
      System.out.println( x.longValue() );      
   }
}
This will produce the following result −
5
5.0
5


    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
PyQt - QPixmap Class

QPixmap class provides an off-screen representation of an image. It can be used as a QPaintDevice object or can be loaded into another widget, typically a label or button.
Qt API has another similar class QImage, which is optimized for I/O and other pixel manipulations. Pixmap, on the other hand, is optimized for showing it on screen. Both formats are interconvertible.
The types of image files that can be read into a QPixmap object are as follows −
Following methods are useful in handling QPixmap object −
copy()
Copies pixmap data from a QRect object
fromImage()
Converts QImage object into QPixmap
grabWidget()
Creates a pixmap from the given widget
grabWindow()
Create pixmap of data in a window
Load()
Loads an image file as pixmap
save()
Saves the QPixmap object as a file
toImage
Converts a QPixmap to QImage
The most common use of QPixmap is to display image on a label/button.
The following example shows an image displayed on a QLabel by using the setPixmap() method. The complete code is as follows −
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

def window():
   app = QApplication(sys.argv)
   win = QWidget()
   l1 = QLabel()
   l1.setPixmap(QPixmap("python.jpg"))
	
   vbox = QVBoxLayout()
   vbox.addWidget(l1)
   win.setLayout(vbox)
   win.setWindowTitle("QPixmap Demo")
   win.show()
   sys.exit(app.exec_())
	
if __name__ == '__main__':
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
AtomicReference get() method in Java with Examples - GeeksforGeeks

27 Dec, 2019
The get() method of a AtomicReference class is used to return the value of this AtomicReference object with memory semantics of reading as if the variable was declared volatile type of variable.
Syntax:
public final V get()

Parameters: This method accepts nothing.
Return value: This method returns current value of this AtomicReference.
Below programs illustrate the get() method:Program 1:
// Java program to demonstrate// AtomicReference.get() method  import java.util.concurrent.atomic.AtomicReference;  public class GFG {    public static void main(String[] args)    {          // create an atomic reference object        // which stores Integer.        AtomicReference<Integer> ref            = new AtomicReference<Integer>();          // set some value        ref.set(12);          // get and print value        int value = ref.get();        System.out.println("value  = " + value);    }}
value  = 12

Program 2:
// Java program to demonstrate// AtomicReference.get() method  import java.util.concurrent.atomic.AtomicReference;  public class GFG {    public static void main(String[] args)    {          // create an atomic reference object        // which stores String.        AtomicReference<String> ref            = new AtomicReference<String>();          // set some value        ref.set("GEEKS FOR GEEKS");          // get and print value        String value = ref.get();        System.out.println("V  = " + value);    }}
V  = GEEKS FOR GEEKS

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/atomic/AtomicReference.html#get()
Java-Functions
Java-util-concurrent-atomic package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java
Java Examples - Search Table Contents

How to Search contents of a table?
Following method uses where & like sql Commands to search through the database.
import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception {
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection(
         "jdbc:derby://localhost:1527/testDb","username", "password");
      
      Statement stmt = con.createStatement();
      String query[] = {
         "SELECT * FROM emp where id = 1", 
         "select name from emp where name like 'ravi_'", 
         "select name from emp where name like 'ravi%'" 
      };
      
      for(String q : query) {
         ResultSet rs = stmt.executeQuery(q);
         System.out.println("Names for query "+q+" are");
         
         while (rs.next()) {
            String name = rs.getString("name");
            System.out.print(name+"  ");
         }
         System.out.println();
      }
   }
}
The above code sample will produce the following result.The result may vary. 
Names for query SELECT * FROM emp where id=1 are
ravi  
Names for query select name from emp where name like 'ravi_' are
ravi2  ravi3  
Names for query select name from emp where name like 'ravi%' are
ravi  ravi2  ravi3  ravi123  ravi222  

 Print
 Add Notes
 Bookmark this page
How to read and write unicode (UTF-8) files in Python?

The io module is now recommended and is compatible with Python 3's open syntax: The following code is used to read and write to unicode(UTF-8) files in Python
import io
with io.open(filename,'r',encoding='utf8') as f:
    text = f.read()
# process Unicode text
with io.open(filename,'w',encoding='utf8') as f:
    f.write(text)
C++ String Library - compare

It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments.
Following is the declaration for std::string::compare.
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen) const;
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str,
             size_t subpos, size_t sublen = npos) const;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
It returns a signed integral indicating the relation between the strings.
if an exception is thrown, there are no changes in the string.
In below example for std::string::compare.
#include <iostream>
#include <string>

int main () {
   std::string str1 ("green mango");
   std::string str2 ("red mango");

   if (str1.compare(str2) != 0)
      std::cout << str1 << " is not " << str2 << '\n';

   if (str1.compare(6,5,"mango") == 0)
      std::cout << "still, " << str1 << " is an mango\n";

   if (str2.compare(str2.size()-5,5,"mango") == 0)
      std::cout << "and " << str2 << " is also an mango\n";

   if (str1.compare(6,5,str2,4,5) == 0)
      std::cout << "therefore, both are mangos\n";

   return 0;
}
The sample output should be like this −
green mango is not red mango
still, green mango is an mango
and red mango is also an mango
therefore, both are mangos

 Print
 Add Notes
 Bookmark this page
Relational and comparison operators in C++

In C Programming, the values keep in 2 variables can be compared using following operators and relation between them will be determined. These operators are called relational operators. Various C++ relational operators available are-
You can use these operators for checking the relationship between the operands. These operators are mostly used in conditional statements and loops to find a relation between 2 operands and act accordingly. For example,
#include<iostream>
using namespace std;

int main() {
   int a = 3, b = 2;

   if(a < b) {
      cout<< a << " is less than " << b;
   }
   else if(a > b) {
      cout<< a << " is greater than " << b;
   }
   else if(a == b){
      cout << a << " is equal to " << b;
   }
   return 0;
}
This will give the output −
3 is greater than 2
ASCII art using Python pyfiglet module

The ASCII text can be used to display many stylish texts by using the module pyfiglet. After installing this module we can use it to control the font that can be used to display the result. In the below program we see various results by choosing various font types.
# import pyfiglet module
import pyfiglet
#Text in default font
out = pyfiglet.figlet_format("Point")
print(out)
Running the above code gives us the following result −
# import pyfiglet module
import pyfiglet
#Text in slant font
out = pyfiglet.figlet_format("Point", font="slant")
print(out)
Running the above code gives us the following result −
# import pyfiglet module
import pyfiglet
#Text in 3D font
out = pyfiglet.figlet_format("Point", font="3-d")
print(out)
Running the above code gives us the following result −
# import pyfiglet module
import pyfiglet
#Text in 3×5 font
out = pyfiglet.figlet_format("Point", font="3x5")
print(out)
Running the above code gives us the following result −
import pyfiglet
#Text in alligator font
out = pyfiglet.figlet_format("Point", font="alligator")
print(out)
Running the above code gives us the following result −
import pyfiglet
#Text in dot matrix font
out = pyfiglet.figlet_format("Point", font="dotmatrix")
print(out)
Running the above code gives us the following result −
import pyfiglet
#Text in bubble font
out = pyfiglet.figlet_format("Point", font="bubble")
print(out)
Running the above code gives us the following result −
 _   _   _   _   _
 / \ / \ / \ / \ / \
( P | o | i | n | t )
 \_/ \_/ \_/ \_/ \_/
import pyfiglet
# Text in digital font
out = pyfiglet.figlet_format("Point", font = "digital" )
print(out)
Running the above code gives us the following result −
+-+-+-+-+-+
|P|o|i|n|t|
+-+-+-+-+-+
upper_bound and lower_bound for non increasing vector in c++ - GeeksforGeeks

20 May, 2020
The lower_bound() and upper_bound() functions, by default works on non-decreasing array. The lower_bound() function finds iterator of first element that does not compare less to given element. The upper_bound() function returns iterator to the first element that is greater.
Given an array converting this to a non-increasing vector, applying the std:: upper_bound and std:: lower_bound function to the vector
For array sorted in a non-increasing array, lower_bound() finds iterator to the first element that does not compare greater than to given element. upper_bound() finds iterator to the first element that is smaller than the given element. We use greater() for this purpose.
// C++ program to demonstrate the working of lower_bound()// and upper_bound() for array sorted in non-decreasing// array,#include <algorithm>#include <iostream>#include <vector>  int main(){    int unsorted[10] = { 3, 3, 2, 1, 5, 5, 4, 3, 7, 8 };    std::vector<int> v(unsorted, unsorted + 10);      // sorting vector in non increasing order. Vector    // becomes {8, 7, 5, 5, 4, 3, 3, 3, 2, 1}    std::sort(v.begin(), v.end(), std::greater<int>());      std::vector<int>::iterator low, up;    low = std::lower_bound(v.begin(), v.end(), 3, std::greater<int>());             up = std::upper_bound(v.begin(), v.end(), 5, std::greater<int>());                std::cout << "lower_bound at position " << (low - v.begin()) << '\n';    std::cout << "upper_bound at position " << (up - v.begin()) << '\n';      return 0;}
lower_bound at position 5
upper_bound at position 4

harshitkathuria14
cpp-algorithm-library
cpp-binary-search
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Queue in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Perl | substitution Operator - GeeksforGeeks

07 May, 2019
Substitution Operator or ‘s’ operator in Perl is used to substitute a text of the string with some pattern specified by the user.
Syntax: s/text/pattern
Returns: 0 on failure and number of substitutions on success
Example 1:
#!/usr/bin/perl -w  # String in which text # is to be replaced$string = "GeeksforGeeks";  # Use of s operator to replace# text with pattern$string =~ s/for/to/;  # Printing the updated stringprint "$string\n";
GeekstoGeeks

Example 2:
#!/usr/bin/perl -w  # String in which text # is to be replaced$string = "Hello all!!! Welcome here";  # Use of s operator to replace# text with pattern$string =~ s/here/to Geeks/;  # Printing the updated stringprint "$string\n";
Hello all!!! Welcome to Geeks

perl-operators
Perl-String-Operators
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | join() Function
Perl | Basic Syntax of a Perl Program
Perl | Boolean Values
Perl | sleep() Function
Perl | Subroutines or Functions
Perl | Inheritance in OOPs
HTML | currentTarget Event Property - GeeksforGeeks

18 Jan, 2019
The currentTarget event property is used for returning the element whose event listeners are responsible for triggering the event. The currentTarget event property is generally used during capturing and bubbling.
Syntax :
event.currentTarget
Below program illustrates the currentTarget event property :
Example: Getting the element whose event listeners triggered a specific event.
<!DOCTYPE html><html>  <head>    <title>currentTarget Event Property in HTML</title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body onclick="MyEvent(event)">      <h1>GeeksforGeeks</h1>    <h2>currentTarget Event Property</h2>      <p>Click on this line to receive an       alert box with the element whose       event listener triggered the event.</p>      <script>        function MyEvent(event) {            alert(event.currentTarget.nodeName);        }    </script>  </body>  </html>       
Output:
Before clicking the button:
After clicking the button:
Supported Browsers:
Opera
Internet Explorer
Google Chrome
Firefox
Apple Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Property
Web technologies
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 ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
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 create optional arguments in PHP ? - GeeksforGeeks

27 Apr, 2020
Arguments that do not stop the function from working even though there is nothing passed to it are known as optional arguments. Arguments whose presence is completely optional, their value will be taken by the program if provided. But if no value is given for a certain argument, the program will not halt. These arguments are given rise by usually providing the function with a default value for the parameter. Now, if the function is given with the value of the argument during the call, the given arguments overwrite the default one and the program continues normally. But if the call doesn’t provide the function with any value, the program continues normally with the default ones.
The idea here is to create such optional arguments within are program. This will as mentioned will be carried out using the default value.
Flow chart: Although the concept is pretty straight-forward but here is a flow chart to understand better.
Below examples illustrate the optional arguments in PHP.
Example 1:
<?phpfunction travel($place = "Sweden"){  return "Traveling to $place.\n";}echo travel();echo travel("Australia");echo travel("Tokyo");?>
Output:
Travelling to Sweden. 
Traveling to Australia. 
Traveling to Tokyo.
Example 2: In this example it confirms that the timer is set.
<?phpfunction timer($hour=00, $min=00, $sec=00){   $time="$hour : $min : $sec.";  return "Timer set for $time \n";}echo timer();echo timer(10, 30, );echo timer(00, 20, 40);?>
Output:
Timer set for 0 : 0 : 0. 
Timer set for 10 : 30 : 0. 
Timer set for 0 : 20 : 40.
PHP-Misc
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
HTML | DOM console.log() Method - GeeksforGeeks

23 Jul, 2019
The console.log() method in HTML is used for writing a message in the console. It indicates an important message during testing of any program. The message is sent as a parameter to the console.log() method.
Syntax:
console.log( message )
Parameters: This method accepts single parameter message which is mandatory and used to specify the information to be written on the console.
Below programs illustrate the console.log() method in HTML:Example 1:
<!DOCTYPE html><html>  <head>    <title>DOM console.log() Method</title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>DOM console.log() Method</h2>    <p>        To view the message in the console         press the F12 key on your keyboard.    </p>    <p>        To view the message, double click        the button below:    </p>    <br>    <button ondblclick="log_console()">        View Message    </button>    <script>        function log_console() {            console.log                ("GeeksforGeeks is a portal for geeks.");        }    </script></body>  </html>
Output:Console View:
Example 2: Displaying an object while using console.log() method
<!DOCTYPE html><html>  <head>    <title>DOM console.log() Method</title>    <style>        h1 {            color: green;        }                  h2 {            font-family: Impact;        }                  body {            text-align: center;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>DOM console.log( ) Method</h2>    <p>        To view the message in the console        press the F12 key on your keyboard.    </p>    <p>        To view the message, double click        the button below:    </p>    <br>    <button ondblclick="log_console()">        View Message    </button>    <script>        function log_console() {            var MyElement = {                Product: "Coca Cola",                Type: "Beverage"            };            console.log(MyElement);        }    </script></body>  </html>
Output:Console View:
Supported Browsers: The browser supported by console.log() method are listed below:
Google Chrome
Internet Explorer 8.0
Firefox 4.0
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
What is the use of UseIISIntegration in C# Asp.net Core?

All ASP.NET Core applications require a WebHost object that essentially serves as
the application and web server. WebHostBuilder is used to configure and create the
WebHost. You will normally see UseKestrel() and UseIISIntegration() in the
WebHostBuilder setup code.
UseKestrel() − This registers the IServer interface for Kestrel as the server that will be used to host your application.
In the future, there could be other options, including WebListener which will be Windows only.
UseIISIntegration() − This tells ASP.NET that IIS will be working as a reverse proxy in front of Kestrel.
This then specifies some settings around which port Kestrel should
listen on, forwarding headers, and other details.
public class Program{
   public static void Main(string[] args){
      var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseIISIntegration()
      .UseStartup()
      .Build();
      host.Run();
   }
}
Until ASP.NET Core 2.2, ASP.NET Core was hosted out-of-process in IIS,we had
two processes for an application −
w3wp.exe, the IIS process
dotnet.exe, the ASP.NET Core process, where the Kestrel web server was started. This means that IIS and Kestrel were communicating between those two processes.
For this scenario, we use UseIISIntegration.
Java program to find the roots of a quadratic equation

Roots of a quadratic equation are determined by the following formula:
x=−b±b2−4ac2a
To calculate the roots −
Calculate the determinant value (b*b)-(4*a*c).
If determinant is greater than 0 roots are [-b +squareroot(determinant)]/2*a and [-b -squareroot(determinant)]/2*a.
If determinant is equal to 0 root value is (-b+Math.sqrt(d))/(2*a)
import java.util.Scanner;
public class RootsOfQuadraticEquation {
   public static void main(String args[]){
      double secondRoot = 0, firstRoot = 0;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of a ::");
      double a = sc.nextDouble();

      System.out.println("Enter the value of b ::");
      double b = sc.nextDouble();

      System.out.println("Enter the value of c ::");
      double c = sc.nextDouble();

      double determinant = (b*b)-(4*a*c);
      double sqrt = Math.sqrt(determinant);

      if(determinant>0){
         firstRoot = (-b + sqrt)/(2*a);
         secondRoot = (-b - sqrt)/(2*a);
         System.out.println("Roots are :: "+ firstRoot +" and "+secondRoot);
      }else if(determinant == 0){
         System.out.println("Root is :: "+(-b + sqrt)/(2*a));
      }
   }
}
Enter the value of a ::
15
Enter the value of b ::
68
Enter the value of c ::
3
Roots are :: -0.044555558333472335 and -4.488777774999861
GATE | GATE-CS-2004 | Question 65 - GeeksforGeeks

27 Jun, 2018
Consider a small two-way set-associative cache memory, consisting of four blocks. For choosing the block to be replaced, use the least recently used (LRU) scheme. The number of cache misses for the following sequence of block addresses is 8, 12, 0, 12, 8(A) 2(B) 3(C) 4(D) 5Answer: (C)Explanation:
8, 12, 0, 12, 8

Miss 8
Miss 12
Miss 0

No miss for 12
Again a miss for 8
Total misses = 4
Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 65
GATE | Gate IT 2007 | Question 30
GATE | GATE-CS-2000 | Question 43
BigDecimal sqrt() Method in Java with Examples - GeeksforGeeks

29 May, 2019
The java.math.BigDecimal.sqrt(MathContext mc) is an inbuilt function added in Java SE 9 & JDK 9 which returns BigDecimal value of square root of a BigDecimal on which sqrt() method is applied with rounding according to the context settings.
Syntax:
public BigDecimal sqrt(MathContext mc)

Parameters: This method accepts a parameter mc of type MathContext for context settings.
Return Value: This method returns an approximation to the square root of this with rounding according to the context settings.
Exception: The method throws ArithmeticException for following conditions.
If BigDecimal number is less than zero.
If an exact result is requested (Precision = 0) and there is no finite decimal expansion of the exact result.
If the exact result cannot fit in Precision digits.
Note: This method is only available from JDK 9.
Below programs are used to illustrate the sqrt() method of BigDecimal:
Example 1:
// Java program to demonstrate sqrt() method  import java.math.*;  public class GFG {      public static void main(String[] args)    {          // Creating a BigDecimal object        BigDecimal a, squareRoot;          a = new BigDecimal("100000000000000000000");          // Set precision to 10        MathContext mc            = new MathContext(10);          // calculate square root of bigDecimal        // using sqrt() method        squareRoot = a.sqrt(mc);          // print result        System.out.println("Square root value of " + a                           + " is " + squareRoot);    }}
Square root value of 100000000000000000000 is 1.000000000E+10

Example 2: Showing Exception thrown by sqrt() method.
// Java program to demonstrate sqrt() method  import java.math.*;  class GFG {      public static void main(String[] args)    {          // Creating a BigDecimal object        BigDecimal a, squareRoot;          a = new BigDecimal("-4");          // Set precision to 10        MathContext mc            = new MathContext(10);          // calculate square root of bigDecimal        // using sqrt() method        try {            squareRoot = a.sqrt(mc);              // print result            System.out.println("Square root"                               + " value of " + a                               + " is " + squareRoot);        }        catch (Exception e) {            System.out.println(e);        }    }}
java.lang.ArithmeticException: Attempted square root of negative BigDecimal

References: https://docs.oracle.com/javase/9/docs/api/java/math/BigDecimal.html#sqrt-java.math.MathContext-
Java-BigDecimal
Java-Functions
Java-math-package
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Python 3 - String strip() Method

The strip() method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
Following is the syntax for strip() method −
str.strip([chars]);

chars − The characters to be removed from beginning or end of the string.
This method returns a copy of the string in which all chars have been stripped from the beginning and the end of the string.
The following example shows the usage of strip() method.
#!/usr/bin/python3

str = "*****this is string example....wow!!!*****"
print (str.strip( '*' ))
When we run above program, it produces the following result −
this is string example....wow!!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Program to find diagonal sum of a matrix in Python

Suppose we have a square matrix; we have to find the sum of the matrix diagonals. So only include the sum of all of the elements on the primary diagonal and all the elements on the secondary diagonal and ignore the crossing element.
So, if the input is like
then the output will be The primary diagonal elements are [10,15,12,3] sum is 40, secondary diagonal [6,3,8,2] sum is 19, so total sum 59.
To solve this, we will follow these steps −
m := row count of matrix
m := row count of matrix
if m is same as 1, thenreturn matrix[0, 0]
if m is same as 1, then
return matrix[0, 0]
return matrix[0, 0]
count := 0
count := 0
for i in range 0 to m - 1, docount := count + matrix[i, i]count := count + matrix[i, (-1 - i)]
for i in range 0 to m - 1, do
count := count + matrix[i, i]
count := count + matrix[i, i]
count := count + matrix[i, (-1 - i)]
count := count + matrix[i, (-1 - i)]
if m is odd, thenind := quotient of m/2count := count - matrix[ind, ind]
if m is odd, then
ind := quotient of m/2
ind := quotient of m/2
count := count - matrix[ind, ind]
count := count - matrix[ind, ind]
return count
return count
Let us see the following implementation to get better understanding −
 Live Demo
def solve(matrix):
   m = len(matrix)
   if m == 1: return matrix[0][0]

   count = 0
   for i in range(m):
      count += matrix[i][i]
      count += matrix[i][-1 - i]

   if m % 2 == 1: count -= matrix[m // 2][m // 2]

   return count

matrix = [[10,5,9,6],[8,15,3,2],[3,8,12,3],[2,11,7,3],]
print(solve(matrix))
[[10,5,9,6],[8,15,3,2],[3,8,12,3],[2,11,7,3]]
59
How to create cumulative sum chart with count on Y-axis in R using ggplot2?

Cumulative sums are often used to display the running totals of values and these sums also help us to identify the overall total. In this way, we can analyze the variation in the running totals over time. To create the cumulative sum chart with count on Y-axis we can use stat_bin function of ggplot2 package.
Consider the below data frame −
 Live Demo
> x<-rnorm(50,1.5)
> df<-data.frame(x)
> head(df,20)
      x
1 1.755900133
2 1.185746239
3 0.821489888
4 1.358420721
5 2.719636441
6 2.885153151
7 1.131452570
8 0.302981998
9 0.433865254
10 2.373338327
11 0.428436149
12 1.835789725
13 2.600838211
14 2.108302471
15 1.164818373
16 1.547473189
17 2.870272096
18 1.790039472
19 -0.006816034
20 3.510828517
> tail(df,20)
      x
31 3.3137587
32 1.0945959
33 1.5224898
34 2.2356911
35 1.5971496
36 2.6768012
37 1.8453177
38 2.5820093
39 0.4334084
40 2.0123960
41 2.6038358
42 2.3482770
43 1.5645365
44 2.4985221
45 2.5645833
46 1.5095937
47 0.2791473
48 3.8218481
49 2.4270537
50 1.7294788
> sort(df$x)
[1] -0.456686181 -0.006816034 0.279147319 0.302981998 0.428436149
[6] 0.433408448 0.433865254 0.660931044 0.821489888 1.094595884
[11] 1.131452570 1.160498413 1.164818373 1.185746239 1.305236133
[16] 1.321902603 1.358420721 1.509593653 1.522489810 1.547473189
[21] 1.564536491 1.597149639 1.729478762 1.738331537 1.755900133
[26] 1.790039472 1.835789725 1.845317696 1.850792130 2.012395996
[31] 2.075640869 2.108302471 2.177636502 2.235691108 2.348277047
[36] 2.373338327 2.427053655 2.498522135 2.564583339 2.582009262
[41] 2.600838211 2.603835849 2.676801213 2.719636441 2.870272096
[46] 2.885153151 3.265762606 3.313758715 3.510828517 3.821848116
Loading ggplot2 package and creating cumulative sum chart with count on Y-axis −
> library(ggplot2)
> ggplot(df,aes(x))+stat_bin(aes(y=cumsum(..count..)),geom="step",bins=30)
Forwarding ref in React.js

Passing a ref to the child component is called as forwarding ref. React provides a createRef function to create a ref for element.
forwardRef is a function to pass the ref to child component.
// ExampleRef.js
const ExampleTextInput = React.forwardRef((props, ref) => (
   <input type="text" placeholder="Welcome" ref={ref} />
));
const exampleInputRef = React.createRef();
class NewTextInput extends React.Component {
   handleFormSubmit = e => {
      e.preventDefault();
      console.log(“Entered value: ”+exampleInputRef.current.value);
   };
   render() {
      return (
         <div>
            <form onSubmit={e => this.handleFormSubmit(e)}>
               <NewTextInput ref={exampleInputRef} />
               <button>Submit</button>
            </form>
         </div>
      );
   }
}
Ref forwarding as name suggest is just receiving the ref and passing it to the children component.
The child component input inside the ExampleTextInput receives the ref through the React.forwardRef function.
React.createRef used to create a ref and assign it to a variable element
Attached the ref created above to the component using as a jsx attribute
The component on which ref is used, has a forwardref function which accepts the props and ref as an argument.
The ref argument is passed to the child component
The child component uses the ref as an jsx attribute
We forward this ref argument down to <button ref={ref}> by specifying it as a JSX attribute.
When the ref is attached, ref.current will point to the <button> DOM node.
Use of forwardRef with higher order component −
const InputHoc = ProvidedComponent => {
   const forwardRef = (props, ref) => {
      const onValueInput = () => console.log(“ref value: ”+ref.current.value);
      return < ProvidedComponent
      forwardedRef={ref}
      onChange={onValueInput}
      {...props} />;
   };
   return React.forwardRef(forwardRef);
};
Java Program to Check Armstrong Number between Two Integers - GeeksforGeeks

17 Mar, 2021
A positive integer with digits p, q, r, s..., is known as an Armstrong number of order n if the following condition is fulfilled.
pqrs... = pn + qn + rn + sn +....
Example:
370 = 3*3*3 + 7*7*7 + 0 
   =  27 + 343 + 0
   =  370
Therefore, 370 is an Armstrong number.
Examples:
Input : 100 200
Output :153
Explanation : 100 and 200 are given  
two integers.
 153 = 1*1*1 + 5*5*5 + 3*3*3  
     = 1 + 125 + 27
     =  153
Therefore, only 153 is an Armstrong number between 100 and 200.
Approach:
Firstly, we will traverse through all the numbers in the given range. Then, for every number, we have to count the number of digits in it. If the number of digits in the current number is n then, find the sum of (n-th) power of all the digits in the number stated. And if the sum is equal to the current number i, then print the number.
Example:
Java
// JAVA program to find Armstrong// numbers between two integersimport java.io.*;import java.math.*;  class gfg {      // Function to print Armstrong    // Numbers between two integers    static void ArmstrongNum(int l, int h)    {        for (int j = l + 1; j < h; ++j) {              // Calculating number of digits            int y = j;            int N = 0;            while (y != 0) {                y /= 10;                ++N;            }              // Calculating the sum of nth            // power of all the digits            int sum_power = 0;            y = j;            while (y != 0) {                int d = y % 10;                sum_power += Math.pow(d, N);                y /= 10;            }              // Checking if the current number            // i is equal to the sum of nth            // power of all the digits            if (sum_power == j)                System.out.print(j + " ");        }    }      // The Driver code    public static void main(String args[])    {        int n1 = 50;        int n2 = 500;        ArmstrongNum(n1, n2);        System.out.println();    }}
153 370 371 407 

Similarly, we can find Armstrong numbers within any given range.
java-basics
Java
Java Programs
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
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
How to check if type of a variable is string in Python?

We can use the isinstance(var, class) to check if the var is instance of given class. In Python 2.x the base class of str and unicode is basestring. So we can use it as follows:
>>> s = 'A string'
>>> isinstance(s, basestring)
True
>>> isinstance(s, str)
True
>>> isinstance(10, basestring)
False
Note: In Python 3.x, basestring is not defined, hence we have to use str instead of it. For example:
>>> s = 'A string'
>>> isinstance(s, str)
True
>>> isinstance(10, str)
False
match_results prefix() and suffix() in C++ - GeeksforGeeks

09 Aug, 2021
The match_results::prefix() is an inbuilt function in C++ which is used to get the string which is preceding the matched string in the input target string.Syntax:  
smatch_name.prefix()

Note: smatch_name is an object of match_results class.
Parameters: This function accept no parameters.Return Value: This function returns the sequence preceding the matched sequence in the target string.Note: First element always contains the whole regex match while the others contain the particular Capturing Group.Below program illustrate the above function:  
CPP
// CPP program to illustrate// match_results prefix() function#include <bits/stdc++.h>using namespace std; int main(){    string s("Geeksforgeeks is a computer science portal");    regex re("computer");     smatch match;     regex_search(s, match, re);     cout << "Prefix is: [";    if (!match.empty()) {        cout << match.prefix() << "]" << endl;    }    return 0;}
Prefix is: [Geeksforgeeks is a ]
 
The match_results::suffix() is an inbuilt function in C++ which is used to get the string which is succeeding the matched string in the input target string.Syntax:  
smatch_name.suffix()

Note: smatch_name is an object of match_results class.
Parameters: This function accepts no parameters.Return Value:T his function returns the sequence succeeding the matched sequence in the target string.Note: First element always contains the whole regex match while the others contain the particular Capturing Group.Below program illustrate the above function:  
CPP
// CPP program to illustrate// match_results suffix() function#include <bits/stdc++.h>using namespace std; int main(){    string s("Geeksforgeeks is a computer science portal");    regex re("computer");     smatch match;     regex_search(s, match, re);     cout << "Suffix is: [";    if (!match.empty()) {        cout << match.suffix() << "]" << endl;    }    return 0;}
Suffix is: [ science portal]
 
anikaseth98
adnanirshad158
ruhelaa48
cpp-class
CPP-Functions
CPP-regex
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Sorting a vector in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Convert string to char array in C++
Iterators in C++ STL
Inline Functions in C++
List in C++ Standard Template Library (STL)
new and delete operators in C++ for dynamic memory