code-rag-bench/online-tutorials huggingface dataset:
Python – Find union of multiple sets

02 Feb, 2021
Given multiple sets list, the task is to write a Python program to find union of each set.
Examples:
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]
Output : {1, 2, 3, 4, 5, 7, 8, 9}
Explanation : All elements from all sets included. Duplicates removed.
Input : test_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}]
Output : {1, 2, 3, 4, 5, 7, 8}
Explanation : All elements from all sets included. Duplicates removed.
Method #1 : Using union() + * operator
In this, we perform task of getting union using union(), and * operator is used to perform task of packing all the sets together.
Python3
# Python3 code to demonstrate working of# Union multiple sets# Using union() + * operator  # initializing listtest_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]  # printing original listprint("The original list is : " + str(test_list))  # * operator packs sets for unionres = set().union(*test_list)  # printing resultprint("Multiple set union : " + str(res))
Output:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Method #2 : Using chain.from_iterable() + * operator
In this, we perform task of union, which in turn is flattening using from_iterable().
Python3
# Python3 code to demonstrate working of# Union multiple sets# Using chain.from_iterable() + * operatorfrom itertools import chain  # initializing listtest_list = [{4, 3, 5, 2}, {8, 4, 7, 2}, {1, 2, 3, 4}, {9, 5, 3, 7}]  # printing original listprint("The original list is : " + str(test_list))  # * operator packs sets for unionres = set(chain(*test_list))  # printing resultprint("Multiple set union : " + str(res))
Output:
The original list is : [{2, 3, 4, 5}, {8, 2, 4, 7}, {1, 2, 3, 4}, {9, 3, 5, 7}]
Multiple set union : {1, 2, 3, 4, 5, 7, 8, 9}
Python set-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Storing money amounts in MySQL?

To store money amounts in MySQL, the best choice is to use DECIMAL data type or NUMERIC type. Float data type is not a good choice for money amounts. It gives some rounding errors. Therefore, avoid float for money amounts.
Let us first create a table with data type DECIMAL. The following is the query to create a table −
mysql> create table MoneyStorageDemo
   -> (
   -> Amount DECIMAL(4,2)
   -> );
Query OK, 0 rows affected (0.44 sec)
Inserting some values into the table with the help of insert command. The query is as follows −
mysql> insert into MoneyStorageDemo values(50.2);
Query OK, 1 row affected (0.10 sec)
mysql> insert into MoneyStorageDemo values(5.50);
Query OK, 1 row affected (0.32 sec)
mysql> insert into MoneyStorageDemo values(10.4);
Query OK, 1 row affected (0.26 sec)
Now you can display all the values from the table with the help of select statement. The query is as follows −
mysql> select *from MoneyStorageDemo;
Here is the output −
+--------+
| Amount |
+--------+
| 50.20  |
| 5.50   |
| 10.40  |
+--------+
3 rows in set (0.00 sec)
Is it mandatory to override the default methods of an interface in Java?

The default methods are introduced in an interface since Java8. Unlike other abstract methods these are the methods can have a default implementation. If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface.
In short, you can access the default methods of an interface using the objects of the implementing classes.
interface MyInterface{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface");
   }
}
public class InterfaceExample implements MyInterface{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}
display method of MyInterface
But, when your class implements two interfaces, and if they both have methods with same name and prototype. You must override this method else a compile time error is generated.
interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      // obj.display();
   }
}
InterfaceExample.java:14: error: class InterfaceExample inherits unrelated defaults for display() from types MyInterface1 and MyInterface2
public class InterfaceExample implements MyInterface1, MyInterface2{
^
1 error
To resolve this you need to override either (or, both) of the display() methods in the implementing class −
interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}
public class InterfaceExample implements MyInterface1, MyInterface2{
   public void display() {
      MyInterface1.super.display();
      //or,
      MyInterface2.super.display();
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.display();
   }
}
display method of MyInterface1
display method of MyInterface2
How can we delete multiple rows from a MySQL table?

We can use DELETE statement along with a WHERE clause, which identifies those multiple rows, to delete multiple rows from MySQL table.
mysql> Select * from names;
+------+-----------+
| id   | name      |
+------+-----------+
| 1    | Rahul     |
| 2    | Gaurav    |
| 3    | Raman     |
| 5    | Ram       |
+------+-----------+
4 rows in set (0.00 sec)

