code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.figure.Figure.set_facecolor() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_facecolor() method figure module of matplotlib library is used to set the face color of the Figure rectangle.
Syntax: set_facecolor(self, color)
Parameters: This method accept the following parameters that are discussed below:
color : This parameter is the color.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_facecolor() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np         fig = plt.figure()        ax = Subplot(fig, 111) fig.add_subplot(ax)    fig.set_facecolor("green")     fig.suptitle("""matplotlib.figure.Figure.set_facecolor()function Example\n\n""", fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np           fig = plt.figure(figsize =(7, 6))         ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])      xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))     fig.set_facecolor("red")     fig.suptitle("""matplotlib.figure.Figure.set_facecolor()function Example\n\n""", fontweight ="bold")   plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
Tailwind CSS Grayscale - GeeksforGeeks

23 Mar, 2022
The Grayscale class is used to apply a filter to the image to set the grayscale of the image. In CSS, we do that by using the CSS grayscale() Function. Tailwind CSS newly added feature brightness in 2.1 version.
Grayscale:
grayscale-0: This class is used to represents the original image.grayscale: This class is used to represents the linear multipliers on the effect.
grayscale-0: This class is used to represents the original image.
grayscale: This class is used to represents the linear multipliers on the effect.
Syntax:
<element class="filter grayscale | grayscale-0">..</element>
Example:
HTML
<!DOCTYPE html><html><head>    <link href="https://unpkg.com/tailwindcss@^2.1/dist/tailwind.min.css"        rel="stylesheet"></head>  <body class="text-center mx-20 space-y-2">    <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>    <b>Tailwind CSS Grayscale Class</b>    <div class="grid grid-flow-col text-center mx-44">        <img class="rounded-lg filter grayscale"           src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg"              alt="image">        <img class="rounded-lg filter grayscale-0"              src="https://media.geeksforgeeks.org/wp-content/uploads/20210604014825/QNHrwL2q-100x100.jpg"              alt="image">              </div></body>  </html>
Output:
Tailwind CSS
Tailwind-Filters
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
PostgreSQL - LAG Function - GeeksforGeeks

08 Oct, 2021
In PostgreSQL, the LAG() function is used to access a row that comes exactly before the current row at a specific physical offset. The LAG() comes in handy while comparing the values of the current row with the previous row.
The following shows the syntax of LAG() function:
Syntax:
LAG(expression [, offset [, default_value]]) 
OVER (
    [PARTITION BY partition_expression, ... ]
    ORDER BY sort_expression [ASC | DESC], ...
)
Let’s analyze the above syntax:
The expression is used to set a comparision basis for the comparision of current and exactly previous rows at a specified offset. It can any among the following, be a column, an expression, or a subquery.
The offset is a positive integer that is used to set in the query the number of rows that that come before the current row. The offset can be an expression, a subquery, or a column. If it is not specified, it defaults to 1.
The LAG() function will return the default_value when the offset goes beyond the scope of the partition.
The LAG() function is applied on the partitions created by the PARTITION BY clause.If partition is not specified, the function treats the whole result set as a single partition.
The ORDER BY clause sets the order of the rows in each partition to which the LAG() function is applied.
Example 1:
Let’s set up a new table for the demonstration named sales:
CREATE TABLE sales(
    year SMALLINT CHECK(year > 0),
    group_id INT NOT NULL,
    amount DECIMAL(10, 2) NOT NULL,
    PRIMARY KEY(year, group_id)
);
Add some data to it:
INSERT INTO 
    sales(year, group_id, amount) 
VALUES
    (2018, 1, 1474),
    (2018, 2, 1787),
    (2018, 3, 1760),
    (2019, 1, 1915),
    (2019, 2, 1911),
    (2019, 3, 1118),
    (2020, 1, 1646),
    (2020, 2, 1975),
    (2020, 3, 1516);
Here the LAG() function to return the sales amount of the current year and the previous year:
WITH cte AS (
    SELECT 
        year, 
        SUM(amount) amount
    FROM sales
    GROUP BY year
) 
SELECT
    year, 
    amount,
    LAG(amount, 1) OVER (
        ORDER BY year
    ) last_year_sales
FROM
    cte;
Output:
Example 2:
This example uses the LAG() function to compare the sales of the current year with the sales of the previous year of each product group:
SELECT
    year, 
    amount,
    group_id,
    LAG(amount, 1) OVER (
        PARTITION BY group_id
        ORDER BY year
    ) last_year_sales
FROM
    sales;
Output:
sooda367
PostgreSQL-function
PostgreSQL-Window-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - TIME Data Type
PostgreSQL - REPLACE Function
PostgreSQL - Copy Table
PostgreSQL - CREATE SCHEMA
PostgreSQL - Rename Table
PostgreSQL - ROW_NUMBER Function
PostgreSQL - Identity Column
How to Change the Color of a Graph Plot in Matplotlib with Python? - GeeksforGeeks

12 Nov, 2020
Prerequisite: Matplotlib
Python offers a wide range of libraries for plotting graphs and Matplotlib is one of them. Matplotlib is simple and easy to use a library that is used to create quality graphs. The pyplot library of matplotlib comprises commands and methods that makes matplotlib work like matlab. The pyplot module is used to set the graph labels, type of chart and the color of the chart. The following methods are used for the creation of graph and corresponding color change of the graph.
Syntax: matplotlib.pyplot.bar(x, height, width, bottom, align, **kwargs)
Parameter:
x : sequence of scalers along the x axis
height : sequence of scaler determining the height of bar ie y-axis
width : width of each bar
bottom : Used to specify the starting value along the Y axis.(Optional)
align : alignment of the bar
**kwargs : other parameters one of which is color which obviously specifies the color of the graph.
Return Value: Returns the graph plotted from the specified columns of the dataset.
In this article, we are using a dataset downloaded from kaggel.com for the examples given below. The dataset used represent countries against the number of confirmed covid-19 cases. The dataset can be downloaded from the given link:
Link to the dataset: Corona virus report
Example 1:
Python3
# import packagesimport pandas as pdimport matplotlibimport matplotlib.pyplot as plt  # import datasetdf = pd.read_csv('country_wise_latest.csv')  # select required columnscountry = df['Country/Region'].head(10)confirmed = df['Confirmed'].head(10)  # plotting graphplt.xlabel('Country')plt.ylabel('Confirmed Cases')plt.bar(country, confirmed, color='green', width=0.4)  # display plotplt.show()
Output
Example 2:
Python3
# import packagesimport pandas as pdimport matplotlibimport matplotlib.pyplot as plt  # import datasetdf = pd.read_csv('country_wise_latest.csv')  # select required datacountry = df['Country/Region'].head(20)confirmed = df['Active'].head(20)  # plot graphplt.xlabel('Country')plt.ylabel('Active Cases')plt.bar(country, confirmed, color='maroon', width=0.4)  # display plotplt.show()
Output
Python-matplotlib
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
PrintWriter write(String) method in Java with Examples - GeeksforGeeks

29 Jan, 2019
The write(String) method of PrintWriter Class in Java is used to write the specified String on the stream. This String value is taken as a parameter.
Syntax:
public void write(String string)
Parameters: This method accepts a mandatory parameter string which is the String to be written in the Stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of write(String) method:
Program 1:
// Java program to demonstrate// PrintWriter write(String) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintWriter instance            PrintWriter writer                = new PrintWriter(System.out);              // Write the String 'GeeksForGeeks'            // to this writer using write() method            // This will put the string in the stream            // till it is printed on the console            writer.write("GeeksForGeeks");              writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GeeksForGeeks

Program 2:
// Java program to demonstrate// PrintWriter write(String) method  import java.io.*;  class GFG {    public static void main(String[] args)    {          try {              // Create a PrintWriter instance            PrintWriter writer                = new PrintWriter(System.out);              // Write the String 'GFG'            // to this writer using write() method            // This will put the string in the stream            // till it is printed on the console            writer.write("GFG");              writer.flush();        }        catch (Exception e) {            System.out.println(e);        }    }}
GFG

Java-Functions
Java-IO package
Java-PrintWriter
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
When is copy constructor called in C++?

The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to −
Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one. If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here −
classname (const classname &obj) {
   // body of constructor
}
Here, obj is a reference to an object that is being used to initialize another object.
 Live Demo
#include <iostream>
using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len ); // simple constructor
      Line( const Line &obj); // copy constructor
      ~Line(); // destructor

   private:
      int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;

   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
int main() {
   Line line(10);
   display(line);
   return 0;
}
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Let us see the same example but with a small change to create another object using an existing object of the same type −
 Live Demo
#include <iostream>
using namespace std;

class Line {
   public:
      int getLength( void );
      Line( int len ); // simple constructor
      Line( const Line &obj); // copy constructor
      ~Line(); // destructor

   private:
      int *ptr;
};

// Member functions definitions including constructor
Line::Line(int len) {
   cout << "Normal constructor allocating ptr" << endl;

   // allocate memory for the pointer;
   ptr = new int;
   *ptr = len;
}

Line::Line(const Line &obj) {
   cout << "Copy constructor allocating ptr." << endl;
   ptr = new int;
   *ptr = *obj.ptr; // copy the value
}

Line::~Line(void) {
   cout << "Freeing memory!" << endl;
   delete ptr;
}

int Line::getLength( void ) {
   return *ptr;
}

void display(Line obj) {
   cout << "Length of line : " << obj.getLength() <<endl;
}

// Main function for the program
   int main() {
   Line line1(10);
   Line line2 = line1; // This also calls copy constructor

   display(line1);
   display(line2);
   return 0;
}
Normal constructor allocating ptr
Copy constructor allocating ptr.
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Copy constructor allocating ptr.
Length of line : 10
Freeing memory!
Freeing memory!
Freeing memory!
How to set same scale for subplots in Python using Matplotlib?

To set the same scale for subplot in Python using Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Add an 'ax1' to the figure as part of a subplot arrangement with nrows=2, ncols=1 and index=1.
Add another axis 'ax2' to the figure as part of a subplot arrangement with nrows=2, ncols=1 and index=2, with shared X-axis (to set same scale for subplots)
Create "t" data points to plot sine and cosine curves on axes ax1 and ax2.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Plot the figure
fig = plt.figure()

# Add the axes
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

# Create data points
t = np.linspace(-5, 5, 100)

# Plot sine and cosine curves on ax1 and ax2
ax1.plot(t, np.sin(2 * np.pi * t), color='red', lw=4)
ax2.plot(t, np.cos(2 * np.pi * t), color='orange', lw=4)

plt.show()
It will produce the following output
How to access child's state in React? - GeeksforGeeks

01 Feb, 2021
In React we can access the child’s state using Refs.  we will assign a Refs for the child component in the parent component. then using Refs we can access the child’s state.
Creating Refs Refs are created using React.createRef() and attached to React elements via the ref attribute.
class App extends React.Component {
constructor(props) {
 super(props);
 //creating ref
 this.childRef= React.createRef();
}
render() {
 return (
 //assigning the ref to child component
 <Child ref= {this.myRef } />
 )
}
}
Accessing Refs When we assign a ref to an element or child component in the render, then we can access the element using the current attribute of the ref.
const element = this.myRef.current;
in the same way, we can access the state using element.state.state_name from the parent component.
Create a react app and edit the App.js file as:
Filepath- src/App.js
Javascript
import React from "react";import Child from './Child'  class App extends React.Component {  constructor(props) {    super(props);    this.ChildElement = React.createRef();  }  handleClick = () => {    const childelement = this.ChildElement.current;      alert("current state of child is :  "+ childelement.state.name);    childelement.changeName("Aakash");              };  render() {    return (      <div >        <Child ref={this.ChildElement} />        <button onClick={this.handleClick}>Show real name</button>      </div>    );  }}export default App
Create a new Child.js component in src folder and edit it as follow:
Filepath- src/Child.js:
Javascript
import React from 'react'class Child extends React.Component {  state = {    name: "Batman"  };  changeName = (newname ) => {    this.setState({      name:newname    });  };  render() {    return <div>{this.state.name}</div>;  }}export default Child
Output:
Picked
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
How to navigate on path by button click in react router ?
How to create a table in ReactJS ?
How to parse JSON Data into React Table Component ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Angular Libraries For Web Developers
Ionic - Icons

