code-rag-bench/online-tutorials huggingface dataset:
Node.js Stream readable.read() Method

12 Oct, 2021
The readable.read() method is an inbuilt application programming interface of Stream module which is used to read the data out of the internal buffer. It returns data as a buffer object if no encoding is being specified or if the stream is working in object mode.
Syntax:
readable.read( size )
Parameters: This method accepts single parameter size which specifies the number of bytes to be read from the internal buffer.
Return Value: If this method is used then the data read after this method is displayed in the output and if no data exist in the buffer then null is returned.
Below examples illustrate the use of readable.read() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // readable.read() method     // Include fs moduleconst fs = require("fs");   // Constructing readable streamconst readable = fs.createReadStream("input.txt");   // Instructions for reading datareadable.on('readable', () => {  let chunk;     // Using while loop and calling  // read method  while (null !== (chunk = readable.read())) {       // Displaying the chunk    console.log(`read: ${chunk}`);  }});console.log("done");
Output:
done
read: hello
Here, in the above example the data read from the buffer is ‘hello’ so it is returned.
Example 2:
// Node.js program to demonstrate the     // readable.read() method    // Include fs moduleconst fs = require("fs");  // Constructing readable streamconst readable = fs.createReadStream("input.txt");  // Instructions for reading datareadable.on('readable', () => {  let chunk;    // Using while loop and calling  // read method with parameter  while (null !== (chunk = readable.read(1))) {      // Displaying the chunk    console.log(`read: ${chunk}`);  }});console.log("done");
Output:
done
read: h
read: e
read: l
read: l
read: o

In the above example the size of the data is stated so only one byte is read in each step from the file “input.txt” which contains data ‘hello’.
Reference: https://nodejs.org/api/stream.html#stream_readable_read_size
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Node.js forEach() function
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 ?
Differences between Functional Components and Class Components in React
JoomScan Vulnerability Scanner Tool in Kali Linux

27 Sep, 2021
JoomScan is a free and Open source tool available on GitHub. It’s a vulnerability scanner tool. This tool is written in perl programming language. When a website is being created developers knowingly or unknowingly do some mistakes in code. A hacker can take advantage of that vulnerability and can access the website data. Joomscan is a tool that can be used to find those vulnerabilities it is also called OWASP Joomla vulnerability scanner.
Joomla tool is used as a scanner.
Joomla tool is used to find a vulnerability.
Joomla tool is used to scan CMS.
Joomla, WordPress can be scanned by JoomlaScan.
OWASP JoomScan is included in Kali Linux distributions.
Step 1: Open you terminal of kali Linux and move to the desktop and Now create a new directory called joomla using the following command.
cd Desktop
mkdir joomla
cd joomla 
Step 2: Now you are under joomla directory here you have to download and install joom tool from GitHub now go to GitHub and search for joom tool .or clone it using the following command.
git clone https://github.com/rezasp/joomscan.git
Step 3: The tool has been downloaded in the joom directory and moves the joomscan dir.
ls
cd joomscan
Step 4: Now you have to run the tool using the following command.
perl joomscan.pl
Usages:
perl joomscan.pl -u www.website.com
Enumerate installed components... :
perl joomscan.pl -u www.website.com --ec
Set cookie :
perl joomscan.pl --url www.website.com --cookie "test=demo;"
Set proxy :
perl joomscan.pl -u www.website.com --proxy https://127.0.0.1:443
Set user-agent :
perl joomscan.pl -u www.website.com -a "Googlebot/2.1 (+http://www.website.com/bot.html)"
Set random user-agent :
perl joomscan.pl --url www.website.com -r
Let’s scan google.com:
perl joomscan.pl -u www.google.com 
as5853535
varshagumber28
Cyber-security
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples
java.time.ZoneOffset Class in Java

06 Sep, 2021
A time-zone offset is that the amount of your time that a time-zone differs from Greenwich/UTC. This is often usually a hard and fast number of hours and minutes. From the time package of java, ZoneOffset class is employed to represent the fixed zone offset from UTC zone and inherits the ZoneId class and implements the Comparable interface.
public final class ZoneOffset extends ZoneId    
implements TemporalAccessor, TemporalAdjuster, Comparable<ZoneOffset>, Serializable  
ZoneOffset class has three fields:
MAX: It is the maximum supported zone offsets.
MIN: It is the minimum supported zone offsets.
UTC: It is the time zone offset constant for UTC.
Method of ZoneOffset class
1. ofHoursMinutes() Method:
syntax:
public static ZoneOffset ofHoursMinutes(int Hours, int Minutes)
This method is used to obtain an instance of ZoneOffset using an offset in hours and minutes.
Java
// Example of ofHoursMinutes() Methodimport java.time.ZoneOffset; public class GFG {   public static void main(String[] args) {     ZoneOffset zone = ZoneOffset.ofHoursMinutes(7,15);     System.out.println(zone);   } }
+07:15
2. ofHours() Method
syntax:
public static ZoneOffset ofHours(int hours)
Obtains an instance of ZoneOffset using an offset in hours.
Java
//Example of ofHours() Methodimport java.time.*;import java.time.ZoneOffset; public class GFG {   public static void main(String[] args) {     ZoneOffset zone = ZoneOffset.ofHours(4);     System.out.println(zone);   } }
+04:00
adnanirshad158
Java-time package
Java-ZoneOffset
Picked
Technical Scripter 2020
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
GATE | GATE CS 1999 | Question 18

24 Oct, 2018
Consider the join of a relation R with a relation S. If K has m tuples and S has n tuples, then the maximum and minimum sizes of the join respectively are:(A) m+n and 0(B) mn and 0(C) m+n and m-n(D) mn and m+nAnswer: (B)Explanation: When there is no foreign key constraint between two tables then the max and min number of tuples in their join is mn and 0 respectively.Quiz of this Question
GATE CS 1999
GATE-GATE CS 1999
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
get_screenshot_as_png driver method – Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_screenshot_as_png driver method in Selenium. get_screenshot_as_png method saves a screenshot of the current window as binary data.
Syntax –
driver.get_screenshot_as_png()
Example –Now one can use get_screenshot_as_png method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.get_screenshot_as_png()

To demonstrate, get_screenshot_as_png method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get screenshot,
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")    # get Screenshotprint(driver.get_screenshot_as_png())
Output –Screenshot added –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery UI dialog open() Method

13 Jan, 2021
open() Method is used to open the dialog. This method does not accept any argument
Syntax:
$( ".selector" ).dialog("open");
Approach: First, add jQuery UI scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en">  <head>    <meta charset="utf-8">    <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"        rel="stylesheet">    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>      <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js">    </script>      <script>        $(function () {            $("#gfg").dialog({                autoOpen: false,            });            $("#geeks").click(function () {                $("#gfg").dialog("open");            });        });    </script></head>  <body>    <div id="gfg" title="GeeksforGeeks">        Jquery UI| open dialog method    </div>          <button id="geeks">Open Dialog</button></body>  </html>
Output:
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Design a web page using HTML and CSS
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
jQuery | children() with Examples
Variable Arguments (Varargs) in C#

Use the param keyword to get the variable arguments in C#.
Let us see an example to multiply integers. We have used params keyword to accept any number of int values −
static int Multiply(params int[] b)
The above allows us to find multiplication of numbers with one as well as two int values. The fllowing calls the same function with multiple values −
int mulVal1 = Multiply(5);
int mulVal2 = Multiply(5, 10);
Let us see the complete code to understand how variable arguments work in C# −
using System;

class Program {
   static void Main() {
      int mulVal1 = Multiply(5);
      int mulVal2 = Multiply(5, 10);

      Console.WriteLine(mulVal1);
      Console.WriteLine(mulVal2);
   }

   static int Multiply(params int[] b) {
      int mul =1;
      foreach (int a in b) {
         mul = mul*a;
      }
      return mul;
   }
}
Django Templates | Set - 1 - GeeksforGeeks

26 Aug, 2019
There are two types of web pages – Static and Dynamic pages. Static webpages are those pages whose content is static i.e. they don’t change with time. Every time you open that page, you see the same content. Their content is independent of time, location, user, etc. Dynamic webpages are those pages whose content are generated dynamically i.e. They vary as per location, time, user and on various factors.
Django framework efficiently handles and generates dynamically HTML web pages which are visible to end-user. Django mainly functions with backend so, in order to provide frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our need.
We can use a single template directory which will be spread over the entire project.For each app of our project, we can create a different template directory.
We can use a single template directory which will be spread over the entire project.
For each app of our project, we can create a different template directory.
For our current project, we will create a single template directory which will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.
Create a template directory in the same directory as our project. In our case, which is geeksforgeeks. So, our directory structure is now,Now, navigate to geeksforgeeks/geeks_site/settings.py.
TEMPLATES = [    {        'BACKEND': 'django.template.backends.django.DjangoTemplates',        'DIRS': [],        'APP_DIRS': True,        'OPTIONS': {            'context_processors': [                'django.template.context_processors.debug',                'django.template.context_processors.request',                'django.contrib.auth.context_processors.auth',                'django.contrib.messages.context_processors.messages',            ],        },    },]
In above code, modify
'DIRS': []