mysql> DELETE from names WHERE id > 2;
Query OK, 2 rows affected (0.04 sec)
The query above will delete multiple rows because WHERE clause identify two rows having id > 2 from table ‘names’.
mysql> Select * from names;
+------+-----------+
| id   | name      |
+------+-----------+
| 1    | Rahul     |
| 2    | Gaurav    |
+------+-----------+
2 rows in set (0.00 sec)
Difference between Early and Late Binding in Java - GeeksforGeeks

17 Jun, 2019
Early Binding: The binding which can be resolved at compile time by the compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time.
Example:
public class NewClass {    public static class superclass {        static void print()        {            System.out.println("print in superclass.");        }    }    public static class subclass extends superclass {        static void print()        {            System.out.println("print in subclass.");        }    }      public static void main(String[] args)    {        superclass A = new superclass();        superclass B = new subclass();        A.print();        B.print();    }}
print in superclass.
print in superclass.

Late binding: In the late binding or dynamic binding, the compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.
Example:
public class NewClass {    public static class superclass {        void print()        {            System.out.println("print in superclass.");        }    }      public static class subclass extends superclass {        @Override        void print()        {            System.out.println("print in subclass.");        }    }      public static void main(String[] args)    {        superclass A = new superclass();        superclass B = new subclass();        A.print();        B.print();    }}
print in superclass.
print in subclass.

Difference table between early and late binding:
Picked
Difference Between
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference Between Spark DataFrame and Pandas DataFrame
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Internal and External fragmentation
Difference between Prim's and Kruskal's algorithm for MST
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java
JavaScript modules

Modules were introduced in ES 2015. Modules were introduced to break over code into smaller pieces. The modules could contain classes or functions in them. Keywords export and import are used to export variables, functions, objects and import them in other files.
Note − To run this example you will need to run a localhost server.
Following is the code for modules in JavaScript
INDEX.html
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color:blueviolet;
   }
</style>
</head>
<body>
<h1>JavaScript Modules</h1>
<button class="Btn">IMPORT</button>
<div class="result"></div>
<h3>Click on the above button to import module</h3>
<script src="script.js" type="module"></script>
<script src="sample.js" type="module"></script>
</body>
</html>
script.js
import test from './sample.js';
document.querySelector('.Btn').addEventListener('click',()=>{
   test();
})
sample.js
let resultEle = document.querySelector(".result");
export default function testImport(){
   resultEle.innerHTML = 'Module testImport has been imported';
}
On clicking the ‘IMPORT’ button −
Implement and set DOUBLE length in MySQL