There are more than 700 premium icons provided by Ionic. There are also different sets of icons provided for Android and IOS. You can find almost anything you need but you are not bound to use them, if you do not want to. You can use your own custom icons or any other icon set instead. You can check all the Ionic icons here.
If you want to use Ionic icons find the icon you need on the page (https://ionicons.com/). When you are adding Ionic elements, you always add the main class first and then you add the subclass you want. The main class for all icons is icon. The Subclass is the name of the icon you want. We will add six icons in our example that is given below −
<i class = "icon icon ion-happy-outline"></i>
<i class = "icon icon ion-star"></i>
<i class = "icon icon ion-compass"></i>
<i class = "icon icon ion-planet"></i>
<i class = "icon icon ion-ios-analytics"></i>
<i class = "icon icon ion-ios-eye"></i>
The above code will produce the following screen −
The size of these icons can be changed with the font-size property in your Ionic CSS file.
.icon {
   font-size: 50px;
}
Once the icon size is setup, the same code will produce the following screenshot as the output −

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
Sorting an array of binary values - JavaScript

Let’s say, we have an array of Numbers that contains only 0, 1 and we are required to write a JavaScript function that takes in this array and brings all 1s to the start and 0s to the end.
For example − If the input array is −
const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];
Then the output should be −
const output = [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
Following is the code −
const arr = [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1];
const sortBinary = arr => {
   const copy = [];
   for(let i = 0; i − arr.length; i++){
      if(arr[i] === 0){
         copy.push(0);
      }else{
         copy.unshift(1);
      };
      continue;
   };
   return copy;
};
console.log(sortBinary(arr));
Following is the output in the console −
[
   1, 1, 1, 1, 1,
   1, 0, 0, 0, 0,
   0
]
Remove spaces from std::string in C++

In this program we will see how to remove the spaces from a std::string in C++. To remove this we will use the remove() function. With this remove() function it takes the beginning and end of the iterator, then takes the third argument that will be deleted from that iterator object.
Input: A string "This is C++ Programming Language"
Output: "ThisisC++ProgrammingLanguage"
Step 1: Get the string
Step 2: Remove spaces from the given string using remove() function.
Step 3: Return string.
 Live Demo
#include<iostream>
#include<algorithm>
using namespace std;
main() {
   string my_str = "This is C++ Programming Language";
   cout << "String with Spaces :" << my_str << endl;
   remove(my_str.begin(), my_str.end(), ' ');
   cout << "String without Spaces :" << my_str;
}
String with Spaces :This is C++ Programming Language
String without Spaces :ThisisC++ProgrammingLanguage
Download file through an AJAX call in PHP

Using Ajax to download files is not considered to be a good idea. Instead, window.location = or document.location should be used.
The 'window.location' has the following characteristics −
JavaScript enabling is required
It doesn't need PHP.
It helps show the content of the site, and redirects the user after a few seconds.
Redirect can be dependent on any conditions such as −
$success = 1
if ($success) {
   window.location.href = 'http://example.com';
}
A variable named ‘success’ is assigned with the value of 1. When this condition is satisfied, the window.location is used.
On running, the user is redirected to the website 'http://example.com'
How to use LINQ to sort a list in C#?

Use the LINQ orderby keyword to sort a list in C#.
In the below example, we have set the orderby for the elements −
var myLen = from element in myList
orderby element.Length
select element;
Let us see an example −
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;

class Demo {
   static void Main() {
      List <string> myList = new List<string>();
      myList.Add("truck");
      myList.Add("bus");
      myList.Add("cab");
      myList.Add("motorbike");

      var myLen = from element in myList
      orderby element.Length
      select element;

      foreach (string str in myLen) {
         Console.WriteLine(str);
      }
   }
}
The above will produce the following result. The word with less number of characters will be displayed first like an ascending order list −
bus
cab
truck
motorbike
How to Set a Tkinter Window With a Constant Size? - GeeksforGeeks

14 May, 2021
Prerequisite:
Python GUI – tkinter
minsize
maxsize
The task here is to produce a Tkinter window with a constant size. A window with a constant size cannot be resized as per users’ convenience, it holds its dimensions rigidly. A normal window on the other hand can be resized.
Approach
Import module
Declare Tkinter object
Create a fixed sized window using maxsize() and minsize() functions.
Syntax:
Here, height and width are in pixels.
minsize(height, width)
In Tkinter, minsize() method is used to set the minimum size of the Tkinter window. Using this method a user can set window’s initialized size to its minimum size, and still be able to maximize and scale the window larger.
maxsize(height, width)
This method is used to set the maximum size of the root window. User will still be able to shrink the size of the window to the minimum possible.
Program 1: Creating a normal window
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # Execute tkinterroot.mainloop()
Output:
 
Program 2: Creating a window with constant size
Python3
# Import modulefrom tkinter import * # Create objectroot = Tk() # Adjust sizeroot.geometry("400x400") # set minimum window size valueroot.minsize(400, 400) # set maximum window size valueroot.maxsize(400, 400) # Execute tkinterroot.mainloop()
Output:
surinderdawra388
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Setting the spacing between grouped bar plots in Matplotlib

To set the spacing between grouped bar plots in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create a dictionary for bar details to be plotted.
Create a dictionary for bar details to be plotted.
Make a Pandas dataframe using dictionary, d.
Make a Pandas dataframe using dictionary, d.
Plot the bar using dictionary, d, with align="center".
Plot the bar using dictionary, d, with align="center".
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import pandas as pd

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

d = {"Name": ["John", "Jacks", "James", "Joe"],"Age": [23, 12, 30, 26],"Marks": [98, 85, 70, 77]}

df = pd.DataFrame(d)
df.set_index('Name').plot(kind="bar", align='center', width=0.1)
plt.tick_params(rotation=45)

plt.show()
Online Javascript Formatter

Editable Javascript Code
12345678910111213141516171819202122232425262728var msg = 'Welcome Back';var colorTimer = null;function toHex(n){var hexChars = '0123456789ABCDEF';if (n === 0) return n;var j, k;var temp = '';while (n !== 0){j = n % 16;n = (n - j)/16;temp = hexChars.charAt(j) + temp;}return temp;}function colorize(){if (!document.getElementById) return;for (i=0; i<msg.length; i++){k = Math.round(Math.random() * 16777215);k = toHex(k);while (k.length < 6){k = k + '0';}document.getElementById('colorizer' + i).style.color = '#' + k;}colorTimer = window.setTimeout(colorize(), 230);}X
Privacy Policy
Cookies Policy
Terms of Use
Intersection of Two Arrays in C++

Suppose we have two arrays; we have to find their intersections.
So, if the input is like [1,5,3,6,9],[2,8,9,6,7], then the output will be [9,6]
To solve this, we will follow these steps −
Define two maps mp1, mp2
Define two maps mp1, mp2
Define an array res
Define an array res
for x in nums1(increase mp1[x] by 1)
for x in nums1
(increase mp1[x] by 1)
(increase mp1[x] by 1)
for x in nums2(increase mp2[x] by 1)
for x in nums2
(increase mp2[x] by 1)
(increase mp2[x] by 1)
for each key-value pair x in mp1cnt := 0cnt := minimum of value of x and mp2[key of x]if cnt > 0, then −insert key of x at the end of res
for each key-value pair x in mp1
cnt := 0
cnt := 0
cnt := minimum of value of x and mp2[key of x]
cnt := minimum of value of x and mp2[key of x]
if cnt > 0, then −insert key of x at the end of res
if cnt > 0, then −
insert key of x at the end of res
insert key of x at the end of res
return res
return res
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> intersection(vector<int>& nums1, vector<int>& nums2){
      unordered_map<int, int> mp1, mp2;
      vector<int> res;
      for (auto x : nums1)
         mp1[x]++;
      for (auto x : nums2)
         mp2[x]++;
      for (auto x : mp1) {
         int cnt = 0;
         cnt = min(x.second, mp2[x.first]);
         if (cnt > 0)
            res.push_back(x.first);
         }
         return res;
      }
};
main(){
   Solution ob;
   vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7};
   print_vector(ob.intersection(v, v1));
}
{1,5,3,6,9},{2,8,9,6,7}
[9, 6, ]
Python  Getting started with psycopg2-PostgreSQL

In this tutorial, we are going to learn how to use PostgreSQL with Python. You have to install certain thing before going into the tutorial. Let's install them.
Install the PostgreSQL with the guide..
Install the Python module psycopg2 for PostgreSQL connection and working. Run the command to install it.
pip install psycopg2
Now, open the pgAdmin. And create a sample database. Next, follow the below steps to get started with database operations.
Import the psycopg2 module.
Store the database name, username, and password in separate variables.
Make a connection to the database using psycopg2.connect(database=name,
user=name, password=password) method.
Instantiate a cursor object to execute SQL commands.
Create queries and execute them with cursor.execute(query) method.
And get the information using cursor.fetchall() method if available.
Close the connection using connection.close() method.
# importing the psycopg2 module
import psycopg2
# storing all the information
database = 'testing'
user = 'postgres'
password = 'C&o%Z?bc'
# connecting to the database
connection = psycopg2.connect(database=database, user=user, password=password)
# instantiating the cursor
cursor = connection.cursor()
# query to create a table
create_table = "CREATE TABLE testing_members (id SERIAL PRIMARY KEY, name VARCH
25) NOT NULL)"
# executing the query
cursor.execute(create_table)
# sample data to populate the database table
testing_members = ['Python', 'C', 'JavaScript', 'React', 'Django']
# query to populate the table testing_members
for testing_member in testing_members:
   populate_db = f"INSERT INTO testing_members (name) VALUES ('{testing_member
   cursor.execute(populate_db)
   # saving the changes to the database
   connection.commit()
   # query to fetch all
   fetch_all = "SELECT * FROM testing_members"
   cursor.execute(fetch_all)
   # fetching all the rows
   rows = cursor.fetchall()
   # printing the data
   for row in rows:
      print(f"{row[0]} {row[1]}")
      # closing the connection
      connection.close()
If you run the above code, then you will get the following result.
1 Python
2 C
3 JavaScript
4 React
5 Django
If you have any doubts in the tutorial, mention them in the comment section.
Difference between Comparable and Comparator in Java

Comparable and comparator both are an interface that can be used to sort the elements of the collection. Comparator interface belongs to java.util package while comparable belongs to java.lang package. Comparator interface sort collection using two objects provided to it, whereas comparable interface compares" this" refers to the one objects provided to it. 
public class ComparableExample {
   public static void main(String[] args) {
      List<Laptop> laptopList = new ArrayList<>();
      laptopList.add(new Laptop("HCL", 16, 800));
      laptopList.add(new Laptop("Apple", 8, 100));
      laptopList.add(new Laptop("Dell", 4, 600));
      Collections.sort(laptopList);
      for (Laptop lap : laptopList) {
         System.out.println(lap.getRam());
      }
   }
}
public class Laptop implements Comparable<Laptop> {
   String name;
   int ram;
   int price;
   public Laptop(String name, int ram, int price) {
      super();
      this.name = name;
      this.ram = ram;
      this.price = price;
   }
   public String getName() {
      return name;
   }
   public int getRam() {
      return ram;
   }
   public void setRam(int ram) {
      this.ram = ram;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getPrice() {
      return price;
   }
   public void setPrice(int price) {
      this.price = price;
   }
   @Override
   public int compareTo(Laptop o) {
      if (this.ram > o.getRam())
         return 1;
      else {
         return -1;
      }  
   }
}
4
8
16
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Laptop implements Comparator {
   String name;
   int ram;
   int price;
   public Laptop(String name, int ram, int price) {
      super();
      this.name = name;
      this.ram = ram;
      this.price = price;
   }
   public String getName() {
      return name;
   }
   public int getRam() {
      return ram;
   }
   public void setRam(int ram) {
      this.ram = ram;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getPrice() {
      return price;
   }
   public void setPrice(int price) {
      this.price = price;
   }
   @Override
   public int compare(Laptop o1, Laptop o2) {
      if (o1.getRam() < o2.getRam()) {
         return -1;
      }else if (o1.getRam() > o2.getRam()) {
         return 1;
      } else {
         return 0;
      }
   }
   public static void main(String[] args) {
      List laptopList = new ArrayList<>();
      laptopList.add(new Laptop("HCL", 16, 800));
      laptopList.add(new Laptop("Apple", 8, 100));
      laptopList.add(new Laptop("Dell", 4, 600));
      Comparator com = (Laptop o1, Laptop o2) -> o1.getName().compareTo(o2.getName());
      Collections.sort(laptopList, com);
      for (Laptop lap : laptopList) {
         System.out.println(lap.getName());
      }
   }
}
Apple
Dell
HCL
Get only the file extension from a column with file names as strings in MySQL?

For this, use the substring_index() function.
The syntax is as follows
select substring_index(yourColumnName, '. ', -1) AS anyAliasNamefrom yourTableName;
Let us first create a table. The query to create a table is as follows
mysql> create table AllFiles
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > UserName varchar(10),
   - > FileName varchar(100)
   - > );
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into AllFiles(UserName,FileName) values('Larry','AddTwoNumber.java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into AllFiles(UserName,FileName) values('Mike','AddTwoNumber.python');
Query OK, 1 row affected (0.15 sec)
mysql> insert into AllFiles(UserName,FileName) values('Sam','MatrixMultiplication.c');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AllFiles(UserName,FileName) values('Carol','vector.cpp');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from AllFiles;
The following is the output
+----+----------+------------------------+
| Id | UserName | FileName               |
+----+----------+------------------------+
|  1 | Larry    | AddTwoNumber.java      |
|  2 | Mike     | AddTwoNumber.python    |
|  3 | Sam      | MatrixMultiplication.c |
|  4 | Carol    | vector.cpp             |
+----+----------+------------------------+
4 rows in set (0.00 sec)
Here is the query to get only the file extension in MySQL
mysql> select substring_index(FileName,'.',-1) AS ALLFILENAMEEXTENSIONS from AllFiles;
The following is the output
+-----------------------+
| ALLFILENAMEEXTENSIONS |
+-----------------------+
| java                  |
| python                |
| c                     |
| cpp                   |
+-----------------------+
4 rows in set (0.00 sec)
C++ Program to Find Hamiltonian Cycle in an UnWeighted Graph

A Hamiltonian cycle is a Hamiltonian Path such that there is an edge (in graph) from the last vertex to the first vertex of the Hamiltonian Path. It is in an undirected graph is a path that visits each vertex of the graph exactly once.
Begin
   1. function isSafe() is used to check for whether it is
   adjacent to the previously added vertex and already not added.
   2. function hamiltonianCycle() solves the hamiltonian problem.
   3. function hamCycle() uses hamiltonianCycle() to solve
   the hamiltonian problem. It returns false if there is no
   Hamiltonian Cycle possible, otherwise return true and prints the path.
End
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define N 5
using namespace std;
void displaytheSolution(int path[]);
bool isSafe(int n, bool g[N][N], int path[], int pos) {
   if (g [path[pos-1]][n] == 0)
      return false;
   for (int i = 0; i < pos; i++)
      if (path[i] == n)
         return false;
   return true;
}
bool hamiltonianCycle(bool g[N][N], int path[], int pos) {
   //If all vertices are included in Hamiltonian Cycle
   if (pos == N) {
      if (g[ path[pos-1] ][ path[0] ] == 1)
         return true;
      else
         return false;
   }
   for (int n = 1; n < N; n++) {
      if (isSafe(n, g, path, pos)) { //Check if this vertex can be added to Hamiltonian Cycle
         path[pos] = n;
         //recur to construct rest of the path
         if (hamiltonianCycle (g, path, pos+1) == true)
            return true;
         path[pos] = -1; //remove vertex if it doesn’t lead to the solution
      }
   }
   return false;
}
bool hamCycle(bool g[N][N]) {
   int *path = new int[N];
   for (int i = 0; i < N; i++)
   path[i] = -1;
   //put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point
   //of the cycle as the graph is undirected
   path[0] = 0;
   if (hamiltonianCycle(g, path, 1) == false) {
      cout<<"\nCycle does not exist"<<endl;
      return false;
   }
   displaytheSolution(path);
   return true;
}
void displaytheSolution(int p[]) {
   cout<<"Cycle Exists:";
   cout<<" Following is one Hamiltonian Cycle \n"<<endl;
   for (int i = 0; i < N; i++)
   cout<<p[i]<<" ";
   cout<< p[0]<<endl;
}
int main() {
   bool g[N][N] = {{0, 1, 0, 1, 1},
      {0, 0, 1, 1, 0},
      {0, 1, 0, 1, 1},
      {1, 1, 1, 0, 1},
      {0, 1, 1, 0, 0},
   };
   hamCycle(g);
   return 0;
}
Cycle Exists: Following is one Hamiltonian Cycle
0 4 1 2 3 0
Usage and syntax of INNER and OUTER JOIN in DB2

Problem: How to explain INNER JOIN and OUTER JOIN with the help of an example on ORDERS and TRANSACTION DB2 table.
Solution
The JOIN is used to combine data from one or more tables in DB2. There are two main types of JOIN — INNER JOIN and OUTER JOIN. The basic difference between them is, INNER JOIN is an intersection of two or more tables while outer join is union of two or more tables. Basically, INNER JOIN is used to combine the data from multiple tables using equal column value and on the other hand, in case of OUTER JOIN, if the column values are not equal then also the row will b   e displayed with NULL values.
For example, consider the table below.
 
For INNER JOIN, we will use the below query.
SELECT ORDER_ID, TRANSACTION_ID FROM
   ORDERS FULL OUTER JOIN TRANSACTIONS ON
   ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID
For OUTER JOIN, we will use the below query.
SELECT ORDER_ID, TRANSACTION_ID FROM
   ORDERS FULL OUTER JOIN TRANSACTIONS ON
   ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID
MySQL order by string with numbers?

To MySQL order string with numbers, the following is the syntax, wherein we have used ORDER BY, SUBSTR() and CAST() −
SELECT *FROM yourTableName ORDER BY
SUBSTR(yourColumnName FROM 1 FOR 2),
CAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table OrderByStringWithNumbers
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Words varchar(10),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.86 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into OrderByStringWithNumbers(Words) values('A10');
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A30');
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A12');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A11');
Query OK, 1 row affected (0.17 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A28');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A21');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from OrderByStringWithNumbers;
The following is the output −
+----+-------+
| Id | Words |
+----+-------+
| 1  | A10   |
| 2  | A30   |
| 3  | A12   |
| 4  | A11   |
| 5  | A28   |
| 6  | A21   |
+----+-------+
6 rows in set (0.00 sec)
Here is the query to order by string with numbers −
mysql> select *from OrderByStringWithNumbers order by
   -> substr(Words from 1 for 2),
   -> cast(substr(Words from 2) AS UNSIGNED);
The following is the output −
+----+-------+
| Id | Words |
+----+-------+
| 1  | A10   |
| 4  | A11   |
| 3  | A12   |
| 6  | A21   |
| 5  | A28   |
| 2  | A30   |
+----+-------+
6 rows in set (0.00 sec)
C# | How to get hash code for the specified key of a Hashtable - GeeksforGeeks

01 Feb, 2019
Hashtable.GetHash(Object) method is used to get the hashcode of the specified key of a Hashtable object. This method is inherited from the Object Class.
Syntax:
protected virtual int GetHash(Object Key);

Exception: This method will give NullReferenceException if the key is null.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# Program to illustrate the // Hashtable.GetHash(Object) methodusing System;using System.Collections;  // Inheriting Hashtable as // Hashtable.GetHash(Object) // method is protected methodclass HashCode : Hashtable {          // Main Method    static void Main(string[] args)    {                  // creating object for HashCode as        // to access protected methods we        // have to create object for the         // derived class        HashCode h = new HashCode();                  // Add Elements into Hashtable        h.Add("1001", "Parek Shetty");        h.Add("1002", "Deshmuk Narayan");        h.Add("1003", "Ratan Kaalikaran");                  ICollection Key = h.Keys;          foreach(string val in Key)        {                          // printing Hashtable            Console.Write(val + " : " + h[val]);            Console.Write("\n");                          // printing hashcode with keys            int hcode = h.GetHash(val);                          Console.Write(val + " : " + hcode);            Console.Write("\n");        }    }}
1002 : Deshmuk Narayan
1002 : 985757554
1001 : Parek Shetty
1001 : -1708895167
1003 : Ratan Kaalikaran
1003 : -1892225314

Example 2:
// C# Program to illustrate the // Hashtable.GetHash(Object) methodusing System;using System.Collections;  class HashCode : Hashtable {          // Main Method    static void Main(string[] args)    {        HashCode h = new HashCode();                  // Adding elements        h.Add('A', "Pritam Devadhya");        h.Add('B', "Arjun Balachi");        h.Add('C', "Timanad Panigrahi");                  ICollection Key = h.Keys;                  int hcode = h.GetHash('C');                  Console.Write("HashCode: " + hcode);    }}
HashCode: 4390979

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.gethash?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
C# program to check for URL in a String

Use the StartWith() method in C# to check for URL in a String.
Let us say our input string is −
string input = "https://example.com/new.html";
Now we need to check for www or non-www link. For this, use the if statement in C# −
if (input.StartsWith("https://www.example.com") || input.StartsWith("https://example.com")) {
}
You can try to run the following code to check for URL in a string.
Live Demo
using System;
class Demo {
   static void Main() {
      string input = "https://example.com/new.html";
      // See if input matches one of these starts.
      if (input.StartsWith("https://www.example.com") || input.StartsWith("https://example.com")) {
         Console.WriteLine(true);
      }
   }
}
True
What is a one-dimensional array in C language?

An array is a group of related items that store with a common name.
The syntax is as follows for declaring an array −
datatype array_name [size];
Arrays are broadly classified into three types. They are as follows −
One – dimensional arrays
Two – dimensional arrays
Multi – dimensional arrays
The Syntax is as follows −
datatype array name [size]
For example, int a[5]
Initialization
An array can be initialized in two ways, which are as follows −
Compile time initialization
Runtime initialization
Following is the C program on compile time initialization −
 Live Demo
#include<stdio.h>
int main ( ){
   int a[5] = {10,20,30,40,50};
   int i;
   printf ("elements of the array are");
   for ( i=0; i<5; i++)
      printf ("%d", a[i]);
}
Upon execution, you will receive the following output −
Elements of the array are
10 20 30 40 50
Following is the C program on runtime initialization −
 Live Demo
#include<stdio.h>
main ( ){
   int a[5],i;
   printf ("enter 5 elements");
   for ( i=0; i<5; i++)
      scanf("%d", &a[i]);
   printf("elements of the array are");
   for (i=0; i<5; i++)
      printf("%d", a[i]);
}
The output is as follows −
enter 5 elements 10 20 30 40 50
elements of the array are : 10 20 30 40 50
Note
The output of compile time initialised program will not change during different runs of the program.
The output of compile time initialised program will not change during different runs of the program.
The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution.
The output of run time initialised program will change for different runs because, user is given a chance of accepting different values during execution.
Following is another C program for one dimensional array −
 Live Demo
#include <stdio.h>
int main(void){
   int a[4];
   int b[4] = {1};
   int c[4] = {1,2,3,4};
   int i; //for loop counter
   //printing all elements of all arrays
   printf("\nArray a:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i,a[i]);
      printf("\nArray b:\n");
   for( i=0; i<4; i++)
      printf("arr[%d]: %d\n",i,b[i]);
      printf("\nArray c:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i, c[i]);
   return 0;
}
The output is stated below −
Array a:
arr[0]: 8
arr[1]: 0
arr[2]: 54
arr[3]: 0
Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0
Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4