code-rag-bench/online-tutorials huggingface dataset:
BFS using STL for competitive coding - GeeksforGeeks

15 Nov, 2021
A STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector.  
In BFS, we start with a node.
1) Create a queue and enqueue source into it. 
   Mark source as visited.
2) While queue is not empty, do following
    a) Dequeue a vertex from queue. Let this 
       be f.
    b) Print f
    c) Enqueue all not yet visited adjacent
       of f and mark them visited.
Below is an example BFS starting from source vertex 1. Note that there can be multiple BFSs possible for a graph (even from a particular vertex).  
For more details of BFS, refer this post . The code here is simplified such that it could be used in competitive coding.  
CPP
// A Quick implementation of BFS using// vectors and queue#include <bits/stdc++.h>#define pb push_back  using namespace std;  vector<bool> v;vector<vector<int> > g;  void edge(int a, int b){    g[a].pb(b);      // for undirected graph add this line    // g[b].pb(a);}  void bfs(int u){    queue<int> q;      q.push(u);    v[u] = true;      while (!q.empty()) {          int f = q.front();        q.pop();          cout << f << " ";          // Enqueue all adjacent of f and mark them visited         for (auto i = g[f].begin(); i != g[f].end(); i++) {            if (!v[*i]) {                q.push(*i);                v[*i] = true;            }        }    }}  // Driver codeint main(){    int n, e;    cin >> n >> e;      v.assign(n, false);    g.assign(n, vector<int>());      int a, b;    for (int i = 0; i < e; i++) {        cin >> a >> b;        edge(a, b);    }      for (int i = 0; i < n; i++) {        if (!v[i])            bfs(i);    }      return 0;}
Input:
8 10
0 1
0 2
0 3
0 4
1 5
2 5
3 6
4 6
5 7
6 7

Output:
0 1 2 3 4 5 6 7
This article is contributed by Nikhil Mahendran. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
chhabradhanvi
BFS
cpp-queue
cpp-vector
Competitive Programming
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bits manipulation (Important tactics)
Formatted output in Java
Algorithm Library | C++ Magicians STL Algorithm
Use of FLAG in programming
Setting up Sublime Text for C++ Competitive Programming Environment
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Graph and its representations
Elixir - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. There are a LOT of operators provided by elixir. They are divided in the following categories −
Arithmetic operators
Comparison operators
Boolean operators
Misc operators
The following table shows all the arithmetic operators supported by Elixir language. Assume variable A holds 10 and variable B holds 20, then −
Show Examples
The comparison operators in Elixir are mostly common to those provided in most other languages. The following table sums up comparison operators in Elixir. Assume variable A holds 10 and variable B holds 20, then −
Show Examples
Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then −
Show Examples
NOTE −and, or, && and || || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example, 
false and raise("An error")  
#This won't raise an error as raise function wont get executed because of short
#circuiting nature of and operator
Bitwise operators work on bits and perform bit by bit operation. Elixir provides bitwise modules as part of the package Bitwise, so in order to use these, you need to use the bitwise module. To use it, enter the following command in your shell −
use Bitwise

 Assume A to be 5 and B to be 6 for the following examples −
Show Examples
Other than the above operators, Elixir also provides a range of other operators like Concatenation Operator, Match Operator, Pin Operator, Pipe  Operator, String Match Operator, Code Point Operator, Capture Operator, Ternary Operator that make it quite a powerful language.
Show Examples

    35 Lectures 
     3 hours 

 Pranjal Srivastava

    54 Lectures 
     6 hours 

 Pranjal Srivastava, Harshit Srivastava

    80 Lectures 
     9.5 hours 

 Pranjal Srivastava

    43 Lectures 
     4 hours 

 Mohammad Nauman
 Print
 Add Notes
 Bookmark this page
How to change the legend title in ggplot2 in R?

In ggplot2, by default the legend title is the title of the grouping column of the data frame. If we want to change that title then scale_color_discrete function. For example, if we have a data frame called df that contains two numerical columns x and y and one grouping column say group then the scatterplot with a different legend title can be created by using the below command −
ggplot(df,aes(x,y,color=group))+geom_point()+scale_color_discrete("Gender")
Consider the below data frame −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> grp<-sample(c("Male","Female"),20,replace=TRUE)
> df<-data.frame(x,y,grp)
> df
             x          y    grp