as
'DIRS': [os.path.join(BASE_DIR, 'templates')]
Above line links our project to our template directory using the os module. If you print BASE_DIR in your terminal, you will see the directory of your project. For example in my case, it is
/home/ankush/Desktop/Programming/webproject/geeksforgeeks
Now our command will join our BASE_DIR to ‘templates’ and feed it to ‘DIRS’ key of TEMPLATE. Now, we can our save HTML codes in geeksforgeeks/templates directory and can access it from our code.
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
CSS - Using Images

Images play an important role in any webpage. Though it is not recommended to include a lot of images, but it is still important to use good images wherever required.
CSS plays a good role to control image display. You can set the following image properties using CSS.
The border property is used to set the width of an image border.
The border property is used to set the width of an image border.
The height property is used to set the height of an image.
The height property is used to set the height of an image.
The width property is used to set the width of an image.
The width property is used to set the width of an image.
The -moz-opacity property is used to set the opacity of an image.
The -moz-opacity property is used to set the opacity of an image.
The border property of an image is used to set the width of an image border. This property can have a value in length or in %.
A width of zero pixels means no border.
Here is the example −
<html>
   <head>
   </head>

   <body>
      <img style = "border:0px;" src = "/css/images/logo.png" />
      <br />
      <img style = "border:3px dashed red;" src = "/css/images/logo.png" />
   </body>
</html> 
It will produce the following result −
The height property of an image is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.
Here is an example −
<html>
   <head>
   </head>

   <body>
      <img style = "border:1px solid red; height:100px;" src = "/css/images/logo.png" />
      <br />
      <img style = "border:1px solid red; height:50%;" src = "/css/images/logo.png" />
   </body>
</html> 
It will produce the following result −
The width property of an image is used to set the width of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.
Here is an example −
<html>
   <head>
   </head>

   <body>
      <img style = "border:1px solid red; width:150px;" src = "/css/images/logo.png" />
      <br />
      <img style = "border:1px solid red; width:100%;" src = "/css/images/logo.png" />
   </body>
</html> 
It will produce the following result −
The -moz-opacity property of an image is used to set the opacity of an image. This property is used to create a transparent image in Mozilla. IE uses filter:alpha(opacity=x) to create transparent images.
In Mozilla (-moz-opacity:x) x can be a value from 0.0 - 1.0. A lower value makes the element more transparent (The same things goes for the CSS3-valid syntax opacity:x).
In IE (filter:alpha(opacity=x)) x can be a value from 0 - 100. A lower value makes the element more transparent.
Here is an example −
<html>
   <head>
   </head>

   <body>
      <img style = "border:1px solid red; -moz-opacity:0.4; filter:alpha(opacity=40);" src = "/css/images/logo.png" />
   </body>
</html> 
It will produce the following result −
How to Add External Library in Android Studio?

05 May, 2021
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. In this article, we will learn how to add external libraries to our android project.
Let us have an external library that we want to use in our project i.e a jar file.
Create a new project named GFGAddLib.
Now, our project has been created.
Now click on the Android drop-down and change to Project files.
Click on Project files.
Copy the jar file to the libs folder.
Here, you can see our added jar file under the libs folder. Right-click on the jar file and select Add As Library.
Now come back to the Android tab, you can see that your library has been already declared in build.grade (Module: GFGAddLib.app)
The library is successfully added to our project.
Let us have a new project GFGAddLib2 and we want to use the same common-lang3-3.4.jar library for this project.
Create a new Android Module. Go to the File -> New -> New Module
Select Import JAR/.AAR Package and click Next.
Select the location of your JAR file and click on Finish.
Module library has been created. Next, we need to declare the dependency of the main project on the newly created module. Now go to the File and click on Project structure.
Now click on circled + sign and select Module Dependency
Click OK, a new dialogue box will appear, select the jar file and click OK.
Click OK once again and our Jar file is added. You can check your module which has been declared in build.grade (Module: GFGAddLib.app).
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get the id after INSERT into MySQL database using Python

11 Dec, 2020
 Prerequisites: MySQL, mysql-connector for python
The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. 
As the name suggests, it inserts data into the database. Certain rules need to be followed while using the insert command. The data to be updated should either be in the same order as the columns of the database or names of the columns should be given to the query along with the data to be inserted.
Syntax:
INSERT INTO <tablename>(Col1,Col2, ...)
VALUES(....);
To print the ID of the last inserted row lastrowid will be used. This is a special keyword that prints the ID of the row last inserted but to do so there are certain protocols that had to be kept in mind before employing this:
ID column of the database should be a primary key
ID column should auto-incremented.
Given below is the implementation of the same:
Database In Use:
Below is the implementation:
Python3
import mysql.connector  mydb = mysql.connector.connect(    host = 'localhost',    database = 'employee',    user = 'root',    password = 'Your_pass')  cs = mydb.cursor()statement = "INSERT INTO geekstudent( id, name,gender, subject)\VALUES(6,'Shoit','M', 'ML')"cs.execute(statement)mydb.commit()  print(cs.rowcount, " record(s) added")  print(cs.lastrowid)
Output:
1  record(s) added
0
Updated Database Output:
Python-mySQL
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Python program to extract Keywords from a list

01 Oct, 2020
Given List of strings, extract all the words that are keywords.
Input : test_list = [“Gfg is True”, “Its a global win”, “try Gfg”], Output : [‘is’, ‘True’, ‘global’, ‘try’] Explanation : All strings in result list is valid Python keyword.
Input : test_list = [“try Gfg”], Output : [‘try’] Explanation : try is used in try/except block, hence a keyword. 
Method #1 : Using iskeyword() + split() + loop
This is one of the ways in which this task can be performed. In this, we check for keyword using iskeyword() and convert a string to words using split(). The logic of extension to all strings happens using loop.
Python3
# Python3 code to demonstrate working of# Extract Keywords from String List  # Using iskeyword() + loop + split()import keyword  # initializing listtest_list = ["Gfg is True", "Gfg will yield a return",             "Its a global win", "try Gfg"]  # printing original listprint("The original list is : " + str(test_list))    # iterating using loopres = []for sub in test_list:   for word in sub.split():         # check for keyword using iskeyword()       if keyword.iskeyword(word):           res.append(word)  # printing resultprint("Extracted Keywords : " + str(res))
Output:
The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]
Method #2: Using list comprehension
This is yet another way in which this task can be performed. Similar to the above method but much compact on paper, use similar functionalities as the above method.
Python3
# Python3 code to demonstrate working of# Extract Keywords from String List  # Using list comprehensionimport keyword  # initializing listtest_list = ["Gfg is True", "Gfg will yield a return",             "Its a global win", "try Gfg"]  # printing original listprint("The original list is : " + str(test_list))  # One-liner using list comprehensionres = [ele for sub in test_list for ele in sub.split() if keyword.iskeyword(ele)]  # printing resultprint("Extracted Keywords : " + str(res))
Output:
The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]
Python list-programs
Python string-programs
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Download File in Selenium Using Python

04 Jan, 2021
Prerequisite: Selenium
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e. Python, Java, C#, etc. We will be working with Python. Selenium Tutorial covers all topics such as– WebDriver, WebElement, Unit Testing with selenium.  In this article, we are going to see to Download the File From Web Page Using Selenium in Python.
For Downloading the File, we will use the click() method. Here our automation we will download a generated text file.
Follow these steps –
Enter data
Click on generate, it will generate a text file
Click on download, it will download the text file
Here we will use id for entering and generating the text file.
When a file is generated it will give a download option, click on it, the download will start.
Approach:
Import module.
Make an object for chromedriver.
Get URL with get() methods.
Create automation text.
Create link automation for downloading.
Below is the full implementation:
Python3
# Import Modulefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keys  # Open Chromedriver = webdriver.Chrome(    'C:/Users/HP/Desktop/Drivers/chromedriver_win32/chromedriver.exe')  # Open URLdriver.get(    'http://demo.automationtesting.in/FileDownload.html')  # Enter textdriver.find_element_by_id('textbox').send_keys("Hello world")  # Generate Text Filedriver.find_element_by_id('createTxt').click()  # Click on Download Buttondriver.find_element_by_id('link-to-download').click()
Output:
Similarly, we can download a PDF file or any other document. 
Python Selenium-Exercises
Python-selenium
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
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Matplotlib.figure.Figure.savefig() in Python

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The savefig() method figure module of matplotlib library is used to save the current figure.
Syntax: savefig(self, fname, *, transparent=None, **kwargs)
Parameters: This method accept the following parameters that are discussed below:
fname :This parameter is the file name string.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.savefig() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function  import numpy as npimport matplotlib.cm as cmimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt   fig, ax = plt.subplots()s = ax.scatter([1, 2, 3], [4, 5, 6])s.set_url('http://www.google.com')   fig.savefig('scatter.svg')  fig.suptitle("""matplotlib.figure.Figure.savefig()function Example\n\n""", fontweight ="bold")     plt.show() 
Output:
Example 2:
# Implementation of matplotlib function  import numpy as npimport matplotlib.cm as cmimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt   fig, ax = plt.subplots()delta = 0.025x = y = np.arange(-3.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z1 = np.exp(-X**2 - Y**2)Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2   im = ax.imshow(Z,               interpolation ='bilinear',               cmap = cm.gray,               origin ='lower',               extent =[-3, 3, -3, 3])   fig.savefig('image.svg')  fig.suptitle("""matplotlib.figure.Figure.savefig()function Example\n\n""", fontweight ="bold")     plt.show() 
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
What is a method signature in Java?

The method signature consists of the method name and the parameter list.
 Live Demo
public class MethodSignature {
   public int add(int a, int b){
      int c = a+b;
      return c;
   }
   public static void main(String args[]){
      MethodSignature obj = new MethodSignature();
      int result = obj.add(56, 34);
      System.out.println(result);
   }
}
90

Method signature does not include the return type of the method. A class cannot have two methods with same signature. If we try to declare two methods with same signature you will get a compile time error.
public class MethodSignature {
   public int add(int a, int b){
      int c = a+b;
      return c;
   }
   public double add(int a, int b){
      double c = a+b;
      return c;
   }
   public static void main(String args[]){
      MethodSignature obj = new MethodSignature();
      int result = obj.add(56, 34);
      System.out.println(result);
   }
}
C:\Sample>javac MethodSignature.java
MethodSignature.java:7: error: method add(int,int) is already defined in class MethodSignature
public double add(int a, int b){
              ^
1 error
Pandas – How to reset index in a given DataFrame

25 Aug, 2021
Let us see how to reset the index of a DataFrame after dropping some of the rows from the DataFrame.Approach : 
Import the Pandas module.Create a DataFrame.Drop some rows from the DataFrame using the drop() method.Reset the index of the DataFrame using the reset_index() method.Display the DataFrame after each step. 
Import the Pandas module.
Create a DataFrame.
Drop some rows from the DataFrame using the drop() method.
Reset the index of the DataFrame using the reset_index() method.
Display the DataFrame after each step. 
Python3
# importing the modulesimport pandas as pdimport numpy as np # creating a DataFrameODI_runs = {'name': ['Tendulkar', 'Sangakkara', 'Ponting',                      'Jayasurya', 'Jayawardene', 'Kohli',                      'Haq', 'Kallis', 'Ganguly', 'Dravid'],            'runs': [18426, 14234, 13704, 13430, 12650,                     11867, 11739, 11579, 11363, 10889]}df = pd.DataFrame(ODI_runs) # displaying the original DataFrameprint("Original DataFrame :")print(df) # dropping the 0th and the 1st indexdf = df.drop([0, 1]) # displaying the altered DataFrameprint("DataFrame after removing the 0th and 1st row")print(df) # resetting the DataFrame indexdf = df.reset_index() # displaying the DataFrame with new indexprint("Dataframe after resetting the index")print(df)
Output :  
 
 
 
anikakapoor
pandas-dataframe-program
Python pandas-dataFrame
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 ?
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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
basic_istream::peek() in C++ with Examples

28 May, 2020
The std::basic_istream::peek() used to reads the next character from the input stream without extracting it. This function does not accept any parameter, simply returns the next character in the input string. Below is the syntax for the same:
Header File:
#include<iostream>

Syntax:
int peek();

Return Value: The std::basic_istream::peek() return a next character in the input string.
Below are the programs to understand the implementation of std::basic_istream::peek() in a better way:
Program 1:
// C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std;  // main methodint main(){    istringstream gfg("GeeksforGeeks");      char c1 = gfg.peek();    char c2 = gfg.get();    char c3 = gfg.get();      cout << "The first character is: "         << c1 << endl         << " and the next is: "         << c3 << endl;}
The first character is: G 
and the next is: e

Program 2:
// C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std;  // main methodint main(){    istringstream gfg("Computer");      char c1 = gfg.peek();    char c2 = gfg.get();    char c3 = gfg.get();      cout << "The first character is: "         << c1 << endl         << " and the next is: "         << c3 << endl;}
The first character is: C 
and the next is: o

Program 3:
// C++ code for std::basic_istream::peek()#include <bits/stdc++.h>using namespace std;  // main methodint main(){    istringstream gfg("Laptop");      char c1 = gfg.peek();    char c2 = gfg.get();    char c3 = gfg.get();    char c4 = gfg.get();      cout << "The first character is: "         << c1 << endl         << " and the next is: "         << c3 << endl         << " after that next is: "         << c4 << endl;}
The first character is: L 
and the next is: a 
after that next is: p

Reference: http://www.cplusplus.com/reference/istream/basic_istream/peek/
CPP-Functions
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Least Slack Time (LST) scheduling Algorithm in real-time systems

16 Jan, 2020
Least Slack Time (LST) is a dynamic priority-driven scheduling algorithm used in real-time systems.
In LST, all the tasks in the system are assigned some priority according to their slack time. The task which has the least slack time has the highest priority and vice versa.
Priorities to the tasks are assigned dynamically.
Slack time can be calculated using the equation:
slack_time = ( D - t - e' )
Here D : Deadline of the task        t : Real time when the cycle starts.        e’ : Remaining Execution Time of the task.
The task which has the minimal slack time is dispatched to the CPU for its execution as it has the highest priority.
Hyper Period (HP) is the time period of the Gantt chart which is equal to the LCM of the periods of all the tasks in the system.
At time t, the slack of a task is equivalent to ( d-t ) minus the time required to complete the remaining portion of the task.
It is a complex algorithm, and that is why it requires extra information like execution times and deadlines. Least Slack Time scheduling algorithm works optimally only when preemption is allowed. It can produce a feasible schedule if and only if a feasible schedule exists for the set of tasks that are runnable.
It is different from the Earliest Deadline First because it requires execution times of the task which are to be scheduled. Hence it is sometimes impractical to implement the Least Slack Time scheduling algorithm because the burst time of the tasks in real-time systems is difficult to predict.
Unlike EDF (Earliest Deadline First) scheduling algorithm, LST may under-utilize the CPU, thus decreasing the efficiency and throughput.
If two or more tasks which are ready for execution in LST, and the tasks have the same slack time or laxity value, then they are dispatched to the processor according to the FCFS (First Come First Serve) basis.
At time t=0: Only task T1, has arrived. T1 is executed till time t=4.
At time t=4: T2 has arrived.Slack time of T1: 33-4-6=23Slack time of T2: 28-4-3=21Hence T2 starts to execute till time t=5 when T3 arrives.
At time t=5:Slack Time of T1: 33-5-6=22Slack Time of T2: 28-5-2=21Slack Time of T3: 29-5-10=12Hence T3 starts to execute till time t=13
At time t=13:Slack Time of T1: 33-13-6=14Slack Time of T2: 28-13-2=13Slack Time of T3: 29-13-2=14Hence T2 starts to execute till time t=15
At time t=15:Slack Time of T1: 33-15-6=12Slack Time of T3: 29-15-2=12Hence T3 starts to execute till time t=16
At time t=16:Slack Time of T1: 33-16-6=11Slack Time of T3:29-16-=12Hence T1 starts to execute till time t=18 and so on..
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Disk Scheduling Algorithms
Introduction of Deadlock in Operating System
Inter Process Communication (IPC)
Paging in Operating System
File Allocation Methods
Introduction of Operating System - Set 1
CPU Scheduling in Operating Systems
Semaphores in Process Synchronization
Difference between Process and Thread
Tryit Editor v3.7

Tryit: Create input fields with black border color on focus
Optimal Division in C++

Suppose we have a list of positive integers; the adjacent integers will perform the float division. So for example, [2,3,4] -> 2 / 3 / 4. Now, we can add any number of parenthesis at any position to change the priority of these operations. We should find out how to add parenthesis to get the maximum result, we have to find the corresponding expression in string format. Our expression should NOT contain redundant parenthesis. So if the input is like [1000,100,10,2], then the result will be “1000/(100/10/2)”.
To solve this, we will follow these steps −
n := size of nums array
if n is 0 then return a blank string.
num := nums[0] as string
if n is 1, then return num
if n is 2, then return num concatenate /, concatenate nums[1] as string
den := an empty string
for i in range 1 to n – 1den := den + nums[i] as stringif i is not n – 1, then den := den concatenate ‘/’
den := den + nums[i] as string
if i is not n – 1, then den := den concatenate ‘/’
return num concatenate / concatenate ( concatenate den , concatenate )
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string optimalDivision(vector<int>& nums) {
      int n = nums.size();
      if(n == 0) return "";
      string num = to_string(nums[0]);
      if(n == 1) return num;
      if(n == 2) return num + "/" + to_string(nums[1]);
      string den = "";
      for(int i = 1; i < n; i++){
         den += to_string(nums[i]);
         if(i != n - 1) den += "/";
      }
      return num + "/" + "(" + den + ")";
   }
};
main(){
   vector<int> v = {1000,100,10,2};
   Solution ob;
   cout << (ob.optimalDivision(v));
}
[1000,100,10,2]
1000/(100/10/2)
How to align the bar and line in Matplotlib two Y-axes chart?

To align the bar and line in matplotlib two Y-axes chart, we can use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis.
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe with columns 1 and 2.
Make a Pandas dataframe with columns 1 and 2.
Plot the dataframe using plot() method with kind="bar", i.e., class by name.
Plot the dataframe using plot() method with kind="bar", i.e., class by name.
Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis.
Use twinx() method to create a twin of Axes with a shared X-axis but independent Y-axis.
Plot the axis (Step 3) ticks and dataframe columns values to plot the lines.
Plot the axis (Step 3) ticks and dataframe columns values to plot the lines.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
import pandas as pd

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

df = pd.DataFrame({"col1": [1, 3, 5, 7, 1], "col2": [1, 5, 7, 9, 1]})
ax = df.plot(kind="bar")
ax2 = ax.twinx()

ax2.plot(ax.get_xticks(),
   df[['col1', 'col2']].values,
   linestyle='-',
   marker='o', linewidth=2.0)

plt.show()
Python - Sequence Assignment to Words - GeeksforGeeks

05 Sep, 2020
Given a String of words, assign index to each word.
Input : test_str = ‘geekforgeeks is best’Output : {0: ‘geekforgeeks’, 1: ‘is’, 2: ‘best’}Explanation : Index assigned to each word.
Input : test_str = ‘geekforgeeks best’Output : {0: ‘geekforgeeks’, 1: ‘best’}Explanation : Index assigned to each word.
Method #1 : Using enumerate() + dict() + split()
In this, we first perform task of split() and then add index component to map each word with index using enumerate().
Python3
# Python3 code to demonstrate working of # Sequence Assignment to Words# Using split() + enumerate() + dict()  # initializing stringtest_str = 'geekforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # using dict() to convert result in idx:word manner res = dict(enumerate(test_str.split()))      # printing result print("The Assigned Sequence : " + str(res)) 
The original string is : geekforgeeks is best for geeks
The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}

Method #2 : Using zip() + count() + dict()
In this, the count() component renders the index logic and pairing of each word to index is done using zip().
Python3
# Python3 code to demonstrate working of # Sequence Assignment to Words# Using zip() + count() + dict()from itertools import count  # initializing stringtest_str = 'geekforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # using dict() to convert result in idx:word manner # count() from itertools used for this taskres = dict(zip(count(), test_str.split()))      # printing result print("The Assigned Sequence : " + str(res)) 
The original string is : geekforgeeks is best for geeks
The Assigned Sequence : {0: 'geekforgeeks', 1: 'is', 2: 'best', 3: 'for', 4: 'geeks'}

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Extract all integers from string in C++ - GeeksforGeeks

19 Apr, 2022
Given a string, extract all integers words from it.
Examples :
Input : str = "geeksforgeeks 12 13 practice"
Output : 12 13

Input : str = "1: Prakhar Agrawal, 2: Manish Kumar Rai, 3: Rishabh Gupta"
Output : 1 2 3

Input : str = "Ankit sleeps at 4 am."
Output : 4

The idea is to use stringstream:, objects of this class use a string buffer that contains a sequence of characters.
Algorithm
 1. Enter the whole string into stringstream.
 2. Extract the all words from string using loop.
 2. Check whether a word is integer or not.

/* Extract all integers from string */#include <iostream>#include <sstream>using namespace std;  void extractIntegerWords(string str){    stringstream ss;          /* Storing the whole string into string stream */    ss << str;      /* Running loop till the end of the stream */    string temp;    int found;    while (!ss.eof()) {          /* extracting word by word from stream */        ss >> temp;          /* Checking the given word is integer or not */        if (stringstream(temp) >> found)            cout << found << " ";          /* To save from space at the end of string */        temp = "";    }}  // Driver codeint main(){    string str = "1: 2 3 4 prakhar";    extractIntegerWords(str);    return 0;}
Output:

1 2 3 4 

Related Articles :
Converting string to number and vice-versa in C++
Program to extract words from a given String
Removing spaces from a string using Stringstream
This article is contributed by Prakhar Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
cpp-string
C++
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Operator Overloading in C++
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
List in C++ Standard Template Library (STL)
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Python program to check if a string is palindrome or not
Rename Root @ localhost username in MySQL?

The syntax is as follows to rename Root @localhost
UPDATE MySQL.user SET user = ‘yourNewRootName’ WHERE user = 'root';
To understand the above concept, let us check all the user names and host. The query is as follows
mysql> select user,host from MySQL.user;
The following is the output
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| Bob              | %         |
| Manish           | %         |
| User2            | %         | 
| mysql.infoschema | %         |
| mysql.session    | %         |
| mysql.sys        | %         |
| root             | %         |
| @UserName@       | localhost |
| Adam Smith       | localhost |
| John             | localhost |
| John Doe         | localhost |
| User1            | localhost |
| am               | localhost |
| hbstudent        | localhost |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
+------------------+-----------+
16 rows in set (0.00 sec)
The following is the query to rename the user ‘root’ to some other name
mysql> UPDATE mysql.user set user = 'MyRoot' where user = 'root';
Query OK, 1 row affected (0.13 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the user ‘root’ has been updated with new name ‘MyRoot’ or not. The query is as follows
mysql> select user,host from MySQL.user;
The following is the output
+------------------+-----------+
| user             | host      |
+------------------+-----------+
| Bob              | %         |
| Manish           | %         |
| MyRoot           | %         |   
| User2            | %         |
| mysql.infoschema | %         |
| mysql.session    | %         |
| mysql.sys        | %         |
| @UserName@       | localhost |
| Adam Smith       | localhost |
| John             | localhost |
| John Doe         | localhost |
| User1            | localhost |
| am               | localhost |
| hbstudent        | localhost |
| mysql.infoschema | localhost |
| mysql.session    | localhost |
+------------------+-----------+
16 rows in set (0.00 sec)
Look at the sample output, the root has been updated with new name “MyRoot” successfully.
How to clear console in C?

There are several methods to clear the console or output screen and one of them is clrscr() function. It clears the screen as function invokes. It is declared in “conio.h” header file. There are some other methods too like system(“cls”) and system(“clear”) and these are declared in “stdlib.h” header file.
Here is the syntax to clear the console in C language,
clrscr();
OR
system(“cls”);
OR
system(“clear”);
Here is an example to clear the console in C language,
Let’s say we have “new.txt” file with the following content −
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
Now, let us see the example.
#include<stdio.h>
#include<conio.h>
void main() {
   FILE *f;
   char s;
   clrscr();
   f=fopen("new.txt","r");
   while((s=fgetc(f))!=EOF) {
      printf("%c",s);
   }
   fclose(f);
   getch();
}
0,hell!o
1,hello!
2,gfdtrhtrhrt
3,demo
In the above program, we have a text file “new.txt”. A file pointer is used to open and read the file. It is displaying the content of file. To clear the console, clrscr() is used.
clrscr();
f=fopen("new.txt","r");
while((s=fgetc(f))!=EOF) {
   printf("%c",s);
}