code-rag-bench/online-tutorials huggingface dataset:
What are the differences between json and simplejson Python modules?

json is simplejson, added to the stdlib. But since json was added in 2.6, simplejson has the advantage of working on more Python versions (2.4+).
simplejson is also updated more frequently than Python. Although they are the same, the version included in the stdlib doesn't include the latest optimizations. So if you need (or want) the latest version, it's best to use simplejson itself, if possible.
A good practice, is to use one or the other as a fallback. For example,
try: import simplejson as json
except ImportError: import json
Download Video in MP3 format using PyTube - GeeksforGeeks

25 Feb, 2021
YouTube is the world’s most common video sharing site, and you can experience a situation as a hacker where you want to script something to download videos. For this, We present Pytube to you.
Pytube is a lightweight, Python-written library. It does not have third-party dependencies and strives to be extremely secure.
Pytube also simplifies pipelining, allowing you to define callback functionality for various download events, such as progress or completion.
Finally, pytube also provides a command-line feature that allows you to stream videos directly from the terminal easily.
To do our task, we will some libraries especially the pytube from python. For this, we have to import it. To import pytube, we can use the commands according to the python version.
For Python2 : pip install pytube
For Python3 : pip3 install pytube
For pyube3 : pip install pytube3
To save the audio file, we are using the os module and import by using the command given below :
pip install os_sys
Procedure:
First, we need to import the required (pytube and os) module.
Then we take input from the user i.e; the link of the YouTube video.
As, we need only an audio file from that video, so we use the filter method.
Now we need to set the output path of the audio file, which we will do by using the os module.
Now finally we can change the audio extension to MP3 and play our audio.
Implementation:
Python3
# importing packagesfrom pytube import YouTubeimport os  # url input from useryt = YouTube(    str(input("Enter the URL of the video you want to download: \n>> ")))  # extract only audiovideo = yt.streams.filter(only_audio=True).first()  # check for destination to save fileprint("Enter the destination (leave blank for current directory)")destination = str(input(">> ")) or '.'  # download the fileout_file = video.download(output_path=destination)  # save the filebase, ext = os.path.splitext(out_file)new_file = base + '.mp3'os.rename(out_file, new_file)  # result of successprint(yt.title + " has been successfully downloaded.")
Output:
Picked
python-utility
Technical Scripter 2020
Python
Technical Scripter
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()
BeautifulSoup object - Python Beautifulsoup - GeeksforGeeks

25 Oct, 2020
BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object.
Syntax:  BeautifulSoup(document, parser)
Parameters: This function accepts two parameters as explained below: 
document: This parameter contains the XML or HTML document.
parser: This parameter contains the name of the parser to be used to parse the document.
Below given examples explain the concept of BeautifulSoup object in Beautiful Soup. Example 1: In this example, we are going to create a document with a BeautifulSoup object and print a tag.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Initialize the object with a HTML pagesoup = BeautifulSoup('''    <html>        <h2> Heading 1 </h2>        <h1> Heading 2 </h1>    </html>    ''', "lxml")  # Get the whole h2 tagtag = soup.h2  # Print the tagprint(tag)
Output: 
<h2> Heading 1 </h2>

Example 2: In this example, we are going to create a document with a BeautifulSoup object and then extract the attributes using attrs approach.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Initialize the object with a HTML pagesoup = BeautifulSoup('''              <h2 class="hello"> Heading 1 </h2>        <h1> Heading 2 </h1>          ''', "lxml")  # Get the whole h2 tagtag = soup.h2  # Get the attributeattribute = tag.attrs  # Print the outputprint(attribute)
Output: 
{'class': ['hello']}

Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to verify a JSON response body using Assertions in Rest Assured?

We can verify the JSON response body using Assertions in Rest Assured. This is done with the help of the Hamcrest Assertion. It uses the Matcher class for Assertion.
To work with Hamcrest we have to add the Hamcrest Core dependency in the pom.xml in our Maven project. The link to this dependency is available in the below link −
https://mvnrepository.com/artifact/org.hamcrest/hamcrest-core
We shall send a GET request via Postman on a mock API, observe the Response.
Using Rest Assured, we shall verify the value of the Location in the Response body.
Code Implementation
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
public class NewTest {
   @Test
   public void ressponseAssertion() {

      //base URL
      RestAssured.baseURI = "https://run.mocky.io";

      //GET operation
      given() .when().get("/v3/6c6ed634-5e78-4b80-94c7-cf17c04c7055").
      then().log().all()

      //verify status code as 200
      .assertThat().statusCode(200)

      //verify body
      .body("Location", Matchers.equalTo("Makinac Island"))

      //verify header
      .header("Content-Length" , "57");
   }
}
initial – Django Form Field Validation

13 Feb, 2020
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments.
initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty. Let’s check how to use initial in a field using a project.
Syntax
field_name = models.Field(option = value)
Illustration of initial using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options.
from django import forms  class GeeksForm(forms.Form):    geeks_field = forms.CharField(initial = "Enter your Name")
Add the geeks app to INSTALLED_APPS
# Application definition  INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'geeks',]
Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm  # Create your views here.def home_view(request):    context = {}    form = GeeksForm(request.POST or None)    context['form'] = form    if request.POST:        if form.is_valid():            temp = form.cleaned_data.get("geeks_field")            print(temp)    return render(request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "POST">    {% csrf_token %}    {{ form }}    <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path  # importing views from views..pyfrom .views import home_view  URLpatterns = [    path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field CharField is created with initial “Enter your Name”.
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Java Program to Find LCM of Two Numbers

28 Mar, 2021
LCM (i.e. Least Common Multiple) is the largest of the two stated numbers that can be divided by both the given numbers.
Example:
LCM of 15 and 25 is 75, and LCM of 3 and 7 is 21.
Therefore, firstly find all the prime factors of both the stated numbers, then find the union of all those factors that are present in both the given numbers. And at last, return the product of elements which are in union.
Below given formula for finding the LCM of two numbers ‘u’ and ‘v’ gives an efficient solution.
u x v = LCM(u, v) * GCD (u, v)
LCM(u, v) = (u x v) / GCD(u, v)
Note: GCD is the greatest common divisor.
Java
// Java program to find LCM of two numbers.class gfg {    // Gcd of u and v using recursive method    static int GCD(int u, int v)    {        if (u == 0)            return v;        return GCD(v % u, u);    }      // LCM of two numbers    static int LCM(int u, int v)    {        return (u / GCD(u, v)) * v;    }      // The Driver method    public static void main(String[] args)    {        int u = 25, v = 15;        System.out.println("LCM of " + u + " and " + v                           + " is " + LCM(u, v));    }}
LCM of 25 and 15 is 75
Similarly, you can find the LCM of any two given numbers.
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Express.js req.hostname Property

25 Jan, 2022
The req.hostname property contains the hostname which is derived from the Host HTTP header. It basically returns the hostname which is being supplied in the host HTTP header.Syntax:  
req.hostname
Parameter: No parameterReturn Value: StringInstallation of express module:  
You can visit the link to Install express module. You can install this package by using this command.  
You can visit the link to Install express module. You can install this package by using this command.  
npm install express
After installing the express module, you can check your express version in command prompt using the command.  
After installing the express module, you can check your express version in command prompt using the command.  
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.  
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.  
node index.js
Example 1: Filename: index.js  
javascript
var express = require('express');var app = express();var PORT = 3000; app.get('/', function (req, res) {  console.log(req.hostname);  res.send();}); app.listen(PORT, function(err){    if (err) console.log(err);    console.log("Server listening on PORT", PORT);});
Steps to run the program:  
The project structure will look like this:  
The project structure will look like this:  
Make sure you have installed express module using the following command:  
Make sure you have installed express module using the following command:  
npm install express
Run index.js file using below command:  
Run index.js file using below command:  
node index.js
Output:  
Output:  
Server listening on PORT 3000
 Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:  
 
Now open your browser and go to http://localhost:3000/, now you can see the following output on your console:  
Server listening on PORT 3000
localhost
 
 
Example 2: Suppose we have a domain name instead of localhost as shown below:  
Host: "demo.com:3000"
console.log(req.hostname);
Output:  
demo.com
Reference: https://expressjs.com/en/4x/api.html#req.hostname 
adnanirshad158
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
JWT Authentication with Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
How to use an ES6 import in Node.js?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set space between the flexbox ?
How to set caption for an image using HTML ?

30 Sep, 2020
The <figurecaption> tag in HTML is used to set a caption to the figure element in a document. This tag is new in HTML5. 
Syntax:
<figcaption> Figure caption... </figcaption>

Example 1: 
HTML
<!DOCTYPE html><html>  <head>    <style>        body {            text-align: center;        }          h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h3>        How to define an image caption?    </h3>      <figure>        <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeks-25.png"              alt="gfglogo" style="width:50%">                  <figcaption>GeeksforGeeks Logo</figcaption>    </figure></body>  </html>
Output:
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
How to create a modal image gallery with CSS and JavaScript?

Following is the code to create modal image gallery with CSS and JavaScript −
 Live Demo
<!DOCTYPE html>
<html>
<head<
<meta name="viewport" content="width=device-width, initial-scale=1" /<
<style>
* {
   box-sizing: border-box;
}
h1 {
   text-align: center;
}
.ImgThumbnail {
   border-radius: 5px;
   cursor: pointer;
   transition: 0.3s;
   height: 250px;
   width: 250px;
}
.ImgThumbnail:nth-of-type(1) {
   margin-left: 20%;
}
.modal {
   display: none;
   position: fixed;
   z-index: 1;
   padding-top: 100px;
   left: 0;
   top: 0;
   width: 100%;
   height: 100%;
   overflow: auto;
   background-color: rgb(0, 0, 0);
   background-color: rgba(0, 0, 0, 0.9);
}
.modalImage {
   margin: auto;
   display: block;
   width: 50%;
   height: 60%;
   max-width: 700px;
}
#caption {
   margin: auto;
   display: block;
   width: 80%;
   max-width: 700px;
   text-align: center;
   color: #ccc;
   padding: 10px 0;
   height: 150px;
}
.close {
   position: absolute;
   top: 15px;
   right: 35px;
   color: #f1f1f1;
   font-size: 40px;
   font-weight: bold;
   transition: 0.3s;
}
.close:hover,
.close:focus {
   color: rgb(255, 0, 0);
   cursor: pointer;
}
@media only screen and (max-width: 700px) {
   .modalImage {
      width: 100%;
   }
}
</style>
</head>
<body>
<h1<Image Modal Gallery Example</h1<
<img class="ImgThumbnail" src="https://images.pexels.com/photos/3540375/pexels-photo-3540375.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"/>
<img class="ImgThumbnail" src="https://i.picsum.photos/id/237/536/354.jpg"/>
<img class="ImgThumbnail" src="https://images.pexels.com/photos/3802510/pexels-photo-3802510.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"/>
<div class="modal">
<span class="close>×</span>
<img class="modalImage" id="img01" />
</div>
<script>
var modalEle = document.querySelector(".modal");
var modalImage = document.querySelector(".modalImage");
Array.from(document.querySelectorAll(".ImgThumbnail")).forEach(item => {
   item.addEventListener("click", event => {
      modalEle.style.display = "block";
      modalImage.src = event.target.src;
   });
});
document.querySelector(".close").addEventListener("click", () => {
   modalEle.style.display = "none";
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking on any of the images −
Java Program to set the Font and Color of some text in a JTextPane using Styles

Let’s say the following is our JTextPane −
JTextPane textPane = new JTextPane();
Now, set the font style for some of the text −
SimpleAttributeSet attributeSet = new SimpleAttributeSet();
StyleConstants.setItalic(attributeSet, true);
textPane.setCharacterAttributes(attributeSet, true);
textPane.setText("Learn with Text and ");
For rest of the text, set different color −
StyledDocument doc = textPane.getStyledDocument();
Style style = textPane.addStyle("", null);
StyleConstants.setForeground(style, Color.orange);
StyleConstants.setBackground(style, Color.black);
doc.insertString(doc.getLength(), "Video Tutorials ", style);
The following is an example to set font and text color in a JTextPane with Styles −
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class SwingDemo {
   public static void main(String args[]) throws BadLocationException {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Container container = frame.getContentPane();
      JTextPane textPane = new JTextPane();
      textPane.setBackground(Color.red);
      SimpleAttributeSet attributeSet = new SimpleAttributeSet();
      StyleConstants.setItalic(attributeSet, true);
      textPane.setCharacterAttributes(attributeSet, true);
      textPane.setText("Learn with Text and "); Font font = new Font("Verdana", Font.BOLD, 22);
      textPane.setFont(font);
      StyledDocument doc = textPane.getStyledDocument();
      Style style = textPane.addStyle("", null);
      StyleConstants.setForeground(style, Color.orange);
      StyleConstants.setBackground(style, Color.black);
      doc.insertString(doc.getLength(), "Video Tutorials ", style);
      JScrollPane scrollPane = new JScrollPane(textPane);
      container.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
This will produce the following output −
VBA - Do-While Loops

A Do...While loop is used when we want to repeat a set of statements as long as the condition is true. The condition may be checked at the beginning of the loop or at the end of the loop.
Following is the syntax of a Do...While loop in VBA.
Do While condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop           

The following example uses Do...while loop to check the condition at the beginning of the loop. The statements inside the loop are executed, only if the condition becomes True.
Private Sub Constant_demo_Click()
   Do While i < 5
      i = i + 1
      msgbox "The value of i is : " & i
   Loop
End Sub
When the above code is executed, it prints the following output in a message box.
The value of i is : 1

The value of i is : 2

The value of i is : 3

The value of i is : 4

The value of i is : 5

There is also an alternate Syntax for Do...while loop which checks the condition at the end of the loop. The major difference between these two syntax is explained in the following example.
Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop While condition

The following example uses Do...while loop to check the condition at the end of the loop. The Statements inside the loop are executed at least once, even if the condition is False.
Private Sub Constant_demo_Click() 
   i = 10
   Do
      i = i + 1
      MsgBox "The value of i is : " & i
   Loop While i < 3 'Condition is false.Hence loop is executed once.
End Sub
When the above code is executed, it prints the following output in a message box.
The value of i is : 11


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Inheritance in Python

In this article, we will learn inheritance and extending classes in Python 3.x. Or earlier.
Inheritance represents real-world relationships well, provides reusability & supports transitivity. It offers faster development time, easier maintenance and easy to extend.
Inheritance is broadly categorized into 5 types −
Single
Multiple
Hierarchical
Multi-level
Hybrid
As shown in the figure above that inheritance is the process in which we try to access the features of other classes without actually making the object of the parent class.
Here we will be learning about the implementation of single and Hierarchical inheritances.
 Live Demo
# parent class
class Student():
   # constructor of parent class
   def __init__(self, name, enrollnumber):
      self.name = name
      self.enrollnumber = enrollnumber
   def display(self):
      print(self.name)
      print(self.enrollnumber)
# child class
class College( Student ):
   def __init__(self, name, enrollnumber, admnyear, branch):
      self.admnyear = admnyear
      self.branch = branch
      # invoking the __init__ of the parent class
      Student.__init__(self, name, enrollnumber)
# creation of an object for base/derived class
obj = College('Rohit',42414802718,2018,"CSE")
obj.display()
Rohit
42414802718
 Live Demo
# parent class
class Student():
   # constructor of parent class
   def __init__(self, name, enrollnumber):
      self.name = name
      self.enrollnumber = enrollnumber
   def display(self):
      print(self.name)
      print(self.enrollnumber)
# child class
class College( Student ):
   def __init__(self, name, enrollnumber, admnyear, branch):
      self.admnyear = admnyear
      self.branch = branch
      # invoking the __init__ of the parent class
      Student.__init__(self, name, enrollnumber)
# child class
class University( Student ):
   def __init__(self, name, enrollnumber, refno, branch):
      self.refno = refno
      self.branch = branch
      # invoking the __init__ of the parent class
      Student.__init__(self, name, enrollnumber)
# creation of an object for base/derived class
obj_1 = College('Rohit',42414802718,2018,"CSE")
obj_1.display()
obj_2 = University ('Rohit',42414802718,"st2018","CSE")
obj_2.display()
Rohit
42414802718
Rohit
42414802718
In this article, we learned about Inheritance in Python broadly single and hierarchical inheritance.
Google Charts - Stacked Area Chart

Following is an example of a stacked area chart. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used isStacked configuration to show stacked chart.
// Set chart options
var options = {
   isStacked: true
};
googlecharts_area_stacked.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable([
               ['Year', 'Asia', 'Europe'],
               ['2013',  1000,      400],
               ['2014',  1170,      460],
               ['2015',  1300,       480],
               ['2016',  1530,      540]
            ]);

            var options = {title: 'Population (in millions)',
               hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
               vAxis: {minValue: 0},
               isStacked: true
            };  

            // Instantiate and draw the chart.
            var chart = new google.visualization.AreaChart(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Substring in C#

Substring is used to get the sub-parts of a string in C#. We have the substring() method for this purpose. Use the substring() method in C# to check each and every substring for unique characters. Loop it until the length of the string.
If anyone the substring matches another, then it would mean that the string does not have unique characters.
You can try to run the following code to determine if a string has all unique characters. The example shows the usage of Substring() method −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Demo {

   public bool CheckUnique(string str) {
      string one = "";
      string two = "";

      for (int i = 0; i < str.Length; i++) {
         one = str.Substring(i, 1);
         for (int j = 0; j < str.Length; j++) {
            two = str.Substring(j, 1);
            if ((one == two) && (i != j))
            return false;
         }
      }
      return true;
   }

   static void Main(string[] args) {
      Demo d = new Demo();
      bool b = d.CheckUnique("amit");
      Console.WriteLine(b);

      Console.ReadKey();
   }
}
Design Patterns - Mediator Pattern 

Mediator pattern is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category.
We are demonstrating mediator pattern by example of a chat room where multiple users can send message to chat room and it is the responsibility of chat room to show the messages to all users. We have created two classes ChatRoom and User. User objects will use ChatRoom method to share their messages.
MediatorPatternDemo, our demo class, will use User objects to show communication between them.
Create mediator class.
ChatRoom.java
import java.util.Date;

public class ChatRoom {
   public static void showMessage(User user, String message){
      System.out.println(new Date().toString() + " [" + user.getName() + "] : " + message);
   }
}
Create user class
User.java
public class User {
   private String name;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public User(String name){
      this.name  = name;
   }

   public void sendMessage(String message){
      ChatRoom.showMessage(this,message);
   }
}
Use the User object to show communications between them.
MediatorPatternDemo.java
public class MediatorPatternDemo {
   public static void main(String[] args) {
      User robert = new User("Robert");
      User john = new User("John");

      robert.sendMessage("Hi! John!");
      john.sendMessage("Hello! Robert!");
   }
}
Verify the output.
Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John!
Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!


    102 Lectures 
     10 hours 

 Arnab Chakraborty

    30 Lectures 
     3 hours 

 Arnab Chakraborty

    31 Lectures 
     4 hours 

 Arnab Chakraborty

    43 Lectures 
     1.5 hours 

 Manoj Kumar

    7 Lectures 
     1 hours 

 Zach Miller

    54 Lectures 
     4 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Matplotlib.pyplot.text() function in Python - GeeksforGeeks

25 Nov, 2020
This function is used to add a text to the axes at location x, y in data coordinates.
Syntax: matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
Example #1: Text on plot sheet
Python3
import matplotlib.pyplot  matplotlib.pyplot.text(0.5, 0.5, "Hello World!")matplotlib.pyplot.savefig("out.png")
Output: 
Example #2: Add text to a plot
Python3
import matplotlib.pyplot as plt    w = 4h = 3d = 70  plt.figure(figsize=(w, h), dpi=d)  x = [1, 2, 4]x_pos = 0.5y_pos = 3  plt.text(x_pos, y_pos, "text on plot")plt.plot(x)plt.savefig("out.png")
Output:
Matplotlib Pyplot-class
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Python | Decimal compare() method - GeeksforGeeks

05 Sep, 2019
Decimal#compare() : compare() is a Decimal class method which compares the two Decimal values.
Syntax: Decimal.compare()
Parameter: Decimal values
Return:1 – if a > b-1 – if a < b0 – if a = b
Code #1 : Example for compare() method
# Python Program explaining # compare() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal(-1)  b = Decimal('0.142857')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.compare() methodprint ("\n\nDecimal a with compare() method : ", a.compare(a))  print ("Decimal a with compare() method : ", a.compare(b))  print ("Decimal b with compare() method : ", b.compare(a))
Output :
Decimal value a :  -1
Decimal value b :  0.142857


Decimal a with compare() method :  0
Decimal a with compare() method :  -1
Decimal b with compare() method :  1


Code #2 : Example for compare() method
# Python Program explaining # compare() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('-3.14')  b = Decimal('321e + 5')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.compare() methodprint ("\n\nDecimal a with compare() method : ", a.compare(a))  print ("Decimal a with compare() method : ", a.compare(b))  print ("Decimal b with compare() method : ", b.compare(a))
Output :
Decimal value a :  -3.14
Decimal value b :  3.21E+7


Decimal a with compare() method :  0
Decimal a with compare() method :  -1
Decimal b with compare() method :  1

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Swapping two column values in MySQL?

To swap two columns, we can apply the below swapping logic.
Add both values and store them into the first column
Add both values and store them into the first column
Subtract the first column’s value from the second and store it into the second column.

Subtract the first column’s value from the second and store it into the second column.

Subtract the first column’s value from the updated second column and store it into the first.
Subtract the first column’s value from the updated second column and store it into the first.
The above rule structure is as follows. Suppose, the first column is a and the second column is b.
1. a = a+b;
2. b = a-b;
3. a = a-b;
Now we will apply the above rule in order to swap the two column values.
Creating a table.
mysql> create table SwappingTwoColumnsValueDemo
   -> (
   -> FirstColumnValue int,
   -> SecondColumnValue int
   -> );
Query OK, 0 rows affected (0.49 sec)
Inserting some records.
mysql>  insert into SwappingTwoColumnsValueDemo values(10,20),(30,40),(50,60),(70,80),(90,100);
Query OK, 5 rows affected (0.19 sec)
Records: 5  Duplicates: 0  Warnings: 0
To check the column values before swapping.
mysql> select *from SwappingTwoColumnsValueDemo;
The following is the output.
+------------------+-------------------+
| FirstColumnValue | SecondColumnValue |
+------------------+-------------------+
|               10 |                20 |
|               30 |                40 |
|               50 |                60 |
|               70 |                80 |
|               90 |               100 |
+------------------+-------------------+
5 rows in set (0.00 sec)

Syntax to swap column values.
mysql> UPDATE SwappingTwoColumnsValueDemo
   -> SET FirstColumnValue = FirstColumnValue+SecondColumnValue,
   -> SecondColumnValue = FirstColumnValue-SecondColumnValue,
   -> FirstColumnValue = FirstColumnValue-SecondColumnValue;
Query OK, 5 rows affected (0.15 sec)
Rows matched: 5  Changed: 5  Warnings: 0
To check if the column values have been swapped or not.
mysql> select *from SwappingTwoColumnsValueDemo;
The following is the output.
+------------------+-------------------+
| FirstColumnValue | SecondColumnValue |
+------------------+-------------------+
|               20 |                10 |
|               40 |                30 |
|               60 |                50 |
|               80 |                70 |
|              100 |                90 |
+------------------+-------------------+
5 rows in set (0.00 sec)
C# Program to find whether the Number is Divisible by 2

If the remainder of the number when it is divided by 2 is 0, then it would be divisible by 2.
Let’s say our number is 5, we will check it using the following if-else −
// checking if the number is divisible by 2 or not
if (num % 2 == 0) {
   Console.WriteLine("Divisible by 2 ");
} else {
   Console.WriteLine("Not divisible by 2");
}
The following is an example to find whether the number is divisible by 2 or not.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int num;
         num = 5;
         // checking if the number is divisible by 2 or not
         if (num % 2 == 0) {
            Console.WriteLine("Divisible by 2 ");
         } else {
            Console.WriteLine("Not divisible by 2");
         }
         Console.ReadLine();
      }
   }
}
Not divisible by 2
C program to find sum of digits of a five digit number

Suppose we have a five-digit number num. We shall have to find the sum of its digits. To do this we shall take out digits from right to left. Each time divide the number by 10 and the remainder will be the last digit and then update the number by its quotient (integer part only) and finally the number will be reduced to 0 at the end. So by summing up the digits we can get the final sum.
So, if the input is like num = 58612, then the output will be 22 because 5 + 8 + 6 + 1 + 2 = 22.
To solve this, we will follow these steps −
num := 58612
sum := 0
while num is not equal to 0, do:sum := sum + num mod 10num := num / 10
sum := sum + num mod 10
num := num / 10
return sum
Let us see the following implementation to get better understanding −
#include <stdio.h>
int main(){
    int num = 58612;
    int sum = 0;
   
    while(num != 0){
        sum += num % 10;
        num = num/10;
    }
    printf("Digit sum: %d", sum);
}

58612
Digit sum: 22
HTML | <td> align Attribute

31 Dec, 2021
The HTML <td> align attribute is used to set the horizontal alignment of text content. It is not supported by HTML 5.
Syntax:
<td align ="left | right | center | justify | char">
Attribute Values:
left: It sets the text left-align.
right: It sets the text right-align.
center: It sets the text center-align.
justify: It stretches the text of paragraph to set the width of all lines equal.
char: It sets the text-align to a specific character.
Note : The <td> align attribute is not supported by HTML 5. Use CSS instead .
Example:
<!DOCTYPE html><html>  <head>    <title>      HTML td align Attribute  </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML td align Attribute</h2>      <table width="500" border="1">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>          <tr>            <td align="center">BITTU</td>            <td align="left">22</td>            <td align="right">CSE</td>        </tr>          <tr>            <td align="center">RAKESH</td>            <td align="left">25</td>            <td align="right">EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <td> align attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
hritikbhatnagar2182
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
JavaScript | RegExp \W Metacharacter

22 Apr, 2019
The RegExp \W Metacharacter in JavaScript is used to find the non word character i.e. characters which are not from a to z, A to Z, 0 to 9. It is same as [^a-zA-Z0-9].
Syntax:
/\W/ 
or
new RegExp("\\W")
Syntax with modifiers:
/\W/g 
or
new RegExp("\\W", "g")
Example 1: This example searches the non words characters.
<!DOCTYPE html><html>  <head>    <title>        JavaScript RegExp \W Metacharacter    </title></head>  <body style="text-align:center">          <h1 style="color:green">        GeeksforGeeks    </h1>          <h2>RegExp \W Metacharacter</h2>          <p>        Input String: GeeksforGeeks@_123_$    </p>          <button onclick="geek()">        Click it!    </button>          <p id="app"></p>          <script>        function geek() {            var str1 = "GeeksforGeeks@_123_$";            var regex4 = /\W/g;            var match4 = str1.match(regex4);              document.getElementById("app").innerHTML =                         "Found " + match4.length                        + " matches: " + match4;        }    </script></body>  </html>                    
Output:Before Clicking the button:After Clicking the button:
Example 2: This example searches the non-word characters in the whole string.
<!DOCTYPE html><html>  <head>    <title>        JavaScript RegExp \W Metacharacter    </title></head>  <body style="text-align:center">          <h1 style="color:green">        GeeksforGeeks    </h1>          <h2>RegExp \W Metacharacter</h2>          <p>Input String: Geeky@128</p>          <button onclick="geek()">        Click it!    </button>          <p id="app"></p>          <script>        function geek() {            var str1 = "Geeky@128";                     var regex4 = new RegExp("\\W", "g");            var match4 = str1.match(regex4);              document.getElementById("app").innerHTML =                        "Found " + match4.length                        + " matches: " + match4;        }    </script></body>  </html>                    
Output:Before Clicking the button:After Clicking the button:
Supported Browsers: The browsers supported by RegExp \W Metacharacter are listed below:
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
JavaScript-RegExp
JavaScript
Web Technologies
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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
\boxed - Tex Command

\boxed - Used to draw a box around argument; argument is in math mode.
{ \boxed #1 }
\boxed command draws a box around argument; argument is in math mode.

\boxed ab 

ab


\boxed{ab} 

ab


\boxed{ab\strut} 

ab


\boxed{\text{boxed text}} 

boxed text



\boxed ab 

ab


\boxed ab 
\boxed{ab} 

ab


\boxed{ab} 
\boxed{ab\strut} 

ab


\boxed{ab\strut} 
\boxed{\text{boxed text}} 

boxed text


\boxed{\text{boxed text}} 

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Program to find winner of stone game in Python

Suppose Amal and Bimal are playing a game and Amal's turn is first. The game is like below −
There are n stones in a pile. Each player can take a stone from the pile and receive points based on the position of that stone. Amal and Bimal may value the stones in different manner.
We have two arrays of same length, A_Values and B_Values. Each A_Values[i] and B_Values[i] represents how Amal and Bimal, respectively, value the ith stone. Here whose score is maximum, he will be winner after all the stones are taken out. If there is a tie, the game results in a draw. Both players will play optimally. Both of them know the other's values. So if Amal wins, return 1. If Bimal wins, return -1. And for a draw match, return 0.
So, if the input is like A_Values = [2,4] B_Values = [3,5], then the output will be 1 because Amal will select second stone with point 4, so Bimal has only one chance to take first stone with point 3, but as Amal has greater score, so he wins.
To solve this, we will follow these steps −
n := size of A_Values
combinedValues := a new list
for i in range 0 to n, dotmpV := A_Values[i] + B_Values[i]insert pair (temV, i) into combinedValues at the end
tmpV := A_Values[i] + B_Values[i]
insert pair (temV, i) into combinedValues at the end
sort the list combinedValues in reverse order
score_a := 0, score_b := 0
for i in range 0 to n - 1, docurV := combinedValues[i]if i mod 2 is same as 0, thenscore_a := score_a + A_Values[curV[1]]otherwise,score_b := score_b + B_Values[curV[1]]
curV := combinedValues[i]
if i mod 2 is same as 0, thenscore_a := score_a + A_Values[curV[1]]
score_a := score_a + A_Values[curV[1]]
otherwise,score_b := score_b + B_Values[curV[1]]
score_b := score_b + B_Values[curV[1]]
if score_a > score_b, thenreturn 1
return 1
otherwise when score_a is same as score_b, thenreturn 0
return 0
otherwise,return -1
return -1
Let us see the following implementation to get better understanding −
def solve(A_Values, B_Values):
   n = len(A_Values)
   combinedValues = []
   for i in range(n):
      tmpV = A_Values[i] + B_Values[i]
      combinedValues.append([tmpV, i])

   combinedValues.sort(reverse=True)

   score_a, score_b = 0, 0
   for i in range(n):
      curV = combinedValues[i]
      if (i % 2 == 0):
         score_a += A_Values[curV[1]]
      else:
         score_b += B_Values[curV[1]]

   if (score_a > score_b):
      return 1
   elif (score_a == score_b):
      return 0
   else:
      return -1

A_Values = [2,4]
B_Values = [3,5]
print(solve(A_Values, B_Values))
[2,4], [3,5]

1
How to multiply a given number by 2 using Bitwise Operators in C#?

A number can be multiplied by 2 using bitwise operators. This is done by using the left shift operator and shifting the bits left by 1. This results in double the previous number.
A program that demonstrates multiplication of a number by 2 using bitwise operators is given as follows.
 Live Demo
using System;
namespace BitwiseDemo {
   class Example {
      static void Main(string[] args) {
         int num = 25, result;
         result = num << 1;
         Console.WriteLine("The original number is: {0}", num);
         Console.WriteLine("The number multiplied by two is: {0}", result);
      }
   }
}
The output of the above program is as follows.
The original number is: 25
The number multiplied by two is: 50
Now let us understand the above program.
First, the number is defined. Then, the left shift operator is used and the bits in num are shifted left by 1. This results in double the previous number which is stored in result. Then, the values of num and result are displayed. The code snippet for this is given as follows −
int num = 25, result;
result = num << 1;
Console.WriteLine("The original number is: {0}", num);
Console.WriteLine("The number multiplied by two is: {0}", result);
How to find intersection between two Numpy arrays?

In this problem, we will find the intersection between two numpy arrays. Intersection of two arrays is an array with elements common in both the original arrays
Step 1: Import numpy.
Step 2: Define two numpy arrays.
Step 3: Find intersection between the arrays using the numpy.intersect1d() function.
Step 4: Print the array of intersecting elements.
import numpy as np

array_1 = np.array([1,2,3,4,5])
print("Array 1:\n", array_1)

array_2 = np.array([2,4,6,8,10])
print("\nArray 2:\n", array_2)

intersection = np.intersect1d(array_1, array_2)
print("\nThe intersection between the two arrays is:\n", intersection)
Array 1:
 [1 2 3 4 5]
Array 2:
 [2  4  6  8 10]
The intersection between the two arrays is:
 [2 4]