code-rag-bench/online-tutorials huggingface dataset:
Python - Email Messages

Email is a service which allows us to send the message in electronic mode over the internet. It offers an efficient, inexpensive and real time mean of distributing information among people.
Each user of email is assigned a unique name for his email account. This name is known as E-mail address. Different users can send and receive messages according to the e-mail address.
E-mail is generally of the form username@domainname.  For example, webmaster@tutorialspoint.com is an e-mail address where webmaster is username and tutorialspoint.com is domain name.
The username and the domain name are separated by @ (at) symbol. 
The username and the domain name are separated by @ (at) symbol. 
E-mail addresses are not case sensitive.
E-mail addresses are not case sensitive.
Spaces are not allowed in e-mail address.
Spaces are not allowed in e-mail address.
The first five lines of an E-mail message is called E-mail header. The header part comprises of following fields:
From
From
Date
Date
To
To
Subject
Subject
CC
CC
BCC
BCC
The From field indicates the sender’s address i.e. who sent the e-mail.
The Date field indicates the date when the e-mail was sent.
The To field indicates the recipient’s address i.e. to whom the e-mail is sent.
The Subject field indicates the purpose of e-mail. It should be precise and to the point.
CC stands for Carbon copy. It includes those recipient addresses whom we want to keep informed but not exactly the intended recipient.
BCC stands for Black Carbon Copy.  It is used when we do not want one or more of the recipients to know that someone else was copied on the message.
Greeting is the opening of the actual message. Eg. Hi Sir or Hi Guys etc.
It represents the actual content of the message.
This is the final part of an e-mail message. It includes Name of Sender, Address, and Contact Number.
Python has EmailMessage class which can be used build email messages.
This class ahs the required methods to customize different parts of the email message like - the TO and FROM tags, the Subject Line as well as the content of the email. 
In the below example we create an email message with all the necessary parts of an email. Once we print out the content of the message we can see the complete email.
import email.message, email.policy, email.utils, sys
text = """Welcome to TutorialsPoint - Simple Easy Learning"""

message = email.message.EmailMessage(email.policy.SMTP)
message['To'] = 'you@yourdomain.com'
message['From'] = 'Learn '
message['Subject'] = 'A mail To you'
message['Date'] = email.utils.formatdate(localtime=True)
message['Message-ID'] = email.utils.make_msgid()
message.set_content(text)
sys.stdout.buffer.write(message.as_bytes())
When we run the above program, we get the following output −

To: you@yourdomain.com
From: Learn 
Subject: A mail To you
Date: Wed, 13 Jun 2018 06:51:09 -0700
Message-ID: <152889786976.4106.5718297150260802709@ubuntu>
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0

Welcome to TutorialsPoint - Simple Easy Learning
GATE | GATE CS 2018 | Question 61

22 Nov, 2021
The instruction pipeline of a RISC processor has the following stages: Instruction Fetch (IF), Instruction Decode (ID), Operand Fetch (OF), Perform Operation (PO) and Writeback (WB), The IF, ID, OF and WB stages take 1 clock cycle each for every instruction. Consider a sequence of 100 instructions. In the PO stage, 40 instructions take 3 clock cycles each, 35 instructions take 2 clock cycles each, and the remaining 25 instructions take 1 clock cycle each. Assume that there are no data hazards and no control hazards.
The number of clock cycles required for completion of execution of the sequence of instruction is ______ .
Note – This was Numerical Type question.(A) 219(B) 104(C) 115(D) 220Answer: (A)Explanation:
Given, total number of instructions (n) = 100 Number of stages (k) = 5 Since, if n instructions take c cycle, so (c-1) stalls will occur for these instructions. 
Therefore, the number of clock cycles required = Total number of cycles required in general case + Extra cycles required (here, in PO stage),
= (n + k - 1) + Extra cycles 
= (100 + 5 -1) + 40*(3-1)+35*(2-1)+25*(1-1) 
= (100 + 4) + 40*2+35*1+25*0
= 104 + 115 
= 219 cycles 
So, option (A) is correct. 
Quiz of this Question
sag72434
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 1996 | Question 63
GATE | GATE CS 1996 | Question 38
DateTime.ToLocalTime() Method in C#

11 Feb, 2019
This method is used to convert the value of the current DateTime object to local time.
Syntax: public DateTime ToLocalTime ();
Return Value: This method returns an object whose Kind property is Local, and whose value is the local time equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented as a DateTime object.
Below programs illustrate the use of DateTime.ToLocalTime() Method
Example 1:
// C# program to demonstrate the// DateTime.ToLocalTime()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // creating object of DateTime        DateTime date = new DateTime(2011, 1,                                1, 4, 0, 15);          // Converts the value of the current         // DateTime object to local time.        // using ToLocalTime() method;        DateTime value = date.ToLocalTime();          // Display the TimeSpan        Console.WriteLine("local time is {0}", value);    }}
local time is 01/01/2011 04:00:15

Example 2:
// C# program to demonstrate the// DateTime.ToLocalTime()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // creating object of DateTime        DateTime date = DateTime.Now;          // Converts the value of the current        // DateTime object to local time.        // using ToLocalTime() method;        DateTime value = date.ToLocalTime();          // Display the TimeSpan        Console.WriteLine("local time is {0}", value);    }}
local time is 02/11/2019 05:13:37

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tolocaltime?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
C# | .NET Framework (Basic Architecture and Component Stack)
HashSet in C# with Examples
Lambda Expressions in C#
Switch Statement in C#
Partial Classes in C#
Hello World in C#
Difference between break and continue in PHP - GeeksforGeeks

10 Apr, 2022
The break and continue both are used to skip the iteration of a loop. These keywords are helpful in controlling the flow of the program. Difference between break and continue:
The break statement terminates the whole iteration of a loop whereas continue skips the current iteration.The break statement terminates the whole loop early whereas the continue brings the next iteration early.In a loop for switch, break acts as terminator for case only whereas continue 2 acts as terminator for case and skips the current iteration of loop.
The break statement terminates the whole iteration of a loop whereas continue skips the current iteration.
The break statement terminates the whole loop early whereas the continue brings the next iteration early.
In a loop for switch, break acts as terminator for case only whereas continue 2 acts as terminator for case and skips the current iteration of loop.
Program 1: This program illustrates the continue statement inside a loop. 
php
<?phpfor ($i = 1; $i < 10; $i++) {    if ($i % 2 == 0) {        continue;    }    echo $i . " ";}?>
Output:  Program 2: This program illustrates the break statement inside a loop. 
php
<?phpfor ($i = 1; $i < 10; $i++) {    if ($i == 5) {        break;    }    echo $i . " ";}?>
Output:  Program 3: Using switch inside a loop and continue 2 inside case of switch. 
php
<?phpfor ($i = 10; $i <= 15; $i++) {    switch ($i) {        case 10:            echo "Ten";            break;         case 11:            continue 2;         case 12:            echo "Twelve";            break;         case 13:            echo "Thirteen";            break;         case 14:            continue 2;         case 15:            echo "Fifteen";            break;    }     echo "<br> Below switch, and i = " . $i . ' <br><br> ';}?>
Output: 
Let us see the differences in a tabular form -:
Its syntax is -:
break;
Its syntax is -:
continue;
mayank007rawa
PHP-basics
Picked
Difference Between
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.
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
Difference between Compile-time and Run-time Polymorphism in Java
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to Install BeautifulSoup in Python on MacOS? - GeeksforGeeks

14 Sep, 2021
In this article, we will learn how to install Beautiful Soup in Python on MacOS.
Step 1: Install latest Python3 in MacOS
Step 2: Check if pip3 and python3 are correctly installed.
python3 --version
pip3 --version
Step 3: Upgrade your pip to avoid errors during installation.
pip3 install --upgrade pip
Step 4: Enter the following command to install Beautiful Soup using pip.
pip3 install beautifulsoup4
Step 1: Download the latest package of Beautiful Soup for python3.
curl https://files.pythonhosted.org/packages/a1/69/daeee6d8f22c997e522cdbeb59641c4d31ab120aba0f2c799500f7456b7e/beautifulsoup4-4.10.0.tar.gz > bs.tar.gz
Step 2: Extract the downloaded package using the following command.
tar -xzvf bs.tar.gz 
Step 3: Go inside the folder and Enter the following command to install the package.
cd beautifulsoup4-4.10.0
python3 setup.py install
Import the module in the Python terminal to check if Beautiful Soup is installed correctly
from bs4 import BeautifulSoup 
Note: If there is any error while importing the module then is not installed properly.
Blogathon-2021
how-to-install
Picked
Blogathon
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
Bash program to find A to the power B - GeeksforGeeks

02 Feb, 2018
Given two number A and B write a shell script to find the value of AB .
Examples:
Input : 
2 4
Output :
2 to the power 4 is 16

Input :
1 0
Output :
1 to the power 0 is 1

A to the power B (AB) means multiplying A, B times. Using a naive approach to solve this problem.For Example:-A = 2 and B = 3A3 = 8 which comes by multiplying 2 3 times i.e. 2*2*2 = 8 .
# Bash Program to find# A to the power B  # Subroutine to find A# to the power Bpow(){  # value of A  a=$1    # value of B  b=$2    # c to count counter  c=1    # res to store the result  res=1    #  if((b==0));  then    res=1  fi    if((a==0));  then    res=0  fi    if((a >= 1 && b >= 1));  then    while((c <= b))    do      res=$((res * a))      c=$((c + 1))    done  fi    # Display the result  echo "$1 to the power $2 is $res"}  # Driver Code  # inputA=2B=4  # calling the pow functionpow $A $B
Output:
16

Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
C++ program to implement Half Subtractor - GeeksforGeeks

14 Sep, 2021
Prerequisite :  Half SubtractorWe are given with two inputs A and B. Our task is to implement Half Subtractor circuit and print the outputs difference and borrow of two inputs.
Introduction :  The half subtractor is used to subtract two 1-bit numbers  which are minuend, and subtrahend . The half subtractor has two input states and two output states. The two outputs are difference and borrow. The Difference is the difference between the inputs it is set when both the inputs are different  and borrow is set when subtrahend  is greater than minuend we borrow “1” and set borrow “1”.  The block diagram of half subtractor is 
Here we have two inputs A, B and two outputs Difference, Borrow. The values of Difference and borrow will depend on A and B . The truth table for Half Subtractor is
The Difference is calculated by XOR operation of A and B and the borrow is calculated by And operation of Ā and B. Here Ā is NOT operation of A which gives inverse output.
Logical Expression :
Difference = A XOR B
Borrow =     Ā AND B
Examples –
Input :          A=1, B= 0
Output:       Difference=1, Borrow=0
Explanation : Here from logical expression Difference = A XOR B 
              i.e  1 XOR 0 = 1, and Ā = NOT(A) i,e NOT(1) = 0.
              So, Borrow=Ā AND B  
              i.e 0 AND 0 = 0.
Input :       A=0, B= 1
Output:       Difference=1, Borrow=1
Explanation:  Here from  logical expression Difference=A XOR B 
              i.e. 0 XOR 1 =1 and Ā = NOT(A) i,e NOT(0) = 1.
              So, Borrow=Ā AND B 
              i.e 1 AND 1 =  1.
Approach :
Initialize the variables Difference and Borrow for storing outputs.
First we will take two inputs A ,B.
By applying  A XOR B  we get the value of Difference.
By applying  NOT A   we get the value of  Ā .
By applying Ā AND B  we get the value of Borrow.
C++
// C++ program to implement Half subtractor #include <bits/stdc++.h>using namespace std;  // Function to print Difference and Borrowvoid Half_Subtractor(int A,int B){    // initializing Difference and Borrow    int Difference,Borrow;    // Calculating value of Difference    Difference = A ^ B;      // Calculating value of Borrow    // Calculating not of A    A = not(A);    Borrow = A & B;      // printing the values    cout<<"Difference = "<<Difference<<endl;    cout<<"Borrow = "<<Borrow<<endl;}int main() {    int A = 1;    int B = 0;    // passing three inputs of half subtractor as arguments to Half_Subtractor function    Half_Subtractor(A,B);    return 0;}
Output :
Difference = 1
Borrow = 0 
sweetyty
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shift Micro-Operations in Computer Architecture
Analog to Digital Conversion
Transmission Impairment in Data Communication
Ring Counter in Digital Logic
Latches in Digital Logic
Introduction to memory and memory units
Half Subtractor in Digital Logic
Restoring Division Algorithm For Unsigned Integer
Synchronous 3 bit Up/Down counter
Introduction of Sequential Circuits
C program to store Student records as Structures and Sort them by Name

In this problem, we are given a student’s record which contains student_id, student_name, student_percentage. Our task is to create a C program to store student records as structure and sort them by name.
Let’s take an example to understand the problem,
Input − student record =
{{ student_id = 1, student_name = nupur, student_percentage = 98},
{ student_id = 2, student_name = Akash, student_percentage = 75},
{ student_id = 3, student_name = Yash, student_percentage = 62},
{ student_id = 4, student_name = Jyoti, student_percentage = 87},
{ student_id = 5, student_name = Ramlal, student_percentage = 80}}
Output − student record =
{{ student_id = 2, student_name = Akash, student_percentage = 75},
{ student_id = 4, student_name = Jyoti, student_percentage = 87},
{ student_id = 1, student_name = nupur, student_percentage = 98},
{ student_id = 5, student_name = Ramlal, student_percentage = 80},
{ student_id = 3, student_name = Yash, student_percentage = 62}}
To solve this problem, we will first create a structure that will store the details of the student. Now, we will use qsort() and in that qsort, we will define a comparator function for this qsort that will compare the names of the structure using strcmp() method.
The program to store Student records as Structures and Sort them by Name
 Live Demo
//C program to store Student records as Structures and Sort them by Name
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
   int student_id;
   char* student_name;
   int student_percentage;
};
int comparator(const void* s1, const void* s2){
   return strcmp(((struct Student*)s1)->student_name,((struct Student*)s2)->student_name);
}
int main() {
   int n = 5;
   struct Student arr[n];
   //student 1
   arr[0].student_id = 1;
   arr[0].student_name = "Nupur";
   arr[0].student_percentage = 98;
   //student 2
   arr[1].student_id = 2;
   arr[1].student_name = "Akash";
   arr[1].student_percentage = 75;
   //student 3
   arr[2].student_id = 3;
   arr[2].student_name = "Yash";
   arr[2].student_percentage = 62;
   //student 4
   arr[3].student_id = 4;
   arr[3].student_name = "Jyoti";
   arr[3].student_percentage = 87;
   //student 5
   arr[4].student_id = 5;
   arr[4].student_name = "Ramlal";
   arr[4].student_percentage = 80;
   printf("Unsorted Student Record:\n");
   for (int i = 0; i < n; i++) {
      printf("Id = %d, Name = %s, Age = %d \n", arr[i].student_id, arr[i].student_name, arr[i].student_percentage);
   }
   qsort(arr, n, sizeof(struct Student), comparator);
   printf("\n\nStudent Records sorted by Name:\n");
   for (int i = 0; i < n; i++) {
      printf("Id = %d, Name = %s, Age = %d \n", arr[i].student_id, arr[i].student_name, arr[i].student_percentage);
   }
   return 0;
}
Unsorted Student Record:
Id = 1, Name = Nupur, Age = 98
Id = 2, Name = Akash, Age = 75
Id = 3, Name = Yash, Age = 62
Id = 4, Name = Jyoti, Age = 87
Id = 5, Name = Ramlal, Age = 80
Student Records sorted by Name:
Id = 2, Name = Akash, Age = 75
Id = 4, Name = Jyoti, Age = 87
Id = 1, Name = Nupur, Age = 98
Id = 5, Name = Ramlal, Age = 80
Id = 3, Name = Yash, Age = 62
Difference between the directory, menu lists and the unordered list - GeeksforGeeks

24 Aug, 2021
While creating an unordered list, we can make use of two different types of tags. These are used to generate directory lists and menu lists.
Directory Lists: The directory list is created using the HTML <dir> tag. This tag is used as a container for lists of files/folders of a directory. With the introduction of HTML 5, the <dir> tag has become deprecated and is no longer supported.
Syntax:
<dir> lists.... </dir>
Example: This example illustrates the <dir> tag in HTML.
HTML
<!DOCTYPE html><html>  <body>    <h1>GeeksforGeeks</h1>    <h2>Dir Tag</h2>    <p>List of all computer science subjects:</p>      <!-- dir tag starts here-->    <dir>        <li>Admin</li>        <li>User</li>        <li>Writer</li>        <li>Database Manager</li>        <li>Founder</li>    </dir>    <!-- dir tag ends here-->      </body>  </html>
Output:
Menu Lists: Menu lists work in the same manner as the directory lists. The <menu> tag is used to create a menu list. It serves as the container for menu items and displays them in the form of a list. Refer to the link to know the difference between <nav> and <menu> for better understanding.
Syntax:
<menu> lists... </menu>
Example:  This example illustrates the <menu> tag in HTML
HTML
<!DOCTYPE html><html>  <body>    <h1>GeeksforGeeks</h1>    <h2>Menu Tag</h2>    <p>List of all folders in the directory</p>      <!-- menu tag starts here-->    <menu>        <li>Admin</li>        <li>User</li>        <li>Writer</li>        <li>Database Manager</li>        <li>Founder</li>    </menu>    <!-- menu tag ends here--></body>  </html>
Output:
Unordered Lists: Unordered Lists are also used to create a list of items. As the name suggests there is no particular order of the items i.e. they are unordered.
Syntax:
<ul> lists.... </ul>
Example:
HTML
<!DOCTYPE html><html>  <body>    <h1>GeeksforGeeks</h1>    <h2>Menu Tag</h2>    <p>unordered list for professions</p>      <ul>        <li>Teacher</li>        <li>Admin</li>        <li>User</li>        <li>Writer</li>        <li>Manager</li>        <li>Founder</li>        <li>Salesperson</li>    </ul></body>  </html>
Difference between Directory List, Menu List, and Unordered List:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
HTML-Tags
Picked
Difference Between
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference Between Method Overloading and Method Overriding in Java
Comparison between Adjacency List and Adjacency Matrix representation of Graph
Difference between Synchronous and Asynchronous Transmission
Difference between LAN, MAN and WAN
Difference between Prim's and Kruskal's algorithm for MST
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Form validation using HTML and JavaScript
Python dictionary values() Method

Python dictionary method values() returns a list of all the values available in a given dictionary.
Following is the syntax for values() method −
dict.values()

NA
NA
This method returns a list of all the values available in a given dictionary.
The following example shows the usage of values() method.
#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  dict.values()
When we run above program, it produces following result −
Value : [7, 'Zara']


    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
Java String lastIndexOf() Method

❮ String Methods

Search a string for the last occurrence of "planet":
String myStr = "Hello planet earth, you are a great planet.";
System.out.println(myStr.lastIndexOf("planet"));

Try it Yourself »

The lastIndexOf() method returns the position of the last occurrence of specified character(s) in a string.
Tip: Use the indexOf method to return the position of the 
first occurrence of specified character(s) in a string.
There are 4 lastIndexOf() methods:
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
public int lastIndexOf(int char)
public int lastIndexOf(int char, int fromIndex)

Find the last occurrence of "e" in a string, starting the search at position 
  5:
public class Main {
  public static void main(String[] args) {
    String myStr = "Hello planet earth, you are a great planet.";
    System.out.println(myStr.lastIndexOf("e", 5));
  }
}


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Implement sigmoid function using Numpy - GeeksforGeeks

03 Oct, 2019
With the help of Sigmoid activation function, we are able to reduce the loss during the time of training because it eliminates the gradient problem in machine learning model while training.
# Import matplotlib, numpy and mathimport matplotlib.pyplot as pltimport numpy as npimport math  x = np.linspace(-10, 10, 100)z = 1/(1 + np.exp(-x))  plt.plot(x, z)plt.xlabel("x")plt.ylabel("Sigmoid(X)")  plt.show()
Output :
Example #1 :
# Import matplotlib, numpy and mathimport matplotlib.pyplot as pltimport numpy as npimport math  x = np.linspace(-100, 100, 200)z = 1/(1 + np.exp(-x))  plt.plot(x, z)plt.xlabel("x")plt.ylabel("Sigmoid(X)")  plt.show()
Output :
Python-numpy
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
MySQL Tryit Editor v1.0

SELECT COALESCE(NULL, NULL, NULL, 'W3Schools.com', NULL, 'Example.com');
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to get the last element of a list in Python?

Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end.  As we want last element in list, use -1 as index.
>>> L1=[1,2,3,4,5]
>>> print (L1[-1])
5
Batch Script - Creating Folders

The creation of a folder is done with the assistance of the MD (Make directory) command.
MKDIR [drive:]path 
MD [drive:]path

Let’s look at some examples on how to use the MD command.
md test

The above command will create a directory called test in your current directory.
md C:\test

The above command will create a directory called test in the C drive.
md “Test A”

If there are spaces in the folder name, then the folder name should be given in quotes.
mkdir \a\b\c

The above command creates directories recursively and is the same as issuing the following set of commands.
mkdir \a 
chdir \a 
mkdir b 
chdir b 
mkdir c

 Print
 Add Notes
 Bookmark this page
Default array values in Java

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples:
Boolean - false
int - 0
double - 0.0
Object - null
 Live Demo
public class Tester {
   public static void main(String[] args) {
      System.out.print("Default values (String array):");
      String strings[] = new String[5];
      for (String s : strings) {
         System.out.print(s + " ");
      }
      System.out.println();
      System.out.print("Default values (int array):");
      int numbers[] = new int[5];
      for (int val : numbers) {
         System.out.print(val + " ");
      }
      System.out.println();
      System.out.print("Default values (double array):");
      double doubles[] = new double[5];
      for (double val : doubles) {
         System.out.print(val + " ");
      }
      System.out.println();
      System.out.print("Default values (boolean array):");
      boolean booleans[] = new boolean[5];
      for (boolean val : booleans) {
         System.out.print(val + " ");
      }
      System.out.println();
      System.out.print("Default values (Object array):");
      Tester testers[] = new Tester[5];
      for (Tester val : testers) {
         System.out.print(val + " ");
      }
   }
}
Default values (String array):null null null null null
Default values (int array):0 0 0 0 0
Default values (double array):0.0 0.0 0.0 0.0 0.0
Default values (boolean array):false false false false false
Default values (Object array):null null null null null
How to print the Python Exception/Error Hierarchy?

We import the inspect module and specifically use the getclasstree() function to print the python Exception/Error hierarchy.
This code arranges and prints the given list of exception classes into a hierarchy of nested lists. We recursively go through __subclasses__() down by an inheritance tree as shown in the output.
import inspect
print "The class hierarchy for built-in exceptions is:"
inspect.getclasstree(inspect.getmro(BaseException))
def classtree(cls, indent=0):
print '.' * indent, cls.__name__
for subcls in cls.__subclasses__():
classtree(subcls, indent + 3)
classtree(BaseException)
On running the code we get the following output.
The class hierarchy for built-in exceptions is:
BaseException
... Exception
...... StandardError
......... TypeError
......... ImportError
............ ZipImportError
......... EnvironmentError
............ IOError
............ OSError
............... WindowsError
......... EOFError
......... RuntimeError
............ NotImplementedError
......... NameError
............ UnboundLocalError
......... AttributeError
......... SyntaxError
............ IndentationError
............... TabError
......... LookupError
............ IndexError
............ KeyError
............ CodecRegistryError
......... ValueError
............ UnicodeError
............... UnicodeEncodeError
............... UnicodeDecodeError
............... UnicodeTranslateError
......... AssertionError
......... ArithmeticError
............ FloatingPointError
............ OverflowError
............ ZeroDivisionError
......... SystemError
............ CodecRegistryError
......... ReferenceError
......... MemoryError
......... BufferError
...... StopIteration
...... Warning
......... UserWarning
......... DeprecationWarning
......... PendingDeprecationWarning
......... SyntaxWarning
......... RuntimeWarning
......... FutureWarning
......... ImportWarning
......... UnicodeWarning
......... BytesWarning
...... _OptionError
...... error
...... Error
...... TokenError
...... StopTokenizing
...... error
...... EndOfBlock
... GeneratorExit
... SystemExit
... KeyboardInterrupt
Copy a few columns from a table to another in MySQL

Let us first create a table −
mysql> create table DemoTable1
   -> (
   -> Id int,
  -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values(10,'John');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable1 values(11,'Chris');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable1 values(12,'Robert');
Query OK, 1 row affected (0.32 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+--------+
| Id   | Name   |
+------+--------+
|   10 | John   |
|   11 | Chris  |
|   12 | Robert |
+------+--------+
3 rows in set (0.00 sec)
Following is the query to copy few columns from a DemoTable1 to another table DemoTable2 −
mysql> create table DemoTable2 (
-> select Name from DemoTable1 where Id=11
-> );
Query OK, 1 row affected (0.70 sec)
Records: 1 Duplicates: 0 Warnings: 0
Now check the table records of table ‘DemoTable2’ −
mysql> select *from DemoTable2;
This will produce the following output −
+-------+
| Name  |
+-------+
| Chris |
+-------+
1 row in set (0.00 sec)
F# - Sets

A set in F# is a data structure that acts as a collection of items without preserving the order in which items are inserted. Sets do not allow duplicate entries to be inserted into the collection.
Sets can be created in the following ways −
By creating an empty set using Set.empty and adding items using the add function.
Converting sequences and lists to sets.
The following program demonstrates the techniques −
(* creating sets *)
let set1 = Set.empty.Add(3).Add(5).Add(7). Add(9)
printfn"The new set: %A" set1

let weekdays = Set.ofList ["mon"; "tues"; "wed"; "thurs"; "fri"]
printfn "The list set: %A" weekdays

let set2 = Set.ofSeq [ 1 .. 2.. 10 ]
printfn "The sequence set: %A" set2
When you compile and execute the program, it yields the following output −
The new set: set [3; 5; 7; 9]
The list set: set ["fri"; "mon"; "thurs"; "tues"; "wed"]
The sequence set: set [1; 3; 5; 7; 9]

The following table shows the basic operations on sets −
The following example demonstrates the uses of some of the above functionalities −
let a = Set.ofSeq [ 1 ..2.. 20 ]
let b = Set.ofSeq [ 1 ..3 .. 20 ]
let c = Set.intersect a b
let d = Set.union a b
let e = Set.difference a b

printfn "Set a: "
Set.iter (fun x -> printf "%O " x) a
printfn""

printfn "Set b: "
Set.iter (fun x -> printf "%O " x) b
printfn""

printfn "Set c = set intersect of a and b : "
Set.iter (fun x -> printf "%O " x) c
printfn""

printfn "Set d = set union of a and b : "
Set.iter (fun x -> printf "%O " x) d
printfn""

printfn "Set e = set difference of a and b : "
Set.iter (fun x -> printf "%O " x) e
printfn""
When you compile and execute the program, it yields the following output −
Set a:
1 3 5 7 9 11 13 15 17 19
Set b:
1 4 7 10 13 16 19
Set c = set intersect of a and b :
1 7 13 19
Set d = set union of a and b :
1 3 4 5 7 9 10 11 13 15 16 17 19
Set e = set difference of a and b :
3 5 9 11 15 17

 Print
 Add Notes
 Bookmark this page
How to sum current month records in MySQL?

To sum current month records, use the SUM() and MONTH() function. Let us first create a table −
mysql> create table DemoTable1889
   (
   DueDate date,
   Amount int
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1889 values('2019-12-11',500);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1889 values('2019-11-11',1000);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1889 values('2018-12-04',700);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1889 values('2017-12-10',300);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1889;
This will produce the following output −
+------------+--------+
| DueDate    | Amount |
+------------+--------+
| 2019-12-11 |    500 |
| 2019-11-11 |   1000 |
| 2018-12-04 |    700 |
| 2017-12-10 |    300 |
+------------+--------+
4 rows in set (0.00 sec)
The current date is as follows −
mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2019-12-10 |
+------------+
1 row in set (0.00 sec)
Here is the query to sum current month records in MySQL −
mysql> select sum(Amount) from DemoTable1889 where MONTH(DueDate)=MONTH(curdate());
This will produce the following output −
+-------------+
| sum(Amount) |
+-------------+
|        1500 |
+-------------+
1 row in set (0.00 sec)
C Program to print all ASCII values.

Print the American Standard Code for Information Interchange (ASCII) values of 0 to 255 characters without initializing the character to integer type variable. Simply, use the format specifier.
Here we are writing a program to print only from 65 to 122.
If you want to see all ASCII values, in for loop you can write as follows −
For(i=0;i<255;i++)
Then, it prints all the ASCII values from 0 to 255.
The logic used to print the ASCII values from 65 to 122 is as follows −
Prints ASII values From A to z
for (i = 65; i < =122; i++){
   printf("%c \t\t %d\n", i, i);
}
Following is the C program to print the ASCII values from 65 to 122 −
 Live Demo
#include <stdio.h>
int main() {
   // Declare Variables
   int i = 0;
   printf("Character \t ASCII Value\n\n");
   //Print ASCII Values
   for (i = 65; i <=122; i++) {
      printf("%c \t\t %d\n", i, i);
   }
   return 0;
}
When the above program is executed, it produces the following output −
Character ASCII Value

A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
K 75
L 76
M 77
N 78
O 79
P 80
Q 81
R 82
S 83
T 84
U 85
V 86
W 87
X 88
Y 89
Z 90
[ 91
\ 92
] 93
^ 94
_ 95
` 96
a 97
b 98
c 99
d 100
e 101
f 102
g 103
h 104
i 105
j 106
k 107
l 108
m 109
n 110
o 111
p 112
q 113
r 114
s 115
t 116
u 117
v 118
w 119
x 120
y 121
z 122
Java Program to parse date and time

Create a SimpleDateFormat object −
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Do not forget to import the following package for SimpleDateFormat class −
import java.text.SimpleDateFormat;
Now, since we have set the format for date above, let us parse the date using parseObject() method −
Date dt = (Date) dateFormat.parseObject("2018.11.22.11.50.15");
The following is an example −
 Live Demo
import java.util.Date;
import java.text.SimpleDateFormat;
public class Demo {
   public static void main(String[] argv) throws Exception {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
      // parse
      System.out.println("Parse Date and Time...");
       Date dt = (Date) dateFormat.parseObject("2018.11.22.11.50.15");
      System.out.println(dt);
   }
}
Parse Date and Time...
Thu Nov 22 11:50:15 UTC 2018
Tryit Editor v3.7

Tryit: HTML comments
Explain putc() and getc() functions of files in C language

File is collection of records or is a place on hard disk, where data is stored permanently.
The operations on files in C programming language are as follows −
Naming the file
Opening the file
Reading from the file
Writing into the file
Closing the file
The syntax for opening a file is as follows −
FILE *File pointer;
For example, FILE * fptr;
The syntax for naming a file is as follows −
File pointer = fopen ("File name", "mode");
For example,
fptr = fopen ("sample.txt", "r");
FILE *fp;
fp = fopen ("sample.txt", "w");
putc( ) function is used for writing a character into a file.
The syntax for putc() function is as follows −
putc (char ch, FILE *fp);
For example,
FILE *fp;
char ch;
putc(ch, fp);
getc( ) function is used to read a character from file.
The syntax for getc() function is as follows −
char getc (FILE *fp);
For example,
FILE *fp;
char ch;
ch = getc(fp);
Following is the C program for using putc() and getc() functions −
 Live Demo
#include<stdio.h>
int main(){
   char ch;
   FILE *fp;
   fp=fopen("std1.txt","w"); //opening file in write mode
   printf("enter the text.press cntrl Z:\n");
   while((ch = getchar())!=EOF){
      putc(ch,fp); // writing each character into the file
   }
   fclose(fp);
   fp=fopen("std1.txt","r");
   printf("text on the file:\n");
   while ((ch=getc(fp))!=EOF){ // reading each character from file
      putchar(ch); // displaying each character on to the screen
   }
   fclose(fp);
   return 0;
}
When the above program is executed, it produces the following result −
enter the text.press cntrl Z:
Hi Welcome to TutorialsPoint
Here I am Presenting Question and answers in C Programming Language
^Z
text on the file:
Hi Welcome to TutorialsPoint
Here I am Presenting Question and answers in C Programming Language
DATE_FORMAT() Function in MySQL - GeeksforGeeks

03 Dec, 2020
DATE_FORMAT() function in MySQL is used to format a specified date as given format value i.e., a date will be given and this function will format that date as specified format parameters.
Syntax :
DATE_FORMAT(date, format)

Parameter : This function accepts two parameters as given below :
date – Specified date to be formatted.
format – Specified format. This list of formats used in this function are listed below:
Returns :It returns the formatted date.
Example-1 :Getting a formatted year as “2020” from the specified date “2020-11-23”.
SELECT DATE_FORMAT("2020-11-23", "%Y");

Output :
2020
Example-2 :Getting a formatted month name as “November” from the specified date “2020-11-23”.
SELECT DATE_FORMAT("2020-11-23", "%M");

Output :
November
Example-3 :Getting a day of the month as a numeric value as “23rd” from the specified date “2020-11-23”.
SELECT DATE_FORMAT("2020-11-23", "%D");

Output :
23rd
Example-4 :Getting month day and year as “November 23 2020” from the specified date “2020-11-23”.
SELECT DATE_FORMAT("2020-11-23", "%M %d %Y");

Output :
November 23 2020
Example-5 :Getting hour and minute as “12 09” from the specified date and time “2020-11-23 12:09:23”.
SELECT DATE_FORMAT("2020-11-23 12:09:23", "%H %i");

Output :
12 09
Application : This function is used to format a specified date as given format value.
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Composite Key in SQL
SQL using Python
SQL | DROP, TRUNCATE
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
How to add a sub-document to sub-document array in MongoDB?

Use the $push operator to add a sub-document. Let us first create a collection with documents −
> db.subDocumentToSubDocumentDemo.insertOne(
   {
      "_id" :101,
      "StudentName" : "Larry",
      "StudentAge" : 21,
      "StudentDetails" : [
         {
            "StudentCountryName" : "US",
            "StudentFavouriteSubjectList" : [ ]
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.subDocumentToSubDocumentDemo.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentDetails" : [
      {
         "StudentCountryName" : "US",
         "StudentFavouriteSubjectList" : [ ]
      }
   ]
}
Following is the query to add a sub-document to sub-document array in MongoDB −
> db.subDocumentToSubDocumentDemo.update(
   { "_id": 101 },
   {
      "$push": {
         "StudentDetails": {
            "StudentCountryName" : "UK",
            "StudentFavouriteSubjectList" : ["MongoDB","Java" ]
         }
      }
   }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check all the documents once again −
> db.subDocumentToSubDocumentDemo.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentAge" : 21,
   "StudentDetails" : [
      {
         "StudentCountryName" : "US",
         "StudentFavouriteSubjectList" : [ ]
      },
      {
         "StudentCountryName" : "UK",
         "StudentFavouriteSubjectList" : [
            "MongoDB",
            "Java"
         ]
      }
   ]
}
Python PRAW - Getting the subreddit on which a comment is posted in Reddit - GeeksforGeeks

26 Jun, 2020
In Reddit, we can post a comment to any submission, we can also comment on a comment to create a thread of comments. Here we will see how to fetch the subreddit in which the comment has been posted using PRAW. We will be using the subreddit attribute of the Comment class to fetch subreddit class of the subreddit in which the comment has been posted.
Example 1 : Consider the following comment :
The ID of the comment is : fvib7aw
# importing the moduleimport praw  # initialize with appropriate valuesclient_id = ""client_secret = ""username = ""password = ""user_agent = ""  # creating an authorized reddit instancereddit = praw.Reddit(client_id = client_id,                      client_secret = client_secret,                      username = username,                      password = password,                     user_agent = user_agent)   # the ID of the commentcomment_id = "fvib7aw"  # instantiating the Comment classcomment = reddit.comment(comment_id)  # fetching the subreddit attributesubreddit = comment.subreddit    print("The name of the subreddit is : " + subreddit.display_name)
Output :
The name of the subreddit is : aww

Example 2 : Consider the following comment:
The ID of the comment is : fv9qvgo
# importing the moduleimport praw  # initialize with appropriate valuesclient_id = ""client_secret = ""username = ""password = ""user_agent = ""  # creating an authorized reddit instancereddit = praw.Reddit(client_id = client_id,                      client_secret = client_secret,                      username = username,                      password = password,                     user_agent = user_agent)   # the ID of the commentcomment_id = "fv9qvgo"  # instantiating the Comment classcomment = reddit.comment(comment_id)  # fetching the subreddit attributesubreddit = comment.subreddit    print("The name of the subreddit is : " + subreddit.display_name)
Output :
The name of the subreddit is : redditdev

Python-PRAW
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?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
Repeating letter string - JavaScript

We are required to write a JavaScript function that takes in a string and a number, say n, and the function should return a new string in which all the letters of the original string are repeated n times.
For example: If the string is −
const str = 'how are you'
And the number n is 2
Then the output should be −
const output = 'hhooww  aarree  yyoouu'
Following is the code −
const str = 'how are you';
const repeatNTimes = (str, n) => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      // using the String.prototype.repeat() function
      res += str[i].repeat(n);
   };
   return res;
};
console.log(repeatNTimes(str, 2));
Following is the output in the console −
hhooww  aarree  yyoouu
Posix Character Class \p{XDigit} Match

The character class \p{XDigit} matches any hexadecimal character.
The following example shows the usage of Posix character class matching.
package com.tutorialspoint;

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

public class PosixCharacterClassDemo {
   private static final String REGEX = "\\p{XDigit}";
   private static final String INPUT = "Bb12\tc!";

   public static void main(String[] args) {
      // create a pattern
      Pattern  pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 

      while(matcher.find()) {
         //Prints the start index of the match.
         System.out.println("Match String start(): "+matcher.start());
      }
   }
}
Let us compile and run the above program, this will produce the following result −
Match String start(): 0
Match String start(): 1
Match String start(): 2
Match String start(): 3
Match String start(): 5

 Print
 Add Notes
 Bookmark this page