To implement DOUBLE in MySQL, the syntax is as follows −
create table yourTableName
     (
     yourColumnName double(5,2) unsigned
);
Let us first create a table −
mysql> create table DemoTable1814
     (
     Amount double(5,2) unsigned
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1814 values(1.98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1814 values(100.24);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1814 values(198.50);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1814;
This will produce the following output −
+--------+
| Amount |
+--------+
|   1.98 |
| 100.24 |
| 198.50 |
+--------+
3 rows in set (0.00 sec)
HTML5 - datetime

A date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC.
<!DOCTYPE HTML>
<html>
   
   <body>
      
      <form action = "/cgi-bin/html5.cgi" method = "get">
         Date and Time : <input type = "datetime" name = "newinput" />
         <input type = "submit" value = "submit" />
      </form>
   
   </body>
</html>

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to copy a String into another String in C#

To copy a String into another String, the code is as follows −
 Live Demo
using System;
public class Demo {
   static public void Main(){
      string str1 = "Kevin";
      string str2 = String.Copy(str1);
      Console.WriteLine("String1 = "+str1);
      Console.WriteLine("String2 = "+str2);
   }
}
This will produce the following output −
String1 = Kevin
String2 = Kevin
Let us now see another example −
 Live Demo
using System;
public class Demo {
   static public void Main(){
      string str1 = "Maisie";
      string str2 = "Ryan";
      Console.WriteLine("String1 (Before copying) = "+str1);
      Console.WriteLine("String2 (Before copying) = "+str2);
      str2 = String.Copy(str1);
      Console.WriteLine("String1 = "+str1);
      Console.WriteLine("String2 (Updated) = "+str2);
   }
}
This will produce the following output −
String1 (Before copying) = Maisie String2 (Before copying) = Ryan
String1 = Maisie
String2 (Updated) = Maisie
GATE | GATE-CS-2006 | Question 59 - GeeksforGeeks

15 Sep, 2021
Consider the following translation scheme.S → ERR → *E{print(“*”);}R | εE → F + E {print(“+”);} | FF → (S) | id {print(id.value);}Here id is a token that represents an integer and id.value represents the corresponding integer value. For an input ‘2 * 3 + 4’, this translation scheme prints(A) 2 * 3 + 4(B) 2 * +3 4(C) 2 3 * 4 +(D) 2 3 4+*Answer: (D)Explanation: Background Required to solve the question – Syntax Directed Translation andParse Tree Construction.
Explanation : We are given L-Attributed Syntax Directed Translation as
semantic actions like printf statements are inserted anywhere on the 
RHS of production (R → *E{print(“*”);}R). After constructing the parse tree 
as shown below from the given grammar, we will follow depth first order left 
to right evaluation in order to generate the final output.

Parse Tree:
Just follow the arrows in the picture (This is actually Depth first 
left to right evaluation ) and the moment we take exit from any child 
which is printf statement in this question, we print that symbol which 
can be a integer value or ‘*’ or ‘+’.

Evaluation :
This explanation has been contributed by Pranjul Ahuja.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | 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:0050:18 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" 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-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
nested if statement in java

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement.
The syntax for a nested if...else is as follows −
if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
   if(Boolean_expression 2) {
      // Executes when the Boolean expression 2 is true
   }
}

You can nest else if...else in the similar way as we have nested if statement.
public class Test {

   public static void main(String args[]) {
      int x = 30;
      int y = 10;

      if( x == 30 ) {
         if( y == 10 ) {
            System.out.print("X = 30 and Y = 10");
         }
      }
   }
}
This will produce the following result −
X = 30 and Y = 10


    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
MySQL - Clone Tables

There may be a situation when you need an exact copy of a table and CREATE TABLE ... SELECT doesn't suit your purposes because the copy must include the same indexes, default values and so forth.
You can handle this situation by following the steps given below −
Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
Use SHOW CREATE TABLE to get a CREATE TABLE statement that specifies the source table's structure, indexes and all.
Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table.
Modify the statement to change the table name to that of the clone table and execute the statement. This way, you will have the exact clone table.
Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.
Optionally, if you need the table contents copied as well, issue an INSERT INTO ... SELECT statement, too.
Try out the following example to create a clone table for tutorials_tbl.
Step 1 − Get the complete structure about the table.
mysql> SHOW CREATE TABLE tutorials_tbl \G;
*************************** 1. row ***************************
      Table: tutorials_tbl
Create Table: CREATE TABLE `tutorials_tbl` (
   `tutorial_id` int(11) NOT NULL auto_increment,
   `tutorial_title` varchar(100) NOT NULL default '',
   `tutorial_author` varchar(40) NOT NULL default '',
   `submission_date` date default NULL,
   PRIMARY KEY  (`tutorial_id`),
   UNIQUE KEY `AUTHOR_INDEX` (`tutorial_author`)
) TYPE = MyISAM
1 row in set (0.00 sec)

ERROR:
No query specified
Step 2 − Rename this table and create another table.
mysql> CREATE TABLE clone_tbl (
   -> tutorial_id int(11) NOT NULL auto_increment,
   -> tutorial_title varchar(100) NOT NULL default '',
   -> tutorial_author varchar(40) NOT NULL default '',
   -> submission_date date default NULL,
   -> PRIMARY KEY  (tutorial_id),
   -> UNIQUE KEY AUTHOR_INDEX (tutorial_author)
-> ) TYPE = MyISAM;
Query OK, 0 rows affected (1.80 sec)
Step 3 − After executing step 2, you will create a clone table in your database. If you want to copy data from old table then you can do it by using INSERT INTO... SELECT statement.
mysql> INSERT INTO clone_tbl (tutorial_id,
   -> tutorial_title,
   -> tutorial_author,
   -> submission_date)
   
   -> SELECT tutorial_id,tutorial_title,
   -> tutorial_author,submission_date
   -> FROM tutorials_tbl;
Query OK, 3 rows affected (0.07 sec)
Records: 3  Duplicates: 0  Warnings: 0
Finally, you will have an exact clone table as you wanted to have.

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
C++ Program for Recursive Bubble Sort - GeeksforGeeks

28 Jun, 2021
Background :Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Following is iterative Bubble sort algorithm :
// Iterative Bubble Sort
bubbleSort(arr[], n)
{
  for (i = 0; i < n-1; i++)      

     // Last i elements are already in place   
     for (j = 0; j  arr[j+1])
         swap(arr[j], arr[j+1]);
} 
Recursion Idea.
Base Case: If array size is 1, return.Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.Recur for all elements except last of current subarray.
Base Case: If array size is 1, return.
Do One Pass of normal Bubble Sort. This pass fixes last element of current subarray.
Recur for all elements except last of current subarray.
// C/C++ program for recursive implementation// of Bubble sort#include <bits/stdc++.h>using namespace std;  // A function to implement bubble sortvoid bubbleSort(int arr[], int n){    // Base case    if (n == 1)        return;      // One pass of bubble sort. After    // this pass, the largest element    // is moved (or bubbled) to end.    for (int i=0; i<n-1; i++)        if (arr[i] > arr[i+1])            swap(arr[i], arr[i+1]);      // Largest element is fixed,    // recur for remaining array    bubbleSort(arr, n-1);}  /* Function to print an array */void printArray(int arr[], int n){    for (int i=0; i < n; i++)        printf("%d ", arr[i]);    printf("\n");}  // Driver program to test above functionsint main(){    int arr[] = {64, 34, 25, 12, 22, 11, 90};    int n = sizeof(arr)/sizeof(arr[0]);    bubbleSort(arr, n);    printf("Sorted array : \n");    printArray(arr, n);    return 0;}
Please refer complete article on Recursive Bubble Sort for more details!
BubbleSort
C++ Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Const keyword in C++
Program to implement Singly Linked List in C++ using class
cout in C++
Dynamic _Cast in C++
How to plot multiple data columns in a DataFrame? - GeeksforGeeks

30 Dec, 2021
Prerequisites: Pandas
Python comes with a lot of useful packages such as pandas, matplotlib, numpy etc. To use dataframe, we need pandas library and to plot columns of a dataframe, we require matplotlib. Pandas has a tight integration with Matplotlib. You can plot data directly from your DataFrame using the plot() method. 
To plot multiple data columns in single frame we simply have to pass the list of columns to the y argument of the plot function. Given below is aproper approach to do so along with example implementation.
Import module
Create or load data
Convert to dataframe
Using plot() method, specify a single column along X-axis and multiple columns as an array along Y-axis.
Display graph.
Below are few examples which illustrates the above approach to plot multiples data columns in a Dataframe.
Example 1:
Database: Bestsellers
Python3
import pandas as pdimport matplotlib.pyplot as mp # take datadata = pd.read_csv("Bestsellers.csv") # form dataframedata = data.head() df = pd.DataFrame(data, columns=["Name", "Price", "User Rating"]) # plot the dataframedf.plot(x="Name", y=["Price", "User Rating"], kind="bar", figsize=(9, 8)) # print bar graphmp.show()
Output:
Example 2:
Python3
import pandas as pdimport matplotlib.pyplot as mp # data to be plotteddata = [["New York", 8.6, 20],        ["Chicago", 2.7, 20],        ["Los Angeles", 3.9, 20],        ["Philadelphia", 1.5, 20],        ["Houston", 2.1, 20]] # form dataframe from datadf = pd.DataFrame(data, columns=["City", "Population(million)", "Year(2020)"]) # plot multiple columns such as population and year from dataframedf.plot(x="City", y=["Population(million)", "Year(2020)"],        kind="line", figsize=(10, 10)) # display plotmp.show()
Output:
gulshankumarar231
Picked
Python Pandas-exercise
Python pandas-plotting
Python-pandas
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 Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
How to read data from a file stored in XAMPP webserver using PHP ? - GeeksforGeeks

01 Dec, 2020
We have given a file stored on XAMPP server and the task is to read the file from server and display the file content on the screen using PHP. We use some PHP functions to solve this problem.
File: A file is set of data stored in a disk in different formats. For example – .txt, .exe, .pdf etc 
fopen() function:  The fopen() function in PHP is an inbuilt function which is used to open a file or a URL. It is used to bind a resource to a steam using a specific filename. The filename and mode to be checked are sent as parameters to the fopen() function and it returns a file pointer resource if a match is found and a False on failure. The error output can be hidden by adding an ‘@’ in front of the function name.
Syntax:
fopen('filename', filemode)

Here, file name is name of the file and file mode includes read(r) mode,write(w) and binary(b) mode etc.
fopen($geek, r) — Here we are opening geek file in read mode.
fopen($geek, r+) — Here we are opening geek file in read and write mode.
fopen($geek, w) — Here we are opening geek file in write mode.
fopen($geek, w+) — Here we are opening geek file in read and write mode.
fopen($geek, b) — Here we are opening geek file in read and write mode.
Requirements:
XAMPP web server — If you have not installed XAMPP/WAMP web server then please install it by using the following steps:
Link to install: https://www.apachefriends.org/download.html
Start the XAMPP Server
Open the notepad and type the below code:
PHP
<?php    // File to be read$file = "./welcome.txt";  // Opening file$f = fopen($file, "r") or     exit("Unable to open file!");  // Read file line by line until// the end of file (feof)while(!feof($f)) {    echo fgets($f)."<br />";}  // Closing filefclose($f);?>
Data in welcome.txt file are:
GEEKS FOR GEEKS IS BEST FOR COMPUTER SCIENCE
Place these two files in folder (Path is show here)
Path
 
Running the Script Type the following URL in the browser: localhost/gfg/1.php
Output:
PHP-Misc
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Different ways for passing data to view in Laravel
Create a drop-down list that options fetched from a MySQL database in PHP
How to generate PDF file using PHP ?
How to create admin login page using PHP?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to Install php-curl in Ubuntu ?
Display default initial values of DataTypes in Java

To display default initial values of a datatype, you need to just declare a variable of the same datatype and display it.
The following is a Java program to display initial values of DataTypes.
 Live Demo
public class Demo {
   boolean t;
   byte b;
   short s;
   int i;
   long l;
   float f;
   double d;
   void Display() {
      System.out.println("boolean (Initial Value) = " + t);
      System.out.println("byte (Initial Value) = " + b);
      System.out.println("short (Initial Value) = " + s);
      System.out.println("int (Initial Value) = " + i);
      System.out.println("long (Initial Value) = " + l);
      System.out.println("float (Initial Value) = " + f);
      System.out.println("double (Initial Value) = " + d);
   }
   public static void main(String[] args) {
      Demo d = new Demo();
      System.out.println("Displaying initial values...");
      d.Display();
   }
}
Displaying initial values...
boolean (Initial Value) = false
byte (Initial Value) = 0
short (Initial Value) = 0
int (Initial Value) = 0
long (Initial Value) = 0
float (Initial Value) = 0.0
double (Initial Value) = 0.0
In the above program, we have declared a variable with different datatypes.
boolean t;
byte b;
short s;
int i;
long l;
float f;
double d;
Now to get the default initial values, just print the variable declared above.
System.out.println("boolean (Initial Value) = " + t);
System.out.println("byte (Initial Value) = " + b);
System.out.println("short (Initial Value) = " + s);
System.out.println("int (Initial Value) = " + i);
System.out.println("long (Initial Value) = " + l);
System.out.println("float (Initial Value) = " + f);
System.out.println("double (Initial Value) = " + d);
The above displays the default values.
C program to print the ASCII values in a string.

An array of characters is called a string.
Given below is the declaration of a string −
char stringname [size];
For example, char string[50]; string of length 50 characters.
Using single character constant.
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants.
char string[10] = “Hello”:;
There is a control string “%s” used for accessing the string till it encounters ‘\0’.
The logic we used to print the ASCII values of a given string at runtime is as follows −
while(str[i]!='\0'){
   printf("\nASCII Value of %c = %d", str[i], str[i]);
   i++;
}
Following is the C program to print the ASCII values of a given string −
#include<stdio.h>
int main() {
   char string[50];
   int i=0;
   printf("Enter the Sentenc: ");
   gets(string);
   while(string[i]!='\0') {
      printf("\nASCII Value of %c=%d", string[i], string[i]);
      i++;
   }
   getch();
   return 0;
}
When the above program is executed, it produces the following output −
Enter the Sentence: Tutorials Point

ASCII Value of T = 84
ASCII Value of u = 117
ASCII Value of t = 116
ASCII Value of o = 111
ASCII Value of r = 114
ASCII Value of i = 105
ASCII Value of a = 97
ASCII Value of l = 108
ASCII Value of s = 115
ASCII Value of   = 32
ASCII Value of P = 80
ASCII Value of o = 111
ASCII Value of i = 105
ASCII Value of n = 110
ASCII Value of t = 116
C library function - strftime()

The C library function size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr) formats the time represented in the structure timeptr according to the formatting rules defined in format and stored into str.
Following is the declaration for strftime() function.
size_t strftime(char *str, size_t maxsize, const char *format, const struct tm *timeptr)
str − This is the pointer to the destination array where the resulting C string is copied.
str − This is the pointer to the destination array where the resulting C string is copied.
maxsize − This is the maximum number of characters to be copied to str.
maxsize − This is the maximum number of characters to be copied to str.
format − This is the C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm. The format specifiers are −
format − This is the C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in tm. The format specifiers are −
timeptr − This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below −

timeptr − This is the pointer to a tm structure that contains a calendar time broken down into its components as shown below −
struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */	
};
If the resulting C string fits in less than size characters (which includes the terminating null-character), the total number of characters copied to str (not including the terminating null-character) is returned otherwise, it returns zero.
The following example shows the usage of strftime() function.
#include <stdio.h>
#include <time.h>

int main () {
   time_t rawtime;
   struct tm *info;
   char buffer[80];

   time( &rawtime );

   info = localtime( &rawtime );

   strftime(buffer,80,"%x - %I:%M%p", info);
   printf("Formatted date & time : |%s|\n", buffer );
  
   return(0);
}
Let us compile and run the above program that will produce the following result −
Formatted date & time : |08/23/12 - 12:40AM|


    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
Python Pandas - Merge DataFrame with indicator value

To merge Pandas DataFrame, use the merge() function. In that, you can set the parameter indicator to True or False. If you want to check which dataframe has a specific record, then use −
indicator= True
As shown above, using above parameter as True, adds a column to the output DataFrame called “_merge”.
At first, let us import the pandas library with an alias −
import pandas as pd

Let us create DataFrame1 −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)


Create DataFrame2 −
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)
Now, merge DataFrames with indicator value True −
# merge DataFrames with indicator value
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="left",indicator=True)


Following is the code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],
      "Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000]

   }
)

print"\nDataFrame2 ...\n",dataFrame2

# merge DataFrames with indicator value
mergedRes = pd.merge(dataFrame1, dataFrame2, how ="left",indicator=True)
print"\nMerged dataframe...\n", mergedRes


This will produce the following output. Here, “both””in “_merge displays that both the value is in both the DataFrames −
DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3  Mustang     80
4  Bentley    110
5   Jaguar     90

DataFrame2 ...
        Car   Reg_Price
0       BMW       7000
1     Lexus       1500
2     Tesla       5000
3   Mustang       8000
4  Mercedes       9000
5    Jaguar       6000

Merged dataframe...
       Car   Units   Reg_Price    _merge
0      BMW    100      7000.0       both
1    Lexus    150      1500.0       both
2     Audi    110         NaN  left_only
3  Mustang     80      8000.0       both
4  Bentley    110         NaN  left_only
5   Jaguar     90      6000.0       both
C++ String Library - empty

It returns whether the string is empty (i.e. whether its length is 0).
Following is the declaration for std::string::empty.
bool empty() const;
bool empty() const noexcept;
none
it returns true if the string length is 0, false otherwise.
if an exception is thrown, there are no changes in the string.
In below example for std::string::empty.
#include <iostream>
#include <string>

int main () {
   std::string content;
   std::string line;
   std::cout << "Please introduce a text. Enter an empty line to finish:\n";
   do {
      getline(std::cin,line);
      content += line + '\n';
   } while (!line.empty());
   std::cout << "The text you introduced above was:\n" << content;
   return 0;
}
The sample output should be like this −
Please introduce a text. Enter an empty line to finish:
sairamrkshna mammahe

The text you introduced above was:
sairamrkshna mammahe

 Print
 Add Notes
 Bookmark this page
Powershell - If Else Statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Following is the syntax of an if...else statement −
if(Boolean_expression) {
   // Executes when the Boolean expression is true
}else {
   // Executes when the Boolean expression is false
}

If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.
$x = 30

if($x -le 20){
   write-host("This is if statement")
}else {
   write-host("This is else statement")
}
This will produce the following result −
This is else statement

An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using single if...elseif statement.
When using if, elseif, else statements there are a few points to keep in mind.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.
Following is the syntax of an if...else statement −
if(Boolean_expression 1) {
   // Executes when the Boolean expression 1 is true
}elseif(Boolean_expression 2) {
   // Executes when the Boolean expression 2 is true
}elseif(Boolean_expression 3) {
   // Executes when the Boolean expression 3 is true
}else {
   // Executes when the none of the above condition is true.
}

$x = 30

if($x -eq 10){
   write-host("Value of X is 10")
} elseif($x -eq 20){
   write-host("Value of X is 20")
} elseif($x -eq 30){
   write-host("Value of X is 30")
} else {
   write-host("This is else statement")
}
This will produce the following result −
Value of X is 30


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Write a program in Python to filter armstrong numbers in a given series

Assume you have a series and the result for filtering armstrong numbers,
original series is
0    153
1    323
2    371
3    420
4    500
dtype: int64
Armstrong numbers are:-
0    153
2    371
dtype: int64
To solve this, we will follow the steps given below −
Define a series.
Define a series.
Create an empty list and set for loop to access all the series data.
Create an empty list and set for loop to access all the series data.
Set armstrong intial value is 0 and create temp variable to store series elements one by one. It is defined below,
Set armstrong intial value is 0 and create temp variable to store series elements one by one. It is defined below,
l = []
for val in data:
   armstrong = 0
   temp = val
Create while loop and check temp>0 and calculate remainder by temp%10. Add armstrong value by taking cube of remainder and divide the temp value by 10 until it reaches 0 to terminate the loop. It is defined below,
Create while loop and check temp>0 and calculate remainder by temp%10. Add armstrong value by taking cube of remainder and divide the temp value by 10 until it reaches 0 to terminate the loop. It is defined below,
while(temp>0):
   rem = temp % 10
   armstrong = armstrong + (rem**3)
   temp = temp // 10
Set if condition to compare an original value against temp value. If it is matched, then append the values to the list.
Set if condition to compare an original value against temp value. If it is matched, then append the values to the list.
if(armstrong==val):
   l.append(val)
Finally, check the list values present in the series using isin(). It is defined below,
Finally, check the list values present in the series using isin(). It is defined below,
data[data.isin(l)]
Let’s see the below code to get a better implementation −
import pandas as pd
data = pd.Series([153,323,371,420,500])
print("original series is\n", data)
l = []
for val in data:
   armstrong = 0
   temp = val
   while(temp>0):
      rem = temp % 10
      armstrong = armstrong + (rem**3)
      temp = temp // 10
   if(armstrong==val):
      l.append(val)
print("Armstrong numbers are:-")
print(data[data.isin(l)])
original series is
0    153
1    323
2    371
3    420
4    500
dtype: int64
Armstrong numbers are:-
0    153
2    371
dtype: int64
Matplotlib – Date manipulation to show the year tick every 12 months

To make matplotlib date manipulation so that the year tick shows up every 12 months, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create d, y, s, years, months, monthsFmt and yearsFmt using Pandas, Numpy and matplotlib dates.
Use "%B" in DateFormatter to show full month names.
Ue "%Y" in DateFormatter to show years.
Create a new figure or activate an existing figure.
Add an 'ax' to the figure as part of a subplot arrangement.
Plot "dts" and "s" data points using plot() method.
Set minor or major axes locator and formatter. Set minor_locator as months so that the year tick will be displayed every 12 months.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import pandas as pd

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

d = pd.date_range("2020-01-01", "2021-06-01", freq="7D")
y = np.cumsum(np.random.normal(size=len(d)))
s = pd.Series(y, index=d)
years = mdates.YearLocator()
months = mdates.MonthLocator()
monthsFmt = mdates.DateFormatter('%B')
yearsFmt = mdates.DateFormatter('\n%Y')

dts = s.index.to_pydatetime()
fig = plt.figure()

ax = fig.add_subplot(111)
ax.plot(dts, s)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)

ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)

plt.show()
It will produce the following output
HTML DOM NodeList.forEach() Method - GeeksforGeeks

24 Jul, 2020
The forEach() method of the NodeList interface calls the callback given in parameter once for each value pair in the list, in insertion order.
Syntax:
NodeList.forEach(callback, currentValue);
Parameters:
Callback: A function to execute on each element of NodeList. It accepts 3 parameters:
currentValue: The current element to be processed in NodeList.
currentIndex (Optional): The index of the currentValue being processed in NodeList.
listobj (Optional): The NodeList on which forEach() is being applied.
thisArg (Optional): Value to use as this when executing callback.
Return value: This method returns undefined.
Example: In this example, we will create a NodeList and hence will get all values from NodeList using this method.
<!DOCTYPE HTML> <html>  <head>    <meta charset="UTF-8">    <title>HTML | DOM NodeList.forEach() Method</title></head>     <body style="text-align:center;">    <h1 style="color:green;">       GeeksforGeeks    </h1>     <p> HTML | DOM NodeList.forEach() Method    </p>      <button onclick = "Geeks()">    Click Here    </button>    <p id="a"></p>    <script>         var a = document.getElementById("a");        a.innerHTML = "elements are : "        function Geeks(){           var parentNode = document.createElement("div");             var c1 = document.createElement("p");             var c2 = document.createElement("span");             var c3 = document.createElement("h1");             parentNode.appendChild(c1);             parentNode.appendChild(c2);             parentNode.appendChild(c3);             var nodelist = parentNode.childNodes;             nodelist.forEach(             function(currentValue, currentIndex, listObj) {            a.innerHTML += "<li>"+currentValue.localName + `</li>`;                console.log(currentValue, currentIndex);               },            );}</script></body>   </html>
Output:
Before Clicking Button:
After Clicking Button: Elements are called using forEach().
In the console: Element Values can be seen.
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
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
HTML
JavaScript
Web Technologies
HTML
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 ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
How to position a div at the bottom of its container using CSS?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Create bar plot of one column in an R data frame using ggplot2.

To create bar plot of one column in an R data frame using ggplot2, we can use
rownames of the data frame as x variable in aes.
For Example, if we have a data frame called df that contains two columns say X and Y
and we want to create the bar plot of values in Y then we can use the below mentioned
command −
ggplot(df,aes(rownames(df),Y))+geom_bar(stat="identity")
Following snippet creates a sample data frame −
x1<-rpois(5,10)
x2<-rpois(5,2)
x3<-rpois(5,5)
df<-data.frame(x1,x2,x3)
df
The following dataframe is created
x1 x2 x3
1 9 2 7
2 9 2 3
3 13 1 3
4 13 3 8
5 11 1 1
To load ggplot2 package and create bar plot for data in column x2 of df on the above
created data frame, add the following code to the above snippet −
x1<-rpois(5,10)
x2<-rpois(5,2)
x3<-rpois(5,5)
df<-data.frame(x1,x2,x3)
library(ggplot2)
ggplot(df,aes(rownames(df),x2))+geom_bar(stat="identity")

If you execute the above given snippet, it generates the following Output −
What is abstraction in C#?

Abstraction and encapsulation are related features in object-oriented programming. Abstraction allows making relevant information visible and encapsulation enables a programmer to implement the desired level of abstraction.
Abstraction can be achieved using abstract classes in C#. C# allows you to create abstract classes that are used to provide a partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.
The following are some of the key points −
You cannot create an instance of an abstract class
You cannot create an instance of an abstract class
You cannot declare an abstract method outside an abstract class
You cannot declare an abstract method outside an abstract class
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
 Live Demo
using System;
namespace Demo {
   abstract class Shape {
      public abstract int area();
   }

   class Rectangle: Shape {
      private int length;
      private int width;

      public Rectangle( int a = 0, int b = 0) {
         length = a;
         width = b;
      }
      public override int area () {
         Console.WriteLine("Rectangle class area :");
         return (width * length);
      }
   }
   class RectangleTester {
      static void Main(string[] args) {
         Rectangle r = new Rectangle(20, 15);
         double a = r.area();
         Console.WriteLine("Area: {0}",a);
         Console.ReadKey();
      }
   }
}
Rectangle class area :
Area: 300