code-rag-bench/online-tutorials huggingface dataset:
Matplotlib.axes.Axes.format_ydata() in Python

19 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.format_ydata() function in axes module of matplotlib library is used to return y formatted as an y-value.
Syntax:
Axes.format_ydata(self, y)

Below examples illustrate the matplotlib.axes.Axes.format_ydata() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook   years = mdates.YearLocator()   months = mdates.MonthLocator()  years_fmt = mdates.DateFormatter('% Y')   with cbook.get_sample_data('goog.npz') as datafile:    data = np.load(datafile)['price_data'].view(np.recarray)       fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data[:300], color ="green")   ax.xaxis.set_major_locator(years) ax.format_ydata = lambda x: '$% 1.2f' % xax.grid(True)  fig.autofmt_xdate()fig.suptitle('matplotlib.axes.Axes.format_ydata() function\ Example', fontweight ="bold")plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook   years = mdates.YearLocator()   months = mdates.MonthLocator()  years_fmt = mdates.DateFormatter('% Y')   with cbook.get_sample_data('goog.npz') as datafile:    data = np.load(datafile)['price_data']   fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data, color ="k")   ax.yaxis.set_major_locator(years)ax.yaxis.set_major_formatter(years_fmt)ax.yaxis.set_minor_locator(months)   ax.format_ydata = mdates.DateFormatter('% Y')ax.grid(True)  fig.suptitle('matplotlib.axes.Axes.format_ydata() function\ Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Build a Simple Web Server with Golang?

10 Oct, 2021
Golang is a procedural programming language ideal to build simple, reliable, and efficient software. 
Create a project folder with a .go file inside eg. server.go. 
Directory structure:
The server.go file:
Go
package main import (    "fmt"    "log"    "net/http") func main() {     // API routes    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintf(w, "Hello world from GfG")    })    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintf(w, "Hi")    })     port := ":5000"    fmt.Println("Server is running on port" + port)     // Start server on port specified above    log.Fatal(http.ListenAndServe(port, nil))}
Run the server using the following command (make sure you’re in the project directory):
go run server.go
Note:  You have to stop the server with Ctrl + C and restart via the same command whenever the server.go file is changed.  
Console:
Open the desired web browser and any of these URLs to verify if the server is running:
http://localhost:5000/ or http://localhost:5000/hi
Output:
Create a static folder with all the static files.Example directory structure:
The GfG logo
The index.html file
HTML
<html>  <head>    <title>Home</title>  </head>  <body>    <h2>Home page</h2>  </body></html>
  
The about.html file
 
HTML
<html>  <head>    <title>About</title>  </head>  <body>    <h2>about page!</h2>  </body></html>
Now Edit the server.go file:
Go
package main import (    "fmt"    "log"    "net/http") func main() {     // API routes     // Serve files from static folder    http.Handle("/", http.FileServer(http.Dir("./static")))     // Serve api /hi    http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintf(w, "Hi")    })     port := ":5000"    fmt.Println("Server is running on port" + port)     // Start server on port specified above    log.Fatal(http.ListenAndServe(port, nil)) }
Verifying if static files are served:
aniruddhashriwant
Go Language
How To
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Time Durations in Golang
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
Java Tutorial
How to filter object array based on attributes?
Python Modules of Cryptography

In this chapter, you will learn in detail about various modules of cryptography in Python.
It includes all the recipes and primitives, and provides a high level interface of coding in Python. You can install cryptography module using the following command −
pip install cryptography

You can use the following code to implement the cryptography module −
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt("This example is used to demonstrate cryptography module")
plain_text = cipher_suite.decrypt(cipher_text)
The code given above produces the following output −
The code given here is used to verify the password and creating its hash. It also includes logic for verifying the password for authentication purpose.
import uuid
import hashlib

def hash_password(password):
   # uuid is used to generate a random number of the specified password
   salt = uuid.uuid4().hex
   return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt

def check_password(hashed_password, user_password):
   password, salt = hashed_password.split(':')
   return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()

new_pass = input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = input('Now please enter the password again to check: ')

if check_password(hashed_password, old_pass):
   print('You entered the right password')
else:
   print('Passwords do not match')
Scenario 1 − If you have entered a correct password, you can find the following output −
Scenario 2 − If we enter wrong password, you can find the following output −
Hashlib package is used for storing passwords in a database. In this program, salt is used which adds a random sequence to the password string before implementing the hash function.

    10 Lectures 
     2 hours 

 Total Seminars

    10 Lectures 
     2 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Forcing Tkinter window to stay on top of fullscreen in Windows 10?

To render widgets in a Tkinter application, we generally use mainloop() function which helps to display the widgets in a window. In many cases, tkinter window displays over the other windows or programs. While switching to other programs or windows, it seems difficult to find and switch back to the Tkinter window again.
We can force our tkinter window to stay on Top of other window or programs by creating a function and defining win.lift() method in a loop. In the loop, it will execute win.after(2000, function()) function to ensure that the tkinter window will always stays on top of other windows.
# Import the required libraries
from tkinter import *
import lorem

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

def stay_on_top():
   win.lift()
   win.after(2000, stay_on_top)

# Add a Label widget
Label(win, text="This window will always stay on Top", font=('Aerial 14')).pack(pady=30, anchor =CENTER)

# Call function to make the window stay on top
stay_on_top()

win.mainloop()
Running the above code will display a window that will automatically remain on top of all other windows.
Lua - break Statement

When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in Lua is as follows −
break

--[ local variable definition --]
a = 10

--[ while loop execution --]
while( a < 20 )
do
   print("value of a:", a)
   a=a+1
	
   if( a > 15)
   then
      --[ terminate the loop using break statement --]
      break
   end
	
end
When you build and run the above code, it produces the following result.
value of a:	10
value of a:	11
value of a:	12
value of a:	13
value of a:	14
value of a:	15


    12 Lectures 
     2 hours 

 Manish Gupta

    80 Lectures 
     3 hours 

 Sanjeev Mittal

    54 Lectures 
     3.5 hours 

 Mehmet GOKTEPE
 Print
 Add Notes
 Bookmark this page
Writing Scrapy Python Output to JSON file - GeeksforGeeks

14 Sep, 2021
In this article, we are going to see how to write scrapy output into a JSON file in Python.
This is the easiest way to save data to JSON is by using the following command:
scrapy crawl <spiderName> -O <fileName>.json
This will generate a file with a provided file name containing all scraped data.
Note that using -O in the command line overwrites any existing file with that name whereas using -o appends the new content to the existing file. However, appending to a JSON file makes the file contents invalid JSON. So use the following command to append data to an existing file.
scrapy crawl <spiderName> -o <fileName>.jl
Note: .jl represents JSON lines format.
Step 1: Creating the project
Now to start a new project in scrapy use the following command
scrapy startproject tutorial
This will create a directory with the following content:
Move to the tutorial directory we created using the following command:
cd tutorial
Step 2: Creating a spider (tutorial/spiders/quotes_spider.py)
Spiders are the programs that user defines and scrapy uses to scrape information from website(s). This is the code for our Spider. Create a file named quotes_spider.py under the tutorial/spiders directory in your project:
Python3
import scrapy    class QuotesSpider(scrapy.Spider):        # name of variable should be 'name' only    name = "quotes"       # urls from which will be used to extract information    # list should be named 'start_urls' only    start_urls = [        'http://quotes.toscrape.com/page/1/',        'http://quotes.toscrape.com/page/2/',    ]      def parse(self, response):                # handle the response downloaded for each of the        # requests made should be named 'parse' only        for quote in response.css('div.quote'):            yield {                'text': quote.css('span.text::text').get(),                'author': quote.css('small.author::text').get(),                'tags': quote.css('div.tags a.tag::text').getall(),            }
This is a simple spider to get the quotes, author names, and tags from the website.
Step 5: Running the program
To run the program and save scrawled data to JSON using:
scrapy crawl quotes -O quotes.json
We can see that a file quotes.json has been created in our project structure, this file contains all the scraped data.
JSON Output:
These are just a few of many quotes of quotes.json file scraped by our spider.
Picked
Python-Scrapy
Python
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?
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python Classes and Objects
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Loop through a Set using Javascript

In the set that we implemented, we can create a for each function in our class and accept a callback that we can call on every element. Let's see how we can implement such a function − 
forEach(callback) {
   for (let prop in this.container) {
      callback(prop);
   }
}
You can test this using − 
const testSet = new MySet();

testSet.add(1);
testSet.add(2);
testSet.add(5);

testSet.forEach(elem => console.log(`Element is ${elem}`));
This will give the output −
Element is 1
Element is 2
Element is 5
The ES6 Set API also provides the same functionality using the forEach method.
Procol Interview Experience

16 Sep, 2020
Procol visited our campus(virtually) in September for the campus hiring(SDE intern + FTE class of 2021). 
Round 1 Talent Decrypt online test: Total duration of 90 mins.
The test consists of 2 sections:21 MCQ’s and 3 coding questions. MCQ’s were based on concepts of networking, operating systems, MySQL and oops.
Coding questions 1
Minimum changes required to make all Array elements Prime.
https://www.geeksforgeeks.org/minimum-changes-required-to-make-all-array-elements-prime/
Coding question 2
Basic String-based question
Coding question 3
https://codeforces.com/blog/entry/67665
I was able to do 1 and 2 question completely and 3rd question partially (out of 3 test cases I got 2 passed).
Out of 230 students, 23 were shortlisted.
Round 2:(Technical Interview 1 Around 60 mins)
Discussion about my projects and Internships.
Ds Algo Questions
1. Find the square root of number up to given precision using binary search.
https://www.geeksforgeeks.org/find-square-root-number-upto-given-precision-using-binary-search/
2. Find the index of first 1 in an infinite sorted array of 0s and 1s
https://www.geeksforgeeks.org/find-index-first-1-infinite-sorted-array-0s-1s/?ref=rp
3. Object-based question
I was able to do 1st and 3rd in the most optimized way and 2nd partially.
Database questions
1. What is normalization?
2. Explain any of the normal forms. (I explained first normal form)
3 What is 2nd normal form?
Some basic Networking and Operating system questions
Out of 23 students, 10 got shortlisted to next round.
Round 3:
It was a mix of both technical and HR round on google meet.
Discussion about company, role and why are you suitable for this role?  
2 coding questions were asked. [I was able to solve them completely using Hashing].
Out of 10 students, 5 got an offer from Procol.
 [Important point: Always read the job description carefully and do some research about the company. It will surely help you in your interviews]
Marketing
Procol
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Amazon Interview Experience for SDE 1
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience SDE-2 (3 Years Experienced)
Write It Up: Share Your Interview Experiences
TCS Ninja Interview Experience (2020 batch)
Amazon Interview Experience for SDE-1
Nagarro Interview Experience | On-Campus 2021
Nagarro Interview Experience
Samsung RnD Coding Round Questions
Draw Line Segments between Particular Points in R Programming – segments() Function

19 Jun, 2020
segment() function in R Language is used to draw a line segment between to particular points.
Syntax: segments(x0, y0, x1, y1)
Parameters:x, y: coordinates to draw a line segment between provided points.
Returns: a line segment between given points
Example 1: To draw a single line segment
# Create empty example plotplot(0, 0, col = "white", xlab = "", ylab = "")  # Draw one linesegments(x0 = - 1, y0 = - 0.5, x1 = 0.5, y1 = 0, col = "darkgreen") 
Output:
Here, x0 & y0 are starting points of the line segment and x1 & y1 are ending points of line segment .
Example 2: Modifying  color, thickness & line type
# Create empty example plotplot(0, 0, col = "white", xlab = "", ylab = "")  # Draw one line as in Example 1segments(x0 = - 1, y0 = - 1, x1 = 0.5, y1 = 0.5,                    # Color of line         col = "darkgreen",                          # Thickness of line         lwd = 5,                                    # Line type         lty = "dotted")                     
Output:
Example 3: Draw multiple line segments to R Plot.
# Create empty example plotplot(0, 0, col = "white", xlab = "", ylab = "")         # Create data frame with line-valuesmultiple_segments <- data.frame(x0 = c(0.1, 0.2, - 0.7, 0.4, - 0.8),                          y0 = c(0.8, 0.3, 0.5, - 0.4, 0.3),                       x1 = c(0, 0.4, 0.5, - 0.5, - 0.7),                       y1 = c(- 0.3, 0.4, - 0.5, - 0.7, 0.8))                          # Draw multiple lines                        segments(x0 = multiple_segments$x0,                            y0 = multiple_segments$y0,         x1 = multiple_segments$x1,         y1 = multiple_segments$y1)
Output:
R-Graphs
R-plots
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Joining of Dataframes in R Programming
Control Statements in R Programming
How to import an Excel File into R ?
How to change Colors in ggplot2 Line Plot in R ?
Normal Distribution in R
How to check whether a form or a control is untouched or not in Angular 10 ?

24 May, 2021
In this article, we are going to check whether a form is untouched or not in Angular 10. untouched property is used to report that the control or the form is valid or not.
Syntax:
form.untouched
Return Value:
boolean: the boolean value to check whether a form is untouched or not.
NgModule: Module used by the untouched property is:
FormsModule
Approach: 
Create the Angular app to be used.
In app.component.html make a form using ngForm directive.
In app.component.ts get the information using untouched property.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators }     from '@angular/forms'  @Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css']})export class AppComponent {  form = new FormGroup({    name: new FormControl(            ),    rollno: new FormControl() });  get name(): any {  return this.form.get('name');}  onSubmit(): void {  console.log("Form is untouched : ",this.form.untouched);}}
app.component.html
<br><form [formGroup]="form" (ngSubmit)="onSubmit()">    <input formControlName="name" placeholder="Name">  <br>  <button type='submit'>Submit</button>  <br>  <br></form>
Output:
Reference: https://angular.io/api/forms/AbstractControlDirective#untouched
Angular10
AngularJS-Basics
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Structure of Input-Output Interface

07 Aug, 2020
The block diagram of an Input-Output Interface unit contain the following blocks :
1. Data Bus Buffer
2. Read/Write Control Logic
3. Port A, Port B register
4. Control and Status register 
These are explained as following below.
Data Bus Buffer :The bus buffer use bi-directional data bus to communicate with CPU. All control word data and status information between interface unit and CPU are transferred through data bus.
Port A and Port B :Port A and Port B are used to transfer data between Input-Output device and Interface Unit. Each port consist of bi-directional data input buffer and bi-directional data output buffer. Interface unit connect directly with an input device and output disk or with device that require both input and output through Port A and Port B i.e. modem, external hard-drive, magnetic disk.
Control and Status Register :CPU gives control information to control register on basis of control information. Interface unit control input and output operation between CPU and input-output device. Bits which are present in status register are used for checking of status conditions. Status register indicate status of data register, port A, port B and also record error that may be occur during transfer of data.
Read/Write Control Logic :This block generates necessary control signals for overall device operations. All commands from CPU are accepted through this block. It also allow status of interface unit to be transferred onto data bus through this block accept CS, read and write control signal from system bus and S0 , S1 from system address bus. Read and Write signal are used to define direction of data transfer over data bus.
Read Operation: CPU <---- I/O device
Write Operation: CPU ----> I/O device

The read signal direct data transfer from interface unit to CPU and write signal direct data transfer from CPU to interface unit through data bus.
Address bus is used to select to interface unit. Two least significant lines of address bus ( A0 , A1 ) are connected to select lines S0, S1. This two select input lines are used to select any one of four registers in interface unit. The selection of interface unit is according to the following criteria :
Read state :
Selection of 
Interface unit
Write State :
Example :
If S0, S1 = 0 1, then Port B data register is selected for data transfer between CPU and I/O device.
If S0, S1 = 1 0, then Control register is selected and store the control information send by the CPU.
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Control Characters
I2C Communication Protocol
Pin diagram of 8085 microprocessor
Difference between SRAM and DRAM
Computer Organization | Different Instruction Cycles
Computer Architecture | Flynn's taxonomy
Difference between RISC and CISC processor | Set 2
Python PIL | Image.new() method

30 Jun, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names. If the color argument is omitted, the image is filled with zero (this usually corresponds to black). If the color is None, the image is not initialized. This can be useful if you’re going to paste or draw things in the image. 
Syntax: PIL.Image.new(mode, size) PIL.Image.new(mode, size, color)Parameters: mode: The mode to use for the new image. (It could be RGB, RGBA) size: A 2-tuple containing (width, height) in pixels. color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes.Return Value: An Image object.  
Code #1:  
Python3
# Imports PIL moduleimport PIL # creating a image object (new image object) with# RGB mode and size 200x200im = PIL.Image.new(mode="RGB", size=(200, 200)) # This method will show image in any image viewerim.show()
Output:  
  Code #2:  
Python3
# imports Pil moduleimport PIL # creating image object which is of specific colorim = PIL.Image.new(mode = "RGB", size = (200, 200),                           color = (153, 153, 255)) # this will show image in any image viewerim.show()
Output:  
One can alter the value of color tuple to get different colors or we can simply use color name (for single band images). 
bambolambo0
Image-Processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
Typeof() vs GetType() in C#

The type takes the Type and returns the Type of the argument.
For example: System.Byte for the following −
typeof(byte)
The following is an example −
 Live Demo
using System;
class Program {
   static void Main() {
      Console.WriteLine(typeof(int));
      Console.WriteLine(typeof(byte));
   }
}
System.Int32
System.Byte
The GetType() method of array class in C# gets the Type of the current instance.
To get the type.
Type tp = value.GetType();
In the below example, we are checking the int value using the type.
if (tp.Equals(typeof(int)))
Console.WriteLine("{0} is an integer data type.", value)
The following is the usage of GetType() method in C#.
 Live Demo
using System;

class Program {
   public static void Main() {
      object[] values = { (int) 100, (long) 17111};
      foreach (var value in values) {

         Type tp = value.GetType();

         if (tp.Equals(typeof(int)))
         Console.WriteLine("{0} is an integer data type.", value);

         else
         Console.WriteLine("'{0}' is not an int data type.", value);
      }
   }
}
100 is an integer data type.
'17111' is not an int data type.
Python OpenCV | cv2.cvtColor() method

18 Oct, 2019
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV. We will use some of color space conversion codes below.
Syntax: cv2.cvtColor(src, code[, dst[, dstCn]])
Parameters:src: It is the image whose color space is to be changed.code: It is the color space conversion code.dst: It is the output image of the same size and depth as src image. It is an optional parameter.dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter.
Return Value: It returns an image.
Image used for all the below examples:
Example #1:
# Python program to explain cv2.cvtColor() method    # importing cv2 import cv2    # path path = r'C:\Users\Administrator\Desktop\geeks.png'   # Reading an image in default modesrc = cv2.imread(path)   # Window name in which image is displayedwindow_name = 'Image'  # Using cv2.cvtColor() method# Using cv2.COLOR_BGR2GRAY color space# conversion codeimage = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY )  # Displaying the image cv2.imshow(window_name, image)
Output:
Example #2:Using HSV color space. HSV color space is mostly used for object tracking.
# Python program to explain cv2.cvtColor() method    # importing cv2 import cv2    # path path = r'C:\Users\Administrator\Desktop\geeks.png'   # Reading an image in default modesrc = cv2.imread(path)   # Window name in which image is displayedwindow_name = 'Image'  # Using cv2.cvtColor() method# Using cv2.COLOR_BGR2HSV color space# conversion codeimage = cv2.cvtColor(src, cv2.COLOR_BGR2HSV )  # Displaying the image cv2.imshow(window_name, image)
Output:
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
How to delete a CSV file in Python?

13 Jan, 2021
In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column.
Approach :
Import module.
Check the path of the file.
If the file is existing then we will delete it with os.remove().
Syntax : os.remove(‘Path)
Example 1: Deleting specific csv file.
Python3
# Python program to delete a csv file # csv file present in same directoryimport os  # first check whether file exists or not# calling remove method to delete the csv file# in remove method you need to pass file name and typefile = 'word.csv'if(os.path.exists(file) and os.path.isfile(file)):  os.remove(file)  print("file deleted")else:  print("file not found")
Output:
file deleted
Example 2: Deleting all csv files in a directory
We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.csv’ files in the given directory.
Python3
import osfor folder, subfolders, files in os.walk('csv/'):             for file in files:                   # checking if file is         # of .txt type         if file.endswith('.csv'):             path = os.path.join(folder, file)                             # printing the path of the file             # to be deleted             print('deleted : ', path )                          # deleting the csv file             os.remove(path)
Output:
deleted :  csv/Sample1.csv
deleted :  csv/Sample2.csv
deleted :  csv/Sample3.csv
deleted :  csv/tips.csv
Picked
python-csv
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Minimum swaps required to make a binary string alternating in C++

Given a binary string of even length and equal number of 0’s and 1’s. What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal
If str = 11110000 then 2 swaps are required.
Count number of zeroes at odd position and even position of the string. Let their count be oddZeroCnt and evenZeroCnt respectively
Count number of ones at odd position and even position of the string. Let their count be oddOneCnt and evenOneCnt respectively
We will always swap a 1 with a 0. So we just check if our alternating string starts with 0 then the number of swaps is min (evenZeroCnt, oddOneCnt) and if our alternating string starts with 1 then the number of swaps is min (evenOneCnt, oddZeroCnt). The answer is min of these two
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int getMinSwaps(string str) {
   int minSwaps = 0;
   int oddZeroCnt = 0;
   int evenZeroCnt = 0;
   int oddOneCnt = 1;
   int evenOneCnt = 1;
   int n = str.length();
   for (int i = 0; i < n; ++i) {
      if (i % 2 == 0) {
         if (str[i] == '1') {
            ++evenOneCnt;
         } else {
            ++evenZeroCnt;
         }
      } else {
         if (str[i] == '1') {
            ++oddOneCnt;
         } else {
            ++oddZeroCnt;
         }
      }
   }
   int zeroSwapCnt = min(evenZeroCnt, oddOneCnt);
   int oneSwapCnt = min(evenOneCnt, oddZeroCnt);
   return min(zeroSwapCnt, oneSwapCnt);
}
int main() {
   string str = "11110000";
   cout << "Minimum swaps = " << getMinSwaps(str) << endl;
   return 0;
}
When you compile and execute above program. It generates following output −
Minimum swaps = 2
MySQL query to display databases sorted by creation date?

You can display databases sorted by creation date with ORDER BY clause. Following is the query to display all databases −
mysql> show databases;
This will produce the following output −
+---------------------------+
| Database                  |
+---------------------------+
| bothinnodbandmyisam       |
| business                  |
| commandline               |
| customer_tracker_database |
| customertracker           |
| database1                 |
| databasesample            |
| demo                      |
| education                 |
| hb_student_tracker        |
| hello                     |
| information_schema        |
| javadatabase2             |
| javasampledatabase        |
| mybusiness                |
| mydatabase                |
| mysql                     |
| onetomanyrelationship     |
| performance_schema        |
| rdb                       |
| sample                    |
| sampledatabase            |
| schemasample              |
| sys                       |
| test                      |
| test3                     |
| tracker                   |
| universitydatabase        |
| web                       |
| webtracker                |
+---------------------------+
30 rows in set (0.00 sec)
Following is the query to show databases sorted by creation date −
mysql> SELECT
   -> TABLE_SCHEMA AS ALL_DATABASE_NAME,
   -> MAX(create_time) AS creationTime,
   -> MAX(update_time) updatingTime
   -> FROM INFORMATION_SCHEMA.TABLES
   -> GROUP BY ALL_DATABASE_NAME
   -> ORDER BY creationTime DESC;
This will produce the following output −
+---------------------+---------------------+---------------------+
| ALL_DATABASE_NAME   | creationTime        | updatingTime        |
+---------------------+---------------------+---------------------+
| test                | 2019-04-03 11:37:58 | 2019-04-03 11:38:55 |
| hb_student_tracker  | 2019-03-19 03:54:32 | NULL                |
| sample              | 2019-03-15 00:04:29 | 2019-03-08 16:06:09 |
| test3               | 2019-03-12 20:29:12 | NULL                |
| mysql               | 2019-02-26 07:10:49 | 2019-04-03 11:38:56 |
| demo                | 2019-02-19 03:27:40 | NULL                |
| tracker             | 2019-02-14 19:49:55 | NULL                |
| bothinnodbandmyisam | 2019-02-06 14:32:26 | 2019-02-05 18:11:14 |
| commandline         | 2019-01-30 21:21:56 | NULL                |
| rdb                 | 2019-01-03 19:37:43 | NULL                |
| business            | 2019-01-02 17:32:17 | 2018-12-10 17:53:02 |
| education           | 2018-10-06 15:07:29 | NULL                |
| information_schema  | 2018-09-23 02:09:14 | NULL                |
| sys                 | 2018-09-23 02:09:03 | NULL                |
| performance_schema  | 2018-09-23 02:08:01 | NULL                |
+---------------------+---------------------+---------------------+
15 rows in set (0.05 sec)
How to check in R whether a matrix element is present in another matrix or not?

We can use %in% to check whether a matrix element is present in another matrix or not. For example, suppose we have two matrices defined as −
   M1
1 2 3
1 2 3
1 2 3
   M2
1 2 3
4 5 6
7 8 9
Then M1%in%M2 will return −
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
But M2%in%M1 will return −
[1] TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE
 Live Demo
M1<−matrix(1:25,ncol=5,byrow=TRUE)
M1
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
[4,] 16 17 18 19 20
[5,] 21 22 23 24 25
M2<−matrix(1:50,ncol=5,byrow=TRUE)
M2
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 6 7 8 9 10
[3,] 11 12 13 14 15
[4,] 16 17 18 19 20
[5,] 21 22 23 24 25
[6,] 26 27 28 29 30
[7,] 31 32 33 34 35
[8,] 36 37 38 39 40
[9,] 41 42 43 44 45
[10,] 46 47 48 49 50
M1%in%M2
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
M2%in%M1
[1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
[13] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE
[25] TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
[37] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE
[49] FALSE FALSE
 Live Demo
M3<−matrix(rpois(40,5),ncol=4,byrow=TRUE)
M3
[,1] [,2] [,3] [,4]
[1,] 4 7 7 6
[2,] 5 4 5 2
[3,] 6 3 5 5
[4,] 8 6 6 6
[5,] 3 6 3 6
[6,] 5 3 7 8
[7,] 9 4 6 2
[8,] 4 6 2 4
[9,] 3 2 4 7
[10,] 6 10 3 2
M4<−matrix(rpois(24,5),ncol=4,byrow=TRUE)
M4
[,1] [,2] [,3] [,4]
[1,] 4 8 7 5
[2,] 9 3 8 9
[3,] 6 2 1 5
[4,] 2 10 7 1
[5,] 5 4 7 7
[6,] 4 5 12 6
M3%in%M4
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
M4%in%M3
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[13] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE
 Live Demo
M6<−matrix(rpois(35,6),ncol=7,byrow=TRUE)
M6
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 6 5 9 5 2 4 7
[2,] 7 5 8 8 8 7 5
[3,] 10 4 6 9 8 10 4
[4,] 7 8 9 5 7 6 8
[5,] 6 3 5 8 9 7 6
M7<−matrix(rpois(63,8),ncol=7,byrow=TRUE)
M7
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 7 10 7 10 12 7 8
[2,] 6 7 6 6 7 10 9
[3,] 12 11 7 8 12 6 6
[4,] 6 6 8 13 6 10 5
[5,] 7 7 11 12 10 3 8
[6,] 14 3 11 10 10 3 8
[7,] 9 12 6 8 4 13 7
[8,] 8 10 12 3 4 4 7
[9,] 8 9 10 9 7 7 9
M6%in%M7
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE
[25] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
M7%in%M6
[1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE
[13] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE
[25] TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE
[37] FALSE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[49] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
[61] TRUE TRUE TRUE
Prefix to Postfix Conversion in C++

In this problem, we are given a prefix expression. Our task is to print the postfix conversion of the given expression.
Prefix expression is those expressions which have operators before the operands.
Example: +AB.
Postfix expressions are those expressions which have operators after operands in the expressions.
Example: AB/
The conversion of prefix to postfix should not involve the conversion to infix.
Let’s take an example to understand the problem,
Input: /+XY+NM
Output: XY+NM+/
Explanation: infix -> (X+Y)/(N+M)
To solve this problem, we will first traverse the whole postfix expression in an reverse order. And we will be using the stack data structure for our processing. And do the following for cases of elements found of traversal
Case: if the symbol is operand -> push(element) in stack.
Case: if symbol is operator -> 2*pop(element) from stack. And then push sequence of operand - operand - operator.
Program to show the implementation of our algorithm
 Live Demo
#include <iostream>
#include <stack>
using namespace std;
bool isOperator(char x) {
   switch (x) {
      case '+':
      case '-':
      case '/':
      case '*':
      return true;
   }
   return false;
}
string convertToPostfix(string prefix) {
   stack<string> expression;
   int length = prefix.size();
   for (int i = length - 1; i >= 0; i--) {
      if (isOperator(prefix[i])) {
         string op1 = expression.top();
         expression.pop();
         string op2 = expression.top();
         expression.pop();
         string temp = op1 + op2 + prefix[i];
         expression.push(temp);
      }
      else
         expression.push(string(1, prefix[i]));
   }
   return expression.top();
}
int main() {
   string prefix = "*-AB/+CD*XY";
   cout<<"Prefix expression : "<<prefix<<endl;
   cout<<"Postfix expression : "<<convertToPostfix(prefix);
   return 0;
}
Prefix expression : *-AB/+CD*XY
Postfix expression : AB-CD+XY*/*
Python | Pandas Series.corr() - GeeksforGeeks

17 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.corr() function compute the correlation with other Series, excluding missing values.
Syntax: Series.corr(other, method=’pearson’, min_periods=None)
Parameter :other : Seriesmethod : {‘pearson’, ‘kendall’, ‘spearman’} or callablemin_periods : Minimum number of observations needed to have a valid result
Returns : correlation : float
Example #1: Use Series.corr() function to find the correlation of the given series object with the other.
# importing pandas as pdimport pandas as pd  # Creating the first Seriessr1 = pd.Series([80, 25, 3, 25, 24, 6])  # Creating the second Seriessr2 = pd.Series([34, 5, 13, 32, 4, 15])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the first indexsr1.index = index_  # set the second indexsr2.index = index_  # Print the first seriesprint(sr1)  # Print the second seriesprint(sr2)
Output :
Now we will use Series.corr() function to find the correlation between the underlying data of the given series object with the others.
# find the correlationresult = sr1.corr(sr2)  # Print the resultprint(result)
Output :As we can see in the output, the Series.corr() function has successfully returned the correlation between the underlying data of the given series objects. Example #2 : Use Series.corr() function to find the correlation of the given series object with the other. The series object contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the first Seriessr1 = pd.Series([51, 10, 24, 18, None, 84, 12, 10, 5, 24, 2])  # Creating the second Seriessr2 = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the first indexsr1.index = index_  # set the second indexsr2.index = index_  # Print the first seriesprint(sr1)  # Print the second seriesprint(sr2)
Output :
Now we will use Series.corr() function to find the correlation between the underlying data of the given series object with the others.
# find the correlationresult = sr1.corr(sr2)  # Print the resultprint(result)
Output :As we can see in the output, the Series.corr() function has successfully returned the correlation between the underlying data of the given series objects. Missing values are skipped while calculating the correlation between the objects.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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()
D3.js | d3.scaleBand() Function - GeeksforGeeks

30 Jul, 2019
The d3.scaleBand() function in D3.js is used to construct a new band scale with the domain specified as an array of values and the range as the minimum and maximum extents of the bands. This function splits the range into n bands where n is the number of values in the domain array.
Syntax:
d3.scaleBand().domain(array of values).range(array of values);
Parameters: This function does not accept any parameters.
Return Value: This function returns the corresponding range for the domain’s value.
Below programs illustrate the d3.scaleBand() function in D3.js:
Example 1:
<!DOCTYPE html><html>  <head>    <title>        D3.js | d3.scaleBand() Function    </title>          <script src =        "https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>                  // Calling the scaleBand() function        var A = d3.scaleBand()            .domain(['January', 'February', 'March', 'April', 'May'])            .range([10, 50]);                  // Getting the corresponding range for        // the domain value        console.log(A('January'));        console.log(A('February'));        console.log(A('March'));        console.log(A('April'));        console.log(A('May'));    </script></body>  </html>
Output:
10
18
26
34
42

Example 2:
<!DOCTYPE html><html>  <head>    <title>        D3.js | d3.scaleBand() Function    </title>          <script src =        "https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>                  // Calling the scaleBand() function        var A = d3.scaleBand()            .domain(['January', 'February', 'March', 'April', 'May'])            .range([1, 2]);                   // Getting the corresponding range for        // the domain value        console.log(A('January'));        console.log(A('February'));        console.log(A('March'));        console.log(A('April'));        console.log(A('May'));    </script></body>  </html>
Output:
1
1.2
1.4
1.6
1.8

Reference: https://devdocs.io/d3~5/d3-scale#scaleBand
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
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?
SubBrute – Tool For Subdomain Brute Force - GeeksforGeeks

14 Sep, 2021
SubBrute is a free and open-source tool available on GitHub. SubBrute uses DNS Scan for finding subdomains of the target domain. This feature of SubBrute provides an extra layer of anonymity for security researchers. This tool is free means you can download and use this tool free of cost. SubBrute is used for reconnaissance of subdomains. SubBrute is used for finding the subdomain of the target website. This tool is used to find subdomains from a website/web application.  SubBrute tool is written in python language you must have python language installed into your Kali Linux in order to use this tool. 
Step1: Open your kali Linux operating system and use the following command to install the tool from GitHub.
git clone https://github.com/TheRook/subbrute.git
Step 2: The tool has been downloaded into your Kali Linux. Use the following command to move into the directory of the tool.
cd subbrute
Step 3: Now you are in the directory of the tool. Use the following command to run the tool.
./subbrute.py --help
The tool is running successfully. Now we will see examples to run the tool.
 Use the SubBrute tool to find subdomains of a domain.
./subbrute.py <domain>
You can see that the tool is giving all the subdomains of the domain google.com. You can use your own domain to find subdomains.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux