code-rag-bench/online-tutorials huggingface dataset:
HTTP headers | Connection - GeeksforGeeks

07 Nov, 2019
The HTTP Connection header is a general type header that allows the sender or client to specify options that are desired for that particular connection. Instead of opening a new connection for every single request/response, Connection helps in sending or receiving multiple HTTP requests/responses using a single TCP connection. It also controls whether or not the network stays open or close after the current transaction finishes.
Syntax:
Connection: keep-alive
Connection: close
Directives: This HTTP Connection header accept two directives mentioned above and described below:
keep-alive This directive indicates that the client wants to keep the connection open or alive after sending the response message. In HTTP 1.1 version, by default uses a persistent connection where it doesn’t close automatically after a transaction. But the HTTP 1.0 will not consider the connections as persistent, so if you want to keep it alive, you need to include a keep-alive connection header.
close This close connection directive indicates that the client wants to close the connection after sending the response message. In HTTP 1.0, by default, the connection gets closed. But in HTTP 1.1, you need to include it in the header if you want your connection to close.
Note: Both the directives are also headers that represent the connection in combine.
Example:
Here, in the below example, the connection is keep-alive (i.e) the client wants to keep it open and the value is 100. Usually, the value 100 is sufficient for almost every scenario. However, you can increase it depending on the number of files the server needs to deliver within the web page.Keep-Alive: 100
Connection: keep-alive
Keep-Alive: 100
Connection: keep-alive
The below example is the request message sent by a client in which it wants the connection to close after the response message is delivered.Connection: close
Connection: close
To check this Connection in action go to Inspect Element -> Network check the header for Connection like below.
Browser Compatibility: The browsers are compatible with HTTP Connection header are listed below:
Google Chrome
Internet Explorer
Edge
Firefox
Safari
OperaMy Personal Notes
arrow_drop_upSave
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
How to execute PHP code using command line ?
Node.js console.timeStamp() Method - GeeksforGeeks

06 Sep, 2020

The console module provides a simple debugging console that is provided by web browsers which export two specific components:
A Console class that can be used to write to any Node.js stream. Example: console.log(), console.error(),  etc.
A global console that can be used without importing console. Example: process.stdout, process.stderr, etc.
The console.timeStamp() (Added in v8.0.0) method is an inbuilt application programming interface of the ‘console‘ module which does not display anything unless used in the inspector. This method adds an event with the label ‘label‘ to the Timeline panel of the inspector.
Note: The global console methods are neither consistently synchronous nor consistently asynchronous.
Syntax:
console.timeStamp([label])
Parameters: This function accepts a single parameter as mentioned above and described below:

label <string>: It accepts the label name that is further to be used in the inspector.

Return Value: It doesn’t print anything in console instead, prints timestamp at the call in Inspector.
The Below examples illustrate the use of console.timeStamp() method in Node.js.
Example 1:   Filename: index.js
 

 
 










// Node.js program to demonstrate the  
// console.timeStamp() Method 
  
// Starting newProfile() console profile 
console.profile("Hello()"); 
  
// Printing timestamp 
console.timeStamp("Hello()"); 
  
// Finishing profile 
console.profileEnd("Hello()"); 






Run index.js file using the following command:
node index.js
Output in Console:

*Doesn’t print anything in Console...

Output in Inspector(edge):
Example 2:   Filename: index.js
 

 
 










// Node.js program to demonstrate the  
// console.timeStamp() Method 
  
// Starting Hello() console profile 
console.profile("Hello()"); 
  
// Printing timeStamp 
console.timeStamp("Hello()"); 
  
// Performing some action 
for(var i=0; i<1; i++) { 
  console.log("doing some task..."); 
} 
  
// Finishing profile 
console.profileEnd("Hello()"); 
  
// Printing timeStamp again 
console.timeStamp("Hello()"); 






Run index.js file using the following command:
node index.js
Output in Console:

Doing some task...

Output in Inspector (edge):
Reference: https://nodejs.org/api/console.html#console_console_timestamp_label

Node.js-console-module


Node.js-Methods


Node.js


Web Technologies

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Difference between dependencies, devDependencies and peerDependencies
How to connect Node.js with React.js ?
Mongoose find() Function
Mongoose Populate() Method
Node.js Export Module
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript
C program to calculate range of values and an average cost of a personal system.

A personal system is sold at different costs by the vendors.
Let’s take the list of costs (in hundreds) quoted by some vendors −
25.00, 30.50, 15.00, 28.25, 58.15,
37.00, 16.65, 42.00 68.45, 53.50
Calculate the average cost and range of values.
The difference between the highest and the lowest values in the series is called range Hence, Range = highest value - lowest value.
Now, find the highest and the lowest values in the series.
Following is the C program to calculate the range of values and average cost of a personal system −
 Live Demo
#include<stdio.h>
main(){
   int count;
   float value, high, low, sum, average, range;
   sum = 0;
   count = 0;
   printf("enter no's in line and at end press any negative number\n");
   input:
   scanf("%f", &value);
   if (value < 0)
   goto output;
      count = count + 1;
   if (count == 1)
      high = low = value;
   else if (value > high)
      high = value;
   else if (value < low)
      low = value;
      sum = sum + value;
   goto input;
      output:
   average = sum/count;
   range = high - low;
   printf("\n\n");
   printf("Total values : %d\n", count);
   printf("Highest-value: %f\nLowest-value : %f\n", high, low);
   printf("Range : %f\nAverage : %f\n", range, average);
}
When the above program is executed, it produces the following output −
Enter numbers in line and at end press any negative number
22.4 56.8 12.3 48.6 31.4 19.0 -1
Total values: 6
Highest-value: 56.799999
Lowest-value: 12.300000
Range: 44.500000
Average: 31.750000
brk() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
brk, sbrk - change data segment size

#include <unistd.h>
int brk(void *end_data_segment);
void *sbrk(intptr_t increment); 


#include <unistd.h>
int brk(void *end_data_segment);
void *sbrk(intptr_t increment); 
brk() sets the end of the data segment to the value specified by
end_data_segment, when that value is reasonable, the system does have enough memory
and the process does not exceed its max data size (see
setrlimit(2)).
sbrk() increments the program’s data space by
increment bytes.
sbrk() isn’t a system call, it is just a C library wrapper.
Calling sbrk() with an increment of 0 can be used to find the current
location of the program break.
On success,
brk() returns zero, and
sbrk() returns a pointer to the start of the new area.  On error, -1 is returned,
and
errno is set to
ENOMEM. 
brk() and
sbrk() are not defined in the C Standard and are deliberately excluded from the
POSIX.1 standard (see paragraphs B.1.1.1.3 and B.8.3.3).
Various systems use various types for the parameter of sbrk(). Common are int, ssize_t, ptrdiff_t, intptr_t.
execve (2)
execve (2)
getrlimit (2)
getrlimit (2)

Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
PostgreSQL – Copy Table

28 Aug, 2020
PostgreSQL allows copying an existing table including the table structure and data by using various forms of PostgreSQL copy table statement. To copy a table completely, including both table structure and data sue the below statement.
Syntax:
CREATE TABLE new_table AS 
TABLE existing_table;
To copy a table structure without data, users need to add the WITH NO DATA clause to the CREATE TABLE statement as follows:
Syntax:
CREATE TABLE new_table AS 
TABLE existing_table 
WITH NO DATA;
To copy a table with partial data from an existing table, users can use the following statement:
Syntax:
CREATE TABLE new_table AS 
SELECT
*
FROM
    existing_table
WHERE
    condition;
The condition in the WHERE clause of the query defines which rows of the existing table will be copied to the new table.
Note: All the statements above copy table structure and data but do not copy indexes and constraints of the existing table.
Example:Creates a new table named contacts for the demonstration using the below statement:
CREATE TABLE contacts(
    id SERIAL PRIMARY KEY,
    first_name VARCHAR NOT NULL,
    last_name VARCHAR NOT NULL,
    email VARCHAR NOT NULL UNIQUE
);
Now let’s add some data to the contacts table using the below statement:
INSERT INTO contacts(first_name, last_name, email) 
VALUES('Raju', 'Kumar', 'rajukumar@gmail.com'),
      ('Nikhil', 'Aggarwal', 'nikhil@gmail.com');
To copy the contacts to a new table, for example, contacts_backup table, you use the following statement:
CREATE TABLE contact_backup 
AS TABLE contacts;
To verify the above use the below statement:
SELECT * FROM contact_backup;
Output:
We can also check the data type and structure of the contact_backup table using the below command:
\d contact_backup;
It will result in the following:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Creating a REST API Backend using Node.js, Express and Postgres
PostgreSQL - Rename Table
PostgreSQL - Loop Statement
PostgreSQL - Joins
PostgreSQL - CTE
PostgreSQL - UNION operator
PostgreSQL - MD5 Function
PostgreSQL- LPAD Function
PostgreSQL - EXISTS Operator
PostgreSQL - INSERT
JavaScript Array indexOf() Method

28 Jan, 2022
Below is the example of the Array indexOf() method.  
Example:  
javascript
<script>    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];     a = name.indexOf('gfg')     // Printing result of method    document.write(a);</script>
Output:  
0
The arr.indexOf() method is used to find the index of the first occurrence of the search element provided as the argument to the method. Syntax:  
array.indexOf(element, start)
Parameters: This method accepts two parameters as mentioned above and described below:  
element: This parameter holds the element which index will be return.
start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0.
Return value: This method returns the index of the first occurrence of the element. If the element cannot be found in the array, then this method returns -1.Below examples illustrate the Array indexOf() method in JavaScript:  
Example 1: In this example the method will searched for the element 2 in that array return that element index.  
Input : [1, 2, 3, 4, 5].indexOf(2);
Output: 1
Example 2: In this example the method will searched for the element 9 in that array if not found then return -1.  
Input : [1, 2, 3, 4, 5].indexOf(9);
Output: -1
Code for the above method is provided below:Program 1:  
javascript
<script>     // Taking input as an array A    // having some elements.    var A = [ 1, 2, 3, 4, 5 ];     // indexOf() method is called to    // test whether the searching element    // is present in given array or not.    a = A.indexOf(2)     // Printing result of method.    document.write(a);</script>
Output:  
1
Program 2:  
javascript
<script>    // Taking input as an array A    // having some elements.    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];     // indexOf() method is called to    // test whether the searching element    // is present in given array or not.    a = name.indexOf('cat')     // Printing result of method    document.write(a);</script>
Output:  
-1
Supported Browsers: The browsers supported by JavaScript Array indexOf() method are listed below:  
Google Chrome 1 and above
Edge 12 and above
Firefox 1.5 and above
Internet Explorer 9 and above
Opera 9.5 and above
Safari 3 and above
 
Akanksha_Rai
ysachin2314
saurabh1990aror
rkbhola5
javascript-array
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
Node.js | fs.writeFileSync() Method
JavaScript | Promises
How to filter object array based on attributes?
Lodash _.debounce() Method
Python | Sympy Line.angle_between method

30 Jan, 2020
Syntax: Line.angle_between(l2)

 Parameters: 
  l1: LinearEntity
  l2: LinearEntity

Returns:
 angle: angle in radians
Notes: From the dot product of vectors v1 and v2 it is known that: dot(v1, v2) = |v1|*|v2|*cos(A)where A is the angle formed between the two vectors. We can get the directional vectors of the two lines and readily find the angle between the two using the above formula.
Example #1:
# import sympy and Point, Line, pifrom sympy import Point, Line, pi  # using Line() methodl1 = Line((0, 0), (1, 0))l2 = Line((0, 0), (1, 1))  # using angle_between() methodrad = l1.angle_between(l2)  print(rad)
Output:
pi/4
Example #2:
# import sympy and Point, Line, pifrom sympy import Point, Line, pi  # using Line() methodl1 = Line((0, 0), (1, 0))l3 = Line((1, 1), (0, 0))  # using angle_between() methodrad = l1.angle_between(l3)  print(rad)
Output:
3*pi/4
Python SymPy-Geometry
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
Convert integer to string in Python
Matplotlib.axis.Axis.set_label() function in Python

05 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_label() function in axis module of matplotlib library is used to set the label that will be displayed in the legend.  
Syntax: Axis.set_label(self, s) 
Parameters: This method accepts the following parameters. 
s: This parameter is converted to a string by calling str.
Return value: This method return the picking behavior of the artist. 
Below examples illustrate the matplotlib.axis.Axis.set_label() function in matplotlib.axis:
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt  import numpy as np  from matplotlib.collections import EllipseCollection         x = np.arange(5)  y = np.arange(7)  X, Y = np.meshgrid(x**2, y**3)         XY = np.column_stack((X.ravel(), Y.ravel()))         fig, ax = plt.subplots()         ec = EllipseCollection(5, 7, 5, units ='y',                         offsets = XY * 0.5,                         transOffset = ax.transData,                         cmap ="plasma")        ec.set_array((X * Y + X * X).ravel())        ax.add_collection(ec)  ax.autoscale_view()        ax.set_xlabel('X')  ax.set_ylabel('y')        cbar = plt.colorbar(ec)  cbar.set_label('X + Y')      fig.suptitle('matplotlib.axis.Axis.set_label() \function Example\n', fontweight ="bold")      plt.show() 
Output:  
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as plt  import numpy as np         np.random.seed(19680801)         n = 100000x = np.random.standard_normal(n)  y = 2 * np.random.standard_normal(n)  z =[1, 2, 3, 4]         fig, ax = plt.subplots()  hb = ax.hexbin(x, y,                gridsize = 50,                bins ='log',                cmap ='bone')          cb = fig.colorbar(hb, ax = ax)  cb.set_label('log')      fig.suptitle('matplotlib.axis.Axis.set_label() \function Example\n', fontweight ="bold")      plt.show() 
Output:  
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Get Month from date in Pandas – Python

02 Jul, 2020
Pandas has many inbuilt methods that can be used to extract the month from a given date that are being generated randomly using the random function or by using Timestamp function or that are transformed to date format using the to_datetimefunction. Let’s see few examples for better understanding.
Example 1
import pandas as pd    dti = pd.date_range('2020-07-01', periods = 4, freq ='M')print(dti.month)
Int64Index([7, 8, 9, 10], dtype='int64')

Example 2
import pandas as pdimport numpy as npimport datetime  date1 = pd.Series(pd.date_range('2020-7-1 12:00:00', periods = 5))df = pd.DataFrame(dict(date_given = date1))  df['month_of_date'] = df['date_given'].dt.monthdf
Example 3
import pandas as pdimport datetimeimport numpy as np    dates =['14 / 05 / 2017', '2017', '07 / 09 / 2017']  frame = pd.to_datetime(dates, dayfirst = True)frame = pd.DataFrame([frame]).transpose()frame['date']= frameframe['month']= frame['date'].dt.monthframe.drop(0, axis = 1, inplace = True)  frame
Python pandas-dataFrame
Python-pandas
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How to remove all CSS classes using jQuery?

To remove all classes, use the removeClass() method with no parameters. This will remove all of the item's classes.
You can try to run the following code to remove all CSS classes using jQuery:
Live Demo
<html>
   <head>
      <title>jQuery Selector</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   
      <script>
         $(document).ready(function() {
           $("#button1").click(function(){
             $("p").removeClass();
           });
         });
      </script>
       
      <style>
         .red { color:red; }
         .blue { color:blue; }
      </style>
   </head>
   
   <body>
      <p class = "red" >This is first paragraph.</p>
      <p class = "blue">This is second paragraph.</p>
      <button id="button1">Remove</button>
   </body>
</html>
Matplotlib.figure.Figure.set_size_inches() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The set_size_inches() method figure module of matplotlib library is used to set the figure size in inches.
Syntax: set_size_inches(self, w, h=None, forward=True)
Parameters: This method accept the following parameters that are discussed below:
w, h : These parameters are the (width, height) of the figure in inches.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.set_size_inches() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figurefrom mpl_toolkits.axisartist.axislines import Subplot import numpy as np         fig = plt.figure()        ax = Subplot(fig, 111) fig.add_subplot(ax)    fig.set_size_inches(4, 5)     fig.suptitle("""matplotlib.figure.Figure.set_size_inches()function Example\n\n""", fontweight ="bold")   plt.show()
Output:
Example 2:
# Implementation of matplotlib function import matplotlib.pyplot as plt from matplotlib.figure import Figureimport numpy as np           fig = plt.figure(figsize =(7, 6))         ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])      xx = np.arange(0, 2 * np.pi, 0.01) ax.plot(xx, np.sin(xx))     fig.set_size_inches(6, 4)     fig.suptitle("""matplotlib.figure.Figure.set_size_inches()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.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
How to assign values to variables in C#?

A variable is a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
To assign values to a variable, add the value after the equal operator −
int a = 10;
Let us see how to assign values to a variable and print it
 Live Demo
using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {

         int a;

         a = 100;

         Console.WriteLine("a = {0}", a);
         Console.ReadLine();
      }
   }
}
a = 100
BeautifulSoup CSS selector - Selecting nth child - GeeksforGeeks

26 Mar, 2021
In this article, we will see how beautifulsoup can be employed to select nth-child. For this, select() methods of the module are used. The select() method uses the SoupSieve package to use the CSS selector against the parsed document.
Syntax: select(“css_selector”)
CSS SELECTOR:
nth-of-type(n): Selects the nth paragraph child of the parent.
nth-child(n): Selects paragraph which is the nth child of the parent
Approach:
Import moduleScrap data from a webpage.Parse the string scraped to HTML.Use find() function to get tag with the given class name or id or tag_name.Use select(“css_selector”) to find the nth  childPrint the child.
Import module
Scrap data from a webpage.
Parse the string scraped to HTML.
Use find() function to get tag with the given class name or id or tag_name.
Use select(“css_selector”) to find the nth  child
Print the child.
Example 1:
Python3
# importing modulefrom bs4 import BeautifulSoup  markup = """<html>    <head>        <title>GEEKS FOR GEEKS EXAMPLE</title>    </head>    <body>        <p class="1"><b>Geeks for Geeks</b></p>          <p class="coding">A Computer Science portal for geeks.            <h1>Heading</h1>            <b class="gfg">Programming Articles</b>,            <b class="gfg">Programming Languages</b>,            <b class="gfg">Quizzes</b>;        </p>          <p class="coding">practice</p>      </body></html>    """  # parsering string to HTMLsoup = BeautifulSoup(markup, 'html.parser')  parent = soup.find(class_="coding")  # assign nn = 2  # print the 2nd <b> of parentprint(parent.select("b:nth-of-type("+str(n)+")"))print()  # print the <b> which is the 2nd child of the parentprint(parent.select("b:nth-child("+str(n)+")"))
Output:
Explanation:
select(“p:nth-of-type(n)”) means select the nth paragraph child of the parent.
select(“p:nth-child(n)”) means select paragraph which is the nth child of the parent.
Both functions will return [] if a parent doesn’t have nth-child.
Example 2:
Python3
# importing modulefrom bs4 import BeautifulSoupimport requests  # assign websitesample_website='https://www.geeksforgeeks.org/python-programming-language/'page=requests.get(sample_website)  # parsering string to HTMLsoup = BeautifulSoup(page.content, 'html.parser')parent = soup.find(class_="wrapper")  # assign nn = 1  # print the 2nd <b> of parentprint(parent.select("b:nth-of-type("+str(n)+")"))print()  # print the <b> which is the 2nd child of the parentprint(parent.select("b:nth-child("+str(n)+")"))
Output:
Picked
Python BeautifulSoup
Python bs4-Exercises
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Selecting rows in pandas DataFrame based on conditions
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Dynamically change TableView Cell height in Swift

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we’ll need to make use of automatic dimension property. We’ll see this with the help of an sample project.
Create an empty project and go to it’s viewController class, conform it to UITableViewDataSource and UITableViewDelegate.
Now, In the below code, we will first create a table, then register a cell for that table, and add some table properties.
We’ll set the table view delegate and table view datasource.
Finally we’ll add the table view to view. Then we’ll call this function inside the viewDidLoad method of our view controller.
Note: We have set a property called estimatedRowHeight 
func initTableView() {
   let tableView = UITableView()
   tableView.frame = self.view.frame
   tableView.dataSource = self
   tableView.delegate = self
   tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
   tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
   tableView.estimatedRowHeight = UITableView.automaticDimension
   self.view.addSubview(tableView)
}
Now, this code will add a table to our view, we also need to tell the table how many sections and rows we want in our code.
func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 5
}
func numberOfSections(in tableView: UITableView) -> Int {
   return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return 5
}
This code will create some big line of text at the second row in our table view so that it gets the height according to content size.
Note: The UITableViewCell has a label property by default, and a label has 1 line of length by default, so we need to change that to see automatic dimension work.
Now we need to tell the table what height its cell should have.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return UITableView.automaticDimension
}

When we run the above code we get the following result.
How to delete all the file contents using PowerShell?

If you want to delete the entire text file content using PowerShell, then we can use the Clear-Content command. For example, we have the below text file called Locations.txt on the C:\Temp path. You can check the content using the below file.
Get-Content C:\temp\locations.txt
To clear the file content, we can use the below command.
Clear-Content C:\Temp\locations.txt -Force
-Force switch is used to clear the contents without user confirmation.
When you use this command with the pipeline in the Get-Content command, it will generate an IO Exception error that the file is in use because we are already retrieving the contents using Get-Content and then trying to delete the existing content.
Clear-Content : The process cannot access the file 'C:\Temp\locations.txt' because it is being used by another process.
At line:1 char:37
+ Get-Content C:\Temp\locations.txt | Clear-Content
+ ~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\Temp\locations.txt:String) [Clear-Content], IOException
+ FullyQualifiedErrorId : ClearContentIOError,Microsoft.PowerShell.Commands.ClearContentCommand
To clear the file contents for the CSV, we can first import that CSV file and then use the Clear() method to clear the file content. For example,
PS C:\> $csvfile = Import-Csv C:\Temp\Services.csv
PS C:\> $csvfile.Clear()
In the above example, the CSV file stored at C:\temp will be cleared. You can also directly use the Clear-Content command for the CSV file or other files to clear the entire content of the file.
How to create a dashed horizontal line in a ggplot2 graph in R?

To create a dashed horizontal line in a ggplot2 graph in R, we can follow the below steps −
First of all, create a data frame.
Then, create a plot using ggplot2.
After that, create the same plot with geom_hline function having horizontal line defined with y intercept and its type defined with line type argument.
Let's create a data frame as shown below −
 Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
         x       y
1 -0.2622735 0.050784727
2 -0.9453493 0.005828098
3 -0.5544653 -0.569278949
4   0.4988631 0.978485828
5   0.5389510 -2.328920035
6   0.4434926 1.099015564
7   0.2681379 0.760637085
8   1.5537351 0.172285069
9   0.9497421 -1.823161011
10 0.3323686 -1.394199992
11 0.2146744 0.538098034
12 0.8275667 -0.361978640
13 -0.4820211 0.477345035
14  0.4364038 -0.341711304
15 -0.4499373 0.854135140
16 1.6604468 -1.333167314
17 -0.4244539 0.989662861
18 1.3667020 -0.358490011
19 -1.5132316 2.234713443
20 0.8474354 1.162478362
Let’s create a scatterplot between x and y −
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Using geom_hline to create the dashed horizontal line in the above plot with yintercept = 0.5 and linetype = 2 −
 Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()+geom_hline(yintercept=0.5,linetype=2)
Double.ToString Method in C#

The Double.ToString() method in C# is used to convert the numeric value of this instance to its equivalent string representation.
Following is the syntax −
public override string ToString ();
Let us now see an example to implement the Double.ToString() method −
using System;
public class Demo{
   public static void Main(){
      double d = 45.7878d;
      string str = d.ToString();
      Console.WriteLine("String = "+str);
   }
}
This will produce the following output −
String = 45.7878
Let us now see another example −
using System;
public class Demo{
   public static void Main(){
      double d = -68.89d;
      string str = d.ToString();
      Console.WriteLine("String = "+str);
   }
}
This will produce the following output −
String = -68.89
jQuery replaceWith() with Examples

The replaceWith() method in jQuery is used to replace selected elements with new content.
The syntax is as follows −
$(selector).replaceWith(content,function(index))
Above, the content parameter is the content to insert, whereas function is to return the content to replace.
Let us now see an example to implement the jQuery replaceWith() method −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("button").click(function(){
         $("h2").replaceWith("<h2>This is it!</h2>");
      });
   });
</script>
</head>
<style>
div {
   margin: 10px;
   width: 60%;
   border: 2px dashed orange;
   padding: 5px;
   text-align:justify;
}
</style>
<body>
<div>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
<h2>Demo Heading</h2>
</div>
<p>Click the below button to update headings</p>
<button>Click</button>
</body>
</html>
This will produce the following output −
Now, click the button to update headings −
Python Program for Extended Euclidean algorithms

In this article, we will learn about the solution to the problem statement given below.
Problem statement − Given two numbers we need to calculate gcd of those two numbers and display them.
GCD Greatest Common Divisor of two numbers is the largest number that can divide both of them. Here we follow the euclidean approach to compute the gcd i.e. to repeatedly divide the numbers and stop when the remainder becomes zero. Here we extend the algorithm based on previous values obtained in recursion.
Now let’s observe the solution in the implementation below −
 Live Demo
# extended Euclidean Algorithm
def gcdExtended(a, b, x, y):
   # Base Case
   if a == 0 :
      x = 0
      y = 1
      return b
   x1 = 1
   y1 = 1 # storing the result
   gcd = gcdExtended(b%a, a, x1, y1)
   # Update x and y with previous calculated values
   x = y1 - (b/a) * x1
   y = x1
   return gcd
x = 1
y = 1
a = 11
b = 15
g = gcdExtended(a, b, x, y)
print("gcd of ", a , "&" , b, " is = ", g)
gcd of 11 & 15 is = 1
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for Extended Euclidean algorithms
Checking the Given File Exists or Not in Golang - GeeksforGeeks

23 Mar, 2020
In Go language, you are allowed to check whether the given file exists or not with the help of the IsNotExist() function. If this function returns true, then it indicates that the error is known to report that the specified file or directory already does not exist and if it returns false, then it indicates that the given file or directory exists. This method also satisfied by ErrNotExist as well as some syscall errors. It is defined under the os package so, you have to import os package in your program for accessing IsNotExist() function.
Syntax:
func IsNotExist(e error) bool
Example 1:
// Golang program to illustrate how to check the// given file exists or not in the default directorypackage main  import (    "log"    "os")  var (    myfile *os.FileInfo    e      error)  func main() {      // Here Stat() function returns file info and     //if there is no file, then it will return an error         myfile, e := os.Stat("gfg.txt")    if e != nil {              // Checking if the given file exists or not      // Using IsNotExist() function        if os.IsNotExist(e) {            log.Fatal("File not Found !!")        }    }    log.Println("File Exist!!")    log.Println("Detail of file is:")    log.Println("Name: ", myfile.Name())    log.Println("Size: ", myfile.Size())        }
Output:
Example 2:
// Golang program to illustrate how to check// the given file exists or not in given // directorypackage main  import (    "log"    "os")  var (    myfile *os.FileInfo    e      error)  func main() {      // Here Stat() function     // returns file info and     // if there is no file,     // then it will return an error         myfile, e := os.Stat("/Users/anki/Documents/new_folder/myfolder/hello.txt")    if e != nil {              // Checking if the given file exists or not      // Using IsNotExist() function        if os.IsNotExist(e) {            log.Fatal("File not Found !!")        }    }    log.Println("File Exist!!")    log.Println("Detail of file is:")    log.Println("Name: ", myfile.Name())    log.Println("Size: ", myfile.Size())        }
Output:
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Anonymous function in Go Language
Loops in Go Language
How to iterate over an Array using for loop in Golang?
time.Parse() Function in Golang With Examples
Strings in Golang
Structures in Golang
Rune in Golang
Python Program for Print Number series without using any loop

04 May, 2022
Problem – Givens Two number N and K, our task is to subtract a number K from N until number(N) is greater than zero, once the N becomes negative or zero then we start adding K until that number become the original number(N). Note : Not allow to use any loop. Examples :
Input : N = 15 K = 5  
Output : 15 10 5 0 1 5 10 15

Input : N = 20 K = 6
Output : 20 14 8 2 -4 2 8 14 20 
Explanation – We can do it using recursion idea is that we call the function again and again until N is greater than zero (in every function call we subtract N by K). Once the number becomes negative or zero we start adding K in every function call until the number becomes the original number. Here we use a single function for both addition and subtraction but to switch between addition or subtraction function we used a Boolean flag. 
Python3
# Python program to Print Number# series without using loop def PrintNumber(N, Original, K, flag):    #print the number    print(N, end = " ")         # change flag if number    # become negative         if (N <= 0):        if(flag==0):            flag = 1        else:            flag = 0             # base condition for    # second_case (Adding K)         if (N == Original and (not(flag))):        return         # if flag is true    # we subtract value until    # number is greater than zero         if (flag == True):        PrintNumber(N - K, Original, K, flag)        return         # second case (Addition )    if (not(flag)):        PrintNumber(N + K, Original, K, flag);        return     N = 20K = 6PrintNumber(N, N, K, True) # This code is contributed by Mohit Gupta_OMG
Output :
20 14 8 2 -4 2 8 14 20 
Please refer complete article on Print Number series without using any loop for more details!
surinderdawra388
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use ToggleButtonGroup Component in ReactJS ?

08 Apr, 2021
Whenever the user wants to group a related option, the ToggleButtonGroup component is used. Material UI for ReactJS has this component available for us, and it is very easy to integrate. We can use the following approach in ReactJS to use ToggleButtonGroup component.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui module using the following command:
npm install @material-ui/core
npm install @material-ui/icons
npm install @material-ui/labs
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import ToggleButton from '@material-ui/lab/ToggleButton';import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft';import FormatAlignJustifyIcon from '@material-ui/icons/FormatAlignJustify';import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter';  export default function App() {    const [currentAlignment, setCurrentAlignment] = React.useState('center');    return (    <div style={{ display: 'block', padding: 30 }}>      <h4>How to use ToggleGroup Component in ReactJS?</h4>      <ToggleButtonGroup        value={currentAlignment}        onChange={(event, newAlignment) => {          setCurrentAlignment(newAlignment);        }}        exclusive        aria-label="Demo Text Alignment"      >        <ToggleButton value="justify"          aria-label="justified" disabled>          <FormatAlignJustifyIcon />        </ToggleButton>        <ToggleButton value="left"          aria-label="left aligned">          <FormatAlignLeftIcon />        </ToggleButton>        <ToggleButton value="center"          aria-label="centered">          <FormatAlignCenterIcon />        </ToggleButton>      </ToggleButtonGroup>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://material-ui.com/components/toggle-button/#toggle-buttons
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Axios in React: A Guide for Beginners
ReactJS useNavigate() Hook
How to install bootstrap in React.js ?
How to do crud operations in ReactJS ?
How to create a multi-page website using React.js ?
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?
Differences between Functional Components and Class Components in React
How to set a click event once a page or view is loaded in vue.js?

22 Jan, 2021
In this article, we will discuss how to set a click event once a page or view is loaded in vue.js. Just like every other JavaScript framework Vue also supports the Mounting hooks. Mounting hooks are often the most used hooks. They allow us to access or modify the DOM of your component just before or after the first render. 
So, here we will use the mounted hook to trigger a click event when the page is loaded.
Step to setup the Environment:
First, we should install vue.js by using the command below:sudo npm install -g @vue/cliAfter, installing the vue.js. you can create a new project by using the command below:vue create testNow, Go to your project folder by usingcd myappYou can run your project using the command below:npm run serve
First, we should install vue.js by using the command below:sudo npm install -g @vue/cli
First, we should install vue.js by using the command below:
sudo npm install -g @vue/cli
After, installing the vue.js. you can create a new project by using the command below:vue create test
After, installing the vue.js. you can create a new project by using the command below:
vue create test
Now, Go to your project folder by usingcd myapp
Now, Go to your project folder by using
cd myapp
You can run your project using the command below:npm run serve
You can run your project using the command below:
npm run serve
The file structure of your project will look like this:
Syntax
Step-1: Give a reference to the button you want to click.<button ref="Btn" @click="logClicked">Click</button>
<button ref="Btn" @click="logClicked">Click</button>
Step-2: In the mounted hook trigger the button click.mounted () {
  this.$refs.Btn.click()
}
mounted () {
  this.$refs.Btn.click()
}
Example: Open your App.vue file from the test project src folder and update the code.
Javascript
<script>export default({  methods: {    logClicked () {      console.log('Clicked')    }  },  mounted () {    this.$refs.Btn.click()  }})</script><template><div id="app" class="container">    <button ref="Btn" @click="logClicked">Click</button></div></template>
OutputFor can see the output in chrome by typing localhost:8080 also open the console in your Chrome browser by using the command below
 ctrl+shift+j
Picked
Technical Scripter 2020
Vue.JS
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
implicitly_wait 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 implicitly_wait driver method in Selenium. implicitly_wait method sets a sticky timeout to implicitly wait for an element to be found, or a command to complete. This method only needs to be called one time per session. To set the timeout for calls to execute_async_script, see set_script_timeout.
Syntax –
driver.implicitly_wait(time_to_wait)
Example –Now one can use implicitly_wait method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.implicitly_wait(30)

To demonstrate, implicitly_wait method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s set wait time to 30.
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")    # set wait timedriver.implicitly_wait(30)
Output –Screenshot added –
Python-selenium
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function