1  -2.27846496  0.8121008   Male
2  -1.75112768 -0.1718679 Female
3  -0.12504696 -0.3265867 Female
4   0.10895490 -0.2015613 Female
5  -1.51196132  0.8480887   Male
6   1.68028497 -1.1329240   Male
7  -0.65238760 -0.9495177   Male
8   0.84725937  1.4825983 Female
9   0.53645228  2.1630524 Female
10 -2.04814594  0.4503883 Female
11 -0.37741279 -1.1621875   Male
12  0.79303416 -0.1804637   Male
13 -0.02095395 -0.9740427   Male
14  0.61453646  1.0327821 Female
15 -0.32875489 -0.4071753   Male
16  0.94227215  2.0651996 Female
17  1.79740910  0.8630703   Male
18  1.09133101 -0.1053076   Male
19  0.33748223 -0.1238961 Female
20 -0.10264760  1.5338488   Male
Loading ggplot2 package and creating a point chart between x and y with grouping of grp −
> library(ggplot2)
> ggplot(df,aes(x,y,color=grp))+geom_point()
Creating a point chart between x and y with grouping of grp and legend title Gender −
> ggplot(df,aes(x,y,color=grp))+geom_point()+scale_color_discrete("Gender")
How to create input Pop-Ups (Dialog) and get input from user in Java?

Use the JOptionPane.showInputDialog() to get input from user in a dialog box like “Which sports you play the most”, “What is your name”, etc. The following is an example to create input Pop-Ups (Dialog) and get input from user −
package my;
import javax.swing.JOptionPane;
public class SwingDemo {
   public static void main(String[] args) {
      String[] sports = { "Football", "Cricket", "Squash", "Baseball", "Fencing", "Volleyball", "Basketball" };
      String res = (String) JOptionPane.showInputDialog(null, "Which sports you play the most?", "Sports",
         JOptionPane.PLAIN_MESSAGE, null, sports, sports[0]);
      switch (res) {
         case "Football" −
            System.out.println("I Love Football");
         break;
         case "Cricket" −
            System.out.println("I Love Cricket");
         break;
         case "Squash" −
            System.out.println("I Love Squash");
         break;
         case "Baseball" −
            System.out.println("I Love Baseball");
         break;
         case "Fencing" −
            System.out.println("I Love Fencing");
         break;
         case "Volleyball" −
            System.out.println("I Love Volleyball");
         break;
         case "Basketball" −
            System.out.println("I Love Basketball");
         break;
      }
   }
}
Now select any of the item from above and click OK to display the selected item in the Console.
We selected “Volleyball” −
The option selected above visible in Console −
ReactJS – Component vs PureComponent

In this article, we are going to see the difference between Component and PureComponent. In ReactJS, Components are widely used to make an App more efficient and effective to use.
ReactJS provides two different ways to use components – Component or PureComponent.
It is the type of component which re-renders itself every time when the props passed to it changes or its parent component re-renders.
Our first component in the following example is App. This component is the parent of the Comp1 component. We are creating Comp1 separately and just adding it inside the JSX tree in our App component. Only the App component needs to be exported.
App.jsx
import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = { color: '#000' };
   }
   render() {
      return (
      <div>
         <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
         <button onClick={() => this.setState({ color: '#ff0000' })}>
            Change Color
         </button>
         <Comp1 />
      </div>
   );
   }
}

class Comp1 extends React.Component {
   render() {
      alert('Comp1 component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
The above code will generate the following result.
It is the type of component which re-renders only when the props passed to it changes and not even if its parent component re-renders or if the shouldComponentUpdate()method is called. It is greatly used to enhance the performance of a web application.
In the following example, we are going to use the PureComponent with Comp1 component so that it only re-renders if the props passed to it changes.
App.jsx
import React from 'react';
class App extends React.Component {
   constructor() {
      super();
      this.state = { color: '#000' };
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Tutorialspoint</h1>
            <button onClick={() => this.setState({ color: '#ff0000' })}>
               Change Color
            </button>
            <Comp1 />
         </div>
      );
   }
}

class Comp1 extends React.PureComponent {
   render() {
      alert('Comp1 component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;
The above code will generate the following result.
Default exports vs Named exports in JavaScript.

There can be only one default export per file and we can assign it any name when importing it to the other file. However, there can be multiple named exports in a file and they are imported using the name that were used to export.
Following is the code showing difference between default exports and named exports in JavaScript −
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Default export vs Named Export</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above export function as named and default export</h3>
<script src="script.js" type="module">
</script>
</body>
</html>
sample.js
export default function testImport(){
   return 'Module testImport has been imported'+'';
}
export function tellTime(){
   return new Date();
}
script.js
import defaultExport from "./sample.js";
import {tellTime} from "./sample.js";
let resultEle = document.querySelector('.result');
document.querySelector('.Btn').addEventListener('click',()=>{
   resultEle.innerHTML+=defaultExport();
   resultEle.innerHTML+=tellTime();
})
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
Constructing a nested JSON object in JavaScript

We have a special kind of string that contains characters in couple, like this −
const str = "AABBCCDDEE";
We are required to construct an object based on this string which should look like this −
const obj = {
   code: "AA",
   sub: {
      code: "BB",
      sub: {
         code: "CC",
         sub: {
            code: "DD",
            sub: {
               code: "EE",
               sub: {}
            }
         }
      }
   }
};
Notice that for each unique couple in the string we have a new sub object and the code property at any level represents a specific couple.
We can solve this problem using a recursive approach.
We will recursively iterate over the string to pick specific couple and assign a new sub object for it.
Therefore, let’s write the code for this function −
The code for this will be −
const str = "AABBCCDDEE";
const constructObject = str => {
   const res = {};
   let ref = res;
   while(str){
      const words = str.substring(0, 2);
      str = str.substr(2, str.length);
      ref.code = words;
      ref.sub = {};
      ref = ref.sub;
   };
   return res;
};
console.log(JSON.stringify(constructObject(str), undefined, 4));
The output in the console will be −
{
   "code": "AA",
   "sub": {
      "code": "BB",
      "sub": {
         "code": "CC",
         "sub": {
            "code": "DD",
            "sub": {
               "code": "EE",
               "sub": {}
            }
         }
      }
   }
}
C# DateTime to add days to the current date

Firstly, get the current date.
DateTime.Today
Now, use AddDays() method to add days to the current date. Here, we are adding 10 days to the current date.
DateTime.Today.AddDays(10)
Let us see the complete code −
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      Console.WriteLine("Today = {0}", DateTime.Today);
      Console.WriteLine("Add 10 Days = {0}", DateTime.Today.AddDays(10));
   }
}
Today = 9/11/2018 12:00:00 AM
Add 10 Days = 9/21/2018 12:00:00 AM
What is compile time polymorphism in C#?

Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
The linking of a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are Function overloading and Operator overloading.
In function overloading you can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list.
The following is an example showing how to implement function overloading in C# −
 Live Demo
using System;

namespace PolymorphismApplication {
   class Printdata {
      void print(int i) {
         Console.WriteLine("Printing int: {0}", i );
      }

      void print(double f) {
         Console.WriteLine("Printing float: {0}" , f);
      }

      void print(string s) {
         Console.WriteLine("Printing string: {0}", s);
      }

      static void Main(string[] args) {
         Printdata p = new Printdata();

         // Call print to print integer
         p.print(5);

         // Call print to print float
         p.print(500.263);

         // Call print to print string
         p.print("Hello C++");
         Console.ReadKey();
      }
   }
}
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
Checked vs Unchecked exceptions in Java


A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the programmer should take care of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to handle the exception.
Live Demo
import java.io.File;
import java.io.FileReader;

public class FilenotFound_Demo {

   public static void main(String args[]) {      
      File file = new File("E://file.txt");
      FileReader fr = new FileReader(file);    
   }
}
If you try to compile the above program, you will get the following exceptions.
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
   FileReader fr = new FileReader(file);                      
      ^
1 error
Note − Since the methods read() and close() of FileReader class throws IOException, you can observe that the compiler notifies to handle IOException, along with FileNotFoundException.
An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Live Demo
public class Unchecked_Demo {

   public static void main(String args[]) {
      int num[] = {1, 2, 3, 4};
      System.out.println(num[5]);
   }
}
If you compile and execute the above program, you will get the following exception.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
   at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Matplotlib.axes.Axes.update() in Python - GeeksforGeeks

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.update() function in axes module of matplotlib library is used to update this artist’s properties from the dictionary props.
Syntax: Axes.update(self, props)
Parameters: This method accepts the following parameters.
props: This parameter is the dictionary of the properties.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.update() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np        np.random.seed(10**7)geeks = np.random.randn(100)   fig, ax = plt.subplots()ax.acorr(geeks, usevlines = True,         normed = True,         maxlags = 80, lw = 3)  ax.grid(True)  prop = {'xticks': np.array([-10., -5.,  0.,   5., 10. ]),        'yticks': np.array([-0.2,  0.2,  0.6,  1.,  1.4]),        'ylabel': None, 'xlabel': None}  ax.update(prop)   fig.suptitle('matplotlib.axes.Axes.update()\ function Example', fontweight ="bold")   plt.show() 
Output:
Example 2:
# Implementation of matplotlib function import numpy as np import matplotlib.pyplot as plt     xx = np.random.rand(16, 30)      fig, ax = plt.subplots()      m = ax.pcolor(xx) m.set_zorder(-20)prop = {'autoscalex_on': False}w = ax.update(prop)   fig.suptitle('matplotlib.axes.Axes.update()\function Example', fontweight ="bold")   plt.show() 
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
Reading and Writing to text files in Python
How to show legend elements horizontally in Matplotlib?

To show legend elements horizontally, we can take the following steps
Set the figure size and adjust the padding between and around the subplots.
Using plot() method, plot lines with the labels line1, line2 and line3.
Place a legend on the figure using legend() method, with number of labels for ncol value in the argument.
To display the figure, use show() method.
from matplotlib import pyplot as plt

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

line1, = plt.plot([1, 2, 3], label="line1")
line2, = plt.plot([3, 2, 1], label="line2")
line3, = plt.plot([2, 3, 1], label="line3")
plt.legend(ncol=3, loc="upper right")
plt.show()
Find the highest 3 values in a dictionary in Python program

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a dictionary, and we need to print the 3 highest value in a dictionary.
There are two approaches as discussed below
 Live Demo
# collections module
from collections import Counter
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}
k = Counter(my_dict)
# 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for i in high:
   print(i[0]," : ",i[1]," ")
Dictionary with 3 highest values:
Keys : Values
S : 99
R : 32
U : 22
Here the mostcommon() method returns a list of the n most common elements and their counts from the most common to the least.
 Live Demo
# nlargest module
from heapq import nlargest
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for val in ThreeHighest:
   print(val, " : ", my_dict.get(val))
Dictionary with 3 highest values:
Keys : Values
S    : 99
R    : 32
U    : 22
Here we used the n largest element that takes up three arguments, one is the no of elements to be selected and the other two arguments i.e. dictionary and its keys.
In this article, we have learned how we can find the highest 3 values in a dictionary
md5sum - Unix, Linux Command

md5sum - compute and check MD5 message digest.
 md5sum [OPTION]... [FILE]... 

 md5sum [OPTION]... [FILE]... 
md5sum  produces for each input  file  a  128-bit  "finger-print" or "message-digest" or it can check with the output of a former run whether the message digests are still the same (i.e. whether the files changed).
Example-1:
To Calculate / Compute md5sum :
$ md5sum file.txt
output:
3b85ec9ab2984b91070128be6aae25eb  file.txt

Example-2:
Calculate or compute md5sum for the input given through STDIN:
$ md5sum -
test
output:
d8e8fca2dc0f896fd7cb4cb0031ba249  -

Example-3:
Compute and Verify checksum of files :
$ md5sum *.txt
output:bbd166fee3f3f624286c4d85dc1994f8  abc.txt
50dcf8c353827eef464cb79f55018d6c  xyz.txt

$ md5sum *.txt > txtmd5sum.md5

$ md5sum -c txtmd5sum.md5 
abc.txt: OK
xyz.txt: OK

If there is a change in any of the file, you will get the
 “computed checksums did NOT match” warning message.
i.e:
md5sum: WARNING: 1 of 3 computed checksums did NOT match

Example-4:
To read in binary mode(md5sum -b file_path):
$ md5sum 1.txt
output:
764efa883dda1e11db47671c4a3bbd9e  1.txt

$ md5sum -b 1.txt 
764efa883dda1e11db47671c4a3bbd9e *1.txt

$ md5sum --binary 1.txt 
764efa883dda1e11db47671c4a3bbd9e *1.txt

“-b” option is equivalent to “–binary” option.

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to use PowerShell break statement in foreach loop?

You can use the PowerShell Break statement with the foreach loop as mentioned below.
foreach($obj in (Get-ChildItem D:\Temp)){
   Write-Output $obj
   if($obj.Name -eq "cars.xml"){Break}
}
Directory: D:\Temp
Mode       LastWriteTime       Length Name
----       -------------       ------ ----
d-----     13-12-2019                 09:52GPO_backup
d-----     24-11-2018 11:31           LGPO
-a----     27-01-2020 22:21     13962 Alias1
-a----     26-01-2020 19:20     13818 aliases.txt
-a----     07-05-2018 23:00301  cars.xml
In the above example, when the file name matches the cars.xml then the loop gets terminated.
Google Maps - Zoom

You can increase or decrease the zoom value of a map by modifying the value of the zoom attribute in the the map options.
We can increase or decrease the zoom value of the map using the zoom option. Given below is the syntax to change the zoom value of the current map.
var mapOptions = {
   zoom:required zoom value
};
The following code will display the roadmap of the city Vishakhapatnam with a zoom value of 6.
<!DOCTYPE html>
<html>
   
   <head>
      <script src = "https://maps.googleapis.com/maps/api/js"></script>
      
      <script>
         function loadMap() {
			
            var mapOptions = {
               center:new google.maps.LatLng(17.609993, 83.221436),
               zoom:6,
               mapTypeId:google.maps.MapTypeId.ROADMAP
            };
            
            var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
         }
      </script>
      
   </head>
   
   <body onload = "loadMap()">
      <div id = "sample" style = "width:587px; height:400px;"></div>
   </body>
   
</html>
It will produce the following output −
The following code will display the roadmap of the city Vishakhapatnam with a zoom value of 10.
<!DOCTYPE html>
<html>
   
   <head>
      <script src = "https://maps.googleapis.com/maps/api/js"></script>
      
      <script>
         function loadMap() {
			
            var mapOptions = {
               center:new google.maps.LatLng(17.609993, 83.221436),
               zoom:10,
               mapTypeId:google.maps.MapTypeId.ROADMAP
            };
				
            var map = new google.maps.Map(document.getElementById("sample"),mapOptions);
         }
      </script>
      
   </head>
   
   <body onload = "loadMap()">
      <div id = "sample" style = "width:587px; height:400px;"></div>
   </body>
   
</html>
It will produce the following output −

    20 Lectures 
     2.5 hours 

 Asif Hussain

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    33 Lectures 
     2.5 hours 

 Sasha Miller

    22 Lectures 
     1.5 hours 

 Zach Miller

    16 Lectures 
     1.5 hours 

 Sasha Miller

    23 Lectures 
     2.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Animate Data Using Python. View Live Data With Just MatPlotLib | by Bruce Ironhardt | Towards Data Science

The goal of this guide is to show you how to update a graph in real-time. This can be used for a variety of applications like visualizing live data from sensors or tracking stock prices.
In this tutorial, the data will be static but can easily be used on live data. You’ll, of course, need to have MatPlotlib and Pandas installed on your local machine or virtual environment.
‘FuncAnimation’ is the method that we’ll be using to update the graph continuously giving it that live effect.
We will be using MatPlotLib in this tutorial to generate our graphs and the panda's library to read CSV files.
We’re going to create a subplot to make it easier for us to draw on the same plot over and over again.
The animation(i) method is what we’ll use to draw our line over and over again. This method will be called by the FuncAnimation method from the MatPlotLib library over and over again until you decide to terminate the program.
In this example, I’ll be using a static file pulled off the internet. This file gives us the 2014 stock price for Apple.
Here’s how our dummy data will look:
Now to mimick live data instead of plotting the whole graph in one go, what I’ll instead do is plot each row. This gives us the illusionary live data.
Remember that the animation(i) function will be called every iteration. Each time its called i goes up by one. This line, AAPL_STOCK[0:i]['AAPL_x'] , will return the rows corresponding to the iteration we’re on.
For example, on iteration 1 we will return the just the first row in the dataset. On the nth iteration, we will return the nth row (and all rows before it) in the dataset.
To draw the line to the graph, we just need to call ax.plot(x,y). We also call ax.clear() to clear the line generated before. We do this to not draw lines over each other after each iteration.
You may have noticed that we read the CSV in our loop. The reason we need to do this is that if new data was added to the CSV we could read it and draw it to our graph.
If you were using a text file instead, you could append values to x and y at each iteration. For example:
To run the animation we just need to use the following.
animation = FuncAnimation(fig, func=animation, interval=1000)plt.show()
Here, the `FuncAnimation` will continuously run our animation program. interval is used to determine the delay between updates. Currently, its set to 1000 milliseconds but it can be as fast or as slow as you need it to be.
Here’s all the code:
So, here I just removed some data from the CSV we were working with above.
Then once the graph updated to the end of the dataset I copied in some new data and saved the file. The graph then updated with all the new data that I just added. In this case, it updated pretty quickly but only cause the interval time was set to 100ms.
If you liked this guide you can check out some other cool articles if written below! If you have any questions feel free to leave a comment and I can try and help you out.
Angular Material mat-tab-group - GeeksforGeeks

16 Feb, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. mat-tab-group is used mainly for navbar requirements when we have multiple tabs to display.
Installation:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatTabsModule’ from ‘@angular/material/tabs’ in the app.module.ts file.
Then use the <mat-tab-group> tag to group all the items inside this group tag.
Inside the <mat-tab-group> tag we need to use <mat-tab> tag for every item.
We can also style the tabs basing upon the position like start, center, and end. For this, we need to use a property called mat-align-tabs.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Example:
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { MatTabsModule } from '@angular/material/tabs';       import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations';    @NgModule({   imports:   [ BrowserModule,     FormsModule,     MatTabsModule,    BrowserAnimationsModule],   declarations: [ AppComponent ],   bootstrap: [ AppComponent ] })   export class AppModule { }
app.component.html
<p>   Implementation of mat-tab-group for    center style and for default theme</p>  <mat-tab-group mat-align-tabs="center">  <mat-tab label="Home">Home Content</mat-tab>  <mat-tab label="Overview">Overview Content</mat-tab></mat-tab-group><br>    <p>  Implementation of mat-tab-group for center   style and for primary theme</p>  <mat-tab-group mat-align-tabs="center" backgroundColor="primary">  <mat-tab label="Home">Home Content</mat-tab>  <mat-tab label="Overview">Overview Content</mat-tab></mat-tab-group><br>    <p>  Implementation of mat-tab-group for center   style and for accent theme</p>  <mat-tab-group mat-align-tabs="center" backgroundColor="accent">  <mat-tab label="Home">Home Content</mat-tab>  <mat-tab label="Overview">Overview Content</mat-tab></mat-tab-group>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
How to create module with Routing in Angular 9 ?
How to setup 404 page in angular routing ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
C++ For Loop

When you know exactly how many times you want to loop through a block of 
code, use the for loop instead of a while loop:
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4:
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 
5). If the condition is true, the loop will start over again, if it is false, 
the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has 
been executed.
This example will only print even values between 0 and 10:
Use a for loop to print "Yes" 5 times:
 (int i = 0; i < 5; ) {
  cout <<  << "\n";
}

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Extract punctuation from the specified column of Dataframe using Regex - GeeksforGeeks

29 Dec, 2020
Prerequisite: Regular Expression in Python
In this article, we will see how to extract punctuation used in the specified column of the Dataframe using Regex.
Firstly, we are making regular expression that contains all the punctuation: [!”\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]* Then we are passing each row of specific column to re.findall() function for extracting the punctuation and then assigning that extracted punctuation to a new column in a Dataframe.
re.findall() function is used to extract all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.
Syntax: re.findall(regex, string) 
Return: All non-overlapping matches of pattern in string, as a list of strings.
Now, Let’s create a Dataframe:
Python3
# import required librariesimport pandas as pdimport re  # creating Dataframe with# name and their commentsdf = pd.DataFrame({    'Name' : ['Akash', 'Ashish', 'Ayush',              'Diksha' , 'Radhika'],        'Comments': ['Hey! Akash how r u' ,                  'Why are you asking this to me?' ,                 'Today, what we are going to do.' ,                 'No plans for today why?' ,                 'Wedding plans, what are you saying?']},        columns = ['Name', 'Comments']    )  # show the Dataframedf
Output:
Now, Extracting the punctuation from the column comment:
Python3
# define a function for extracting# the punctuationsdef check_find_punctuations(text):        # regular expression containing    # all punctuation    result = re.findall(r'[!"\$%&\'()*+,\-.\/:;=#@?\[\\\]^_`{|}~]*',                         text)          # form a string    string = "".join(result)          # list of strings return    return list(string)    # creating new column name# as a punctuation_used and # applying user defined function# on each rows of Comments columndf['punctuation_used'] = df['Comments'].apply(                         lambda x : check_find_punctuations(x)                         )  # show the Dataframedf
Output:
Python pandas-dataFrame
Python Pandas-exercise
Python Regex-programs
Python-pandas
python-regex
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 use JavaScript to load a webpage after 5 seconds?

Use the setTimeout() function in JavaScript to load a webpage after some interval. This function waits for some seconds and then loads the web page.
You can try to run the following code to learn how to load a webpage after 5 seconds −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <script>
         setTimeout(myURL, 5000);
         function myURL(){
            window.open('http://qries.com');
         }
      </script>
      <p>Web page loads after 5 seconds.</p>
   </body>
</html>
How to Block or Disable Normal User Logins in Linux? - GeeksforGeeks

22 Mar, 2021
Here we will see how to block or disable normal user logins in Linux. This is a good idea to prevent Normal users from connecting to your system. We will see how to block Normal user logins using /etc/nologin file. We are going to tell the users that what is actually happening by showing them a message.
The main function of /etc/nologin file is to show a message to the users which are attempting to log on to a system during the process of the shutdown.
Once the message is shown to the user the login procedure terminates which stops the user from logging onto the system and apart from this you can also add your own message which you want to display, you can open the file in vi, nano text editor, and type it.
The /etc/nologin file can be created manually as shown below which is used to block the users’ login:
sudo touch /etc/nologin
And the below message will be shown to the user who is attempting to log on to the system.
echo "System down for maintenance, try again later" | sudo tee /etc/nologin
Now you can see from the screenshot below that a Normal user is not able to login.
To allow logins again you have to delete the /etc/nologin file.
The below command will help you in deleting /etc/nologin file.
sudo rm /etc/nologin
You can use the nologin shell to block some specific users. The nologin shell is located in /usr/sbin/nologin
This command will help you in finding the location of nologin shell:
$ which nologin
/usr/sbin/nologin
Now to set the user’s shell to nologin you can use the usermod command, Here we are going to set “priyanshu” users shell to nologin.
usermod -s /usr/sbin/nologin priyanshu
Now to re-enable some specific users to login again simply set their shell back to bash.
To set the “priyanshu” users shell back to bash use the below command:
usermod -s /bin/bash priyanshu
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
TCP Server-Client implementation in C
AWK command in Unix/Linux with examples
cp command in Linux with examples
How to ensure that child class overrides a super class method in java?

A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.
public abstract myMethod();
To use an abstract method, you need to inherit it by extending its class and provide implementation (body) to it. If a class contains at least one abstract method, you must declare it abstract.
In other words, if you extend an abstract class it is mandatory to implement (override) all the abstract methods in it or, declare it abstract else a compile time error will be generated for each abstract method (that you don’t override) saying “subclass_name is not abstract and does not override abstract method abstractmethod_name in classname”.
Following Java example contains two abstract classes: One is an abstract class (MyClass) that contains 3 abstract methods and the other is a class with name AbstractClassExample that extends the earlier one.
In the subclass we are overriding only one abstract method (display()).
import java.io.IOException;
abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("subclass implementation of the display method ");
   }
   public static void main(String args[]) {
      new AbstractClassExample().display();
   }
}
On compiling, the above method generates the following compile time error.
AbstractClassExample.java:9: error: AbstractClassExample is not abstract and does not override abstract method setAge(int) in MyClass
public class AbstractClassExample extends MyClass{
^
1 error
Therefore, if you need to make sure that the sub class overrides a particular method of the super class method, you just need to declare the required method abstract.
To make the above program work you need to implement all the abstract methods as −
abstract class MyClass {
   public abstract void display();
   public abstract void setName(String name);
   public abstract void setAge(int age);
}
public class AbstractClassExample extends MyClass{
   public void display(){
      System.out.println("subclass implementation of the display method ");
   }
   public void setName(String name){
      System.out.println("Name: "+name);
   }
   public void setAge(int age){
      System.out.println("Age: "+age);
   }
   public static void main(String args[]) {
      AbstractClassExample obj = new AbstractClassExample();
      obj.display();
      obj.setName("Krishna");
      obj.setAge(20);
   }
}
subclass implementation of the display method
Name: Krishna
Age: 20
GATE | GATE-CS-2004 | Question 49 - GeeksforGeeks

14 Feb, 2018
A Unix-style i-node has 10 direct pointers and one single, one double and one triple indirect pointers. Disk block size is 1 Kbyte, disk block address is 32 bits, and 48-bit integers are used. What is the maximum possible file size ?(A) 224 bytes(B) 232 bytes(C) 234 bytes(D) 248 bytesAnswer: (C)Explanation: Image Source: Wiki
Size of Disk Block = 1Kbyte

Disk Blocks address = 32bits, 
but 48 bit integers are used for address
Therefore address size = 6 bytes
                    

No of addresses per block = 1024/6  = 170.66 
Therefore 170 ≈ 2^8 addresses per block can be stored

Maximum File Size = 10 Direct + 1 Single Indirect + 
                    1 Double Indirect + 1 Triple Indirect
                 = 10 + 28 + 28*28 + 28*28*28
                 ≈ 224 Blocks

Since each block is of size 210                 

Maximum files size = 224 * 210     
                   = 234    
Quiz of this Question
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2011 | Question 65
if/else condition in CSS

30 Jun, 2022
Given an HTML file and we need to apply using if-else conditions in CSS.No, We can not use if-else conditions in CSS as CSS doesn’t support logics. But we can use some alternatives to if-else which are discussed below:Method 1: In this method, we will use classes in HTML file to achieve this. We will define different class names according to the conditions which we want to apply in CSS.
Suppose we want to change the color of text according to the line number then the if-else condition will be:
if(line1){
   color : red;
}else{
   color : green;
}
By using the above-discussed method, we will create classes and then apply CSS in it:
.color-line1{
   color : red;
}
.color-line2{
   color : green;
}
So, the above classes will execute only for HTML tags in which these classes are used.Example:
html
<html>   <head>     <title>         If-else condition in CSS    </title>           <!-- Applying CSS -->    <style>        /* First line CSS */        .color-line1{            color : red;        }                  /* Second line CSS */        .color-line2{            color: green;        }    </style></head>   <body style="text-align:center;">       <h1 style="color:green;">         GeeksforGeeks     </h1>       <h3>         If-else condition in CSS    </h3>    <span class="color-line1">This is first line</span>    <br><br>    <span class="color-line2">This is second line</span>  </body>   </html>                                      
Output:
Method 2: We can use CSS preprocessors like SASS which allows us to write condition statements in it. Even if you use SASS you have to pre-process your stylesheets which means that the condition are evaluated at compile time, not at run time.Syntax:
$type: line;
p {
  @if $type == line1 {
    color: blue;
  } @else if $type == line2 {
    color: red;
  } @else if $type == line3 {
    color: green;
  } @else {
    color: black;
  }
}
To know more about SASS click hereTo read about if-else in SASS click hereSupported Browsers:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
ysachin2314
CSS-Misc
Picked
SASS
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Ways to join pair of elements in list

25 Jun, 2019
Given a list, the task is to join a pair of elements of the list. Given below are a few methods to solve the given task.
Method #1: Using zip() method
# Python code to demonstrate # how to join pair of elements of list  # Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f']  # Printing initial list print ("Initial list", str(ini_list))  # Pairing the elements of listsres = [i + j for i, j in zip(ini_list[::2], ini_list[1::2])]  # Printing final resultprint ("Result", str(res))
Initial list ['a', 'b', 'c', 'd', 'e', 'f']
Result ['ab', 'cd', 'ef']

 Method #2: Using list comprehension and next and iters
# Python code to demonstrate # how to join pair of elements of list  # Initialising listini_list = iter(['a', 'b', 'c', 'd', 'e', 'f'])  # Pairing the elements of listsres = [h + next(ini_list, '') for h in ini_list]  # Printing final resultprint ("Result", str(res))
Result ['ab', 'cd', 'ef']

 Method #3: Using list comprehension
# Python code to demonstrate # how to join pair of elements of list  # Initialising listini_list = ['a', 'b', 'c', 'd', 'e', 'f']  # Printing initial listsprint ("Initial list", str(ini_list))  # Pairing the elements of listsres = [ini_list[i] + ini_list[i + 1]        for i in range(0, len(ini_list), 2)]  # Printing final resultprint ("Result", str(res))
Initial list ['a', 'b', 'c', 'd', 'e', 'f']
Result ['ab', 'cd', 'ef']

Python list-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary