code-rag-bench/online-tutorials huggingface dataset:
D3.js hierarchy() Function - GeeksforGeeks

23 Sep, 2020
The d3.hierarchy() function in D3.js library is used to construct a root node data from a given hierarchical data. The data that is given must be of an object and must represent a root node.
Syntax:
d3.hierarchy(data[, children]);
Parameters: This function takes a single parameter as given above and described below.
data: This parameter is an object of representing hierarchical data.
Return Value: This function return an object.
Below given are a few examples of the function given above.
Example 1:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width, initial-scale = 1.0"/>    <script src="https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>        var obj = d3.hierarchy({            name: "rootNode",            children: [                {                    name: "child1"                },                {                    name: "child2",                    children: [                        { name: "grandChild1" },                        { name: "grandChild2" },                        { name: "grandChild3" },                        { name: "grandChild4" }                    ]                },                {                    name: "child3",                    children: [                        { name: "grandChild5" },                        { name: "grandChild6" },                    ]                }            ]        });        console.log(obj);            </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width, initial-scale = 1.0"/>    <script src="https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>        var obj = d3.hierarchy({            name: "rootNode",            children: [                {                    name: "child1"                },                {                    name: "child2",                    children: [                        { name: "grandChild1" },                    ]                }            ]        });        console.log(obj);        console.log(obj.data);        console.log(obj.data.children[0]);            </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Javascript String @@iterator Method - GeeksforGeeks

28 Apr, 2021
String [@@iterator]( ) Method is used to make String iterable. [@@iterator]() returns iterator object which iterate over all code point of String. String[@@iterator] is Built – in Property of String. 
We can use this method by making a string iterator. We can make an iterator by calling the @@iterator property of String. In place of @@iterator, we use Symbol.iterator constant.
Syntax:
// Test String
var str ="String"; 

// iterator to String
var iter = str[Symbol.iterator]();
We can get iterator object with next(). It returns the object with keys value and done. The value key holds a real iterating value string and the done key holds true or false if iteration finishes it keeps true if not then false. We can get the value of the object by str.value and done by str.done.
Example 1: Below is the code that illustrates the use of above approach.
Javascript
<script>  const str = 'GFG';  const iterator = str[Symbol.iterator]();  let theChar = iterator.next();    for(let i = 0; i < str.length ;i++) {    console.log(theChar.value , theChar.done);    theChar = iterator.next();  }</script>
Output : 
"G" false
"F" false
"G" false
We can use @@iterator method without assigning iterator by using for — of loop to iterate over-collection of data by using @@iterator method. On each iteration for — of loop call _next().value to iterate in the collection.
Example 2: Below is the code that illustrates the use of above approach.
Javascript
<script>  const str = 'GFG';  const iterator = str[Symbol.iterator]();  let theChar = iterator;    for(let i = 0; i < str.length ;i++)  {      console.log(theChar.next().value );  }    // Using for - of loop  console.log("Iterating by for-of loop :")  for(let i of str)  {      console.log(i)  }</script>
Output:
"G"
"F"
"G"
Iterating by for-of loop  :
"G"
"F"
"G"
JavaScript-Methods
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
C# | How to get the Standard Output Stream through Console - GeeksforGeeks

28 Jan, 2019
Given a normal console, the task is to get the Standard Output Stream through this Console in C#.
Approach: This can be done using the Out property in the Console class of the System package in C#.
Program: Getting the Standard Output Stream
// C# program to illustrate the// Console.Out Propertyusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Get the Standard Output Stream        Console.WriteLine("Standard Output Stream: {0}",                                          Console.Out);    }}}
Output:
Note: The TextWriter represents the standard output stream.
CSharp-Console-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Class and Object
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Arrays
Python | Numpy matrix.trace() - GeeksforGeeks

29 May, 2019
With the help of Numpy matrix.trace() method, we can find the sum of all the elements of diagonal of a matrix by using the matrix.trace() method.
Syntax : matrix.trace()Return : Return sum of a diagonal elements of a matrix
Example #1 :In this example we can see that by using matrix.trace() method can help us to find the sum of all the elements of a diagonal of given matrix.
# import the important module in pythonimport numpy as np              # make matrix with numpygfg = np.matrix('[4, 1; 12, 3]')              # applying matrix.trace() methodgeek = gfg.trace()    print(geek)
[[7]]

Example #2 :
# import the important module in pythonimport numpy as np              # make matrix with numpygfg = np.matrix('[4, 1, 9; 12, 3, 1; 4, 5, 6]')              # applying matrix.trace() methodgeek = gfg.trace()    print(geek)
[[13]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Sound generation on clicking the button using JavaScript - GeeksforGeeks

16 Apr, 2019
The sound generation after clicking the button, receiving notifications or at the time of page load can be done by using JavaScript.
Note:
URL provided in the playSound function can be changed to give the custom sound url.
Style property is not the part of implementation. It is used to provide a nice interface for viewers.
Example: This example generating the sound after clicking the button.
<!DOCTYPE html><html>  <head>    <title>        Sound generation after clicking the button    </title>          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">          <script src='https://code.jquery.com/jquery-2.2.0.min.js'>    </script>    <script src='https://cdn.rawgit.com/admsev/jquery-play-sound/master/jquery.playSound.js'>    </script></head>  <body style="text-align:center;">    <div class="container-fluid" style="margin:35px;">        <p style="font-size:30px;">            <strong>                Click on the button to generate sound            </strong>        </p>                  <br><br>              <button class="btn btn-primary" onclick='$.playSound("http://tusharbaheti28.000webhostapp.com/notification.mp3")'>            Click Me!        </button>    </div></body>  </html>                    
Output:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
GATE | GATE CS 2020 | Question 12 - GeeksforGeeks

26 May, 2021
For parameters a and b, both of which are ω(1), T(n)=T(n1/a)+1, and T(b)=1. Then T(n) is(A) Θ(logalogbn)(B) Θ(logabn)(C) Θ(logblogan)(D) Θ(log2log2n)Answer: (A)Explanation: Given,
T(n) = T(n1/a)+1, 
T(b) = 1 
Now, using iterative method,
= T(n) 
= [T(n1/a2)+1] + 1
= [T(n1/a3)+1] + 2
= [T(n1/a4)+1] + 3
.
.
.
= [T(n1/ak)+1] + (k-1)
= T(n1/ak) + k 
Let,
→ n1/ak = b
→ log(n1/ak) = log(b)
→ ak = log(n) / log (b) = logb(n)
→ k = logalogb(n)
Therefore,
= T(n1/ak) + k
= T(b) + logalogb(n)
= 1 + logalogb(n)
= Θ(logalogb(n)) 
Option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
turtle.heading() function in Python

14 Mar, 2022
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to return the turtle’s current heading. It doesn’t require any argument.
Syntax :
turtle.heading()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle # default heading valueprint(turtle.heading())
 
 
Output :
 
0.0
 
Example 2 :
 
Python3
# import packageimport turtle # set turtle speed# for better understandingsturtle.speed(1) # loop for patternfor i in range(4):    turtle.forward(100)         # get heading value    val = turtle.heading()         # write it    turtle.write(str(val))    turtle.backward(100)    turtle.left(90)
 
 
Output :
 
 
sumitgumber28
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to plot overlapping lines in Matplotlib?

To plot overlapping lines in matplotlib, we can use variable overlapping that basically sets the opacity or alpha value in the plot.
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable overlapping to set the alpha value of the line.
Plot line1 and line2 with red and green colors, respectively, with the same alpha value.
To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
overlapping = 0.150
line1 = plt.plot([1, 3, 5, 2, 5, 3, 1], c='red', alpha=overlapping, lw=5)
line2 = plt.plot([7, 2, 5, 7, 5, 2, 7], c='green', alpha=overlapping,
lw=5)
plt.show()
URL getPort() method in Java with Examples

27 Dec, 2018
The getPort() function is a part of URL class. The function getPort() returns the port of a specified URL. The function returns the port number or -1 if the port is not set
Function Signature
public int getPort()

Syntax
url.getPort()

Return Type: The function returns Integer Type
Parameter: This function does not require any parameter
Below programs illustrates the use of getPort() function:
Example 1display port of specified URL
// Java program to show the use of the function getPort()import java.net.*;class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {            // create a URL            url = new URL("https:// www.geeksforgeeks.org:80");              // get the  port            int _port = url.getPort();              // display the URL            System.out.println("URL = " + url);              // display the  port            System.out.println(" Port=" + _port);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org:80
 Port=80

Example 2: Create a URL with no defined port and then try to get the port using the getPort() function.
// Java program to show the// use of the function getPort()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url object        URL url = null;          try {            // create a URL            url = new URL("https:// www.geeksforgeeks.org");              // get the port            int _port = url.getPort();              // display the URL            System.out.println("URL = " + url);              // display the port            System.out.println(" Port=" + _port);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org
 Port=-1

Java-Functions
Java-net-package
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Set in Java
Python – Alternate List elements

30 Aug, 2020
Given 2 lists, print element in zig-zag manner, i.e print similar indices of lists and then proceed to next.
Input : test_list1 = [5, 3, 1], test_list2 = [6, 4, 2]Output : [5, 6, 3, 4, 1, 2, 4]Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on.
Input : test_list1 = [5, 3, 1, 9], test_list2 = [6, 4, 2, 10]Output : [5, 6, 3, 4, 1, 2, 4, 9, 10]Explanation : 5 and 6, as in 0th index are printed first, then 3 and 4 on 1st index, and so on.
Method #1 : Using loop  
This is one of the ways in which this task can be performed. In this we plainly perform iteration and append the similar index elements one after another in result list.
Python3
# Python3 code to demonstrate working of# Alternate List elements# Using loop  # initializing liststest_list1 = [5, 3, 1, 4, 7]test_list2 = [6, 4, 2, 5, 1]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # Using loop to print elements in criss cross mannerres = []for idx in range(0, len(test_list1)):    res.append(test_list1[idx])    res.append(test_list2[idx])  # printing resultprint("The zig-zag printing of elements : " + str(res))
The original list 1 : [5, 3, 1, 4, 7]
The original list 2 : [6, 4, 2, 5, 1]
The zig-zag printing of elements : [5, 6, 3, 4, 1, 2, 4, 5, 7, 1]

Method #2 : Using zip() + loop
The combination of above functions can be used to solve this problem. In this, we pair each element with similar index using zip() and then each element is fed into result list using loop.
Python3
# Python3 code to demonstrate working of # Alternate List elements# Using  zip() + loop  # initializing liststest_list1 = [5, 3, 1, 4, 7]test_list2 = [6, 4, 2, 5, 1]  # printing original listsprint("The original list 1 : " + str(test_list1))print("The original list 2 : " + str(test_list2))  # Using zip() to perform pairing and loop to # get elements into result listres = []for ele1, ele2 in zip(test_list1, test_list2):    res.append(ele1)    res.append(ele2)      # printing result print("The zig-zag printing of elements : " + str(res))
The original list 1 : [5, 3, 1, 4, 7]
The original list 2 : [6, 4, 2, 5, 1]
The zig-zag printing of elements : [5, 6, 3, 4, 1, 2, 4, 5, 7, 1]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
OS Process Management - GeeksforGeeks

28 Jul, 2021
void P (binary_semaphore *s) {
  unsigned y;
  unsigned *x = &(s->value);
  do {
     fetch-and-set x, y;
  } while (y);
}

void V (binary_semaphore *s) {
  S->value = 0;
}

Semaphore S is initialized to 2

Process W executes S=1, x=1 but it doesn't update the x variable.

Then process Y executes S=0, it decrements x, now x= -2 and 
signal semaphore S=1

Now process Z executes s=0, x=-4, signal semaphore S=1
Now process W updates x=1, S=2

Then process X executes X=2 
Process X:                         Process Y:
private i;                         private i;
for (i=0; i < n; i++) {            for (i=0; i < n; i++) {
   a[i] = f(i);                       EntryY(R, S);
   ExitX(R, S);                       b[i]=g(a[i]);
}                                 }
ExitX(R, S) {
  P(R);
  V(S);
}

EntryY (R, S) {
  P(S);
  V(R);
}
ExitX(R, S) {
  V(R);
  V(S);
}

EntryY(R, S) {
  P(R);
  P(S);
}
ExitX(R, S) {
  P(S);
  V(R);
}
EntryY(R, S) {
  V(S);
  P(R);
}
ExitX(R, S) {
  V(R);
  P(S);
}
EntryY(R, S) {
  V(S);
  P(R);
}
The purpose here is neither the deadlock should occur
nor the binary semaphores be assigned value greater 
than one.
A leads to deadlock
B can increase value of semaphores b/w 1 to n
D may increase the value of semaphore R and S to
 2 in some cases
Process X:                         Process Y:
private i;                         private i;
for (i=0; i < n; i++) {            for (i=0; i < n; i++) {
   a[i] = f(i);                       EntryY(R, S);
   ExitX(R, S);                       b[i]=g(a[i]);
}                                 }
ExitX(R, S) {
  P(R);
  V(S);
}

EntryY (R, S) {
  P(S);
  V(R);
}
ExitX(R, S) {
  V(R);
  V(S);
}

EntryY(R, S) {
  P(R);
  P(S);
}
ExitX(R, S) {
  P(S);
  V(R);
}
EntryY(R, S) {
  V(S);
  P(R);
}
ExitX(R, S) {
  V(R);
  P(S);
}
EntryY(R, S) {
  V(S);
  P(R);
}
The purpose here is neither the deadlock should occur
nor the binary semaphores be assigned value greater 
than one.
A leads to deadlock
B can increase value of semaphores b/w 1 to n
D may increase the value of semaphore R and S to
  2 in some cases
fork();
fork();
fork(); 
  fork ();    // Line 1
  fork ();   // Line 2
  fork ();   // Line 3

       L1       // There will be 1 child process created by line 1
    /     \
  L2      L2    // There will be 2 child processes created by line 2
 /  \    /  \
L3  L3  L3  L3  // There will be 4 child processes created by line 3
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Learn C++ Programming Step by Step - A 20 Day Curriculum!
Must Do Coding Questions for Product Based Companies
Samsung R&D Internship Interview Experience (On-Campus)
Software Testing - Web Based Testing
What are the different ways of Data Representation?
Bash Script - Command Substitution
Naming Convention in C++
Floyd’s Cycle Finding Algorithm
Samsung R&D Interview Experience
Generate Waffle chart using pyWaffle in Python

21 Apr, 2020
A Waffle Chart is a gripping visualization technique that is normally created to display progress towards goals. Where each cell in the Waffle Chart constitutes of 10 X 10 cell grid in which each cell represents one percentage point summing up to total 100%. It is commonly an effective option when you are trying to add interesting visualization features to a visual. Waffle Charts are widely used as an Excel dashboard.
For generating Waffle Chart in Python, modules needed are – matplotlib, pandas and pyWaffle.To install these packages, run the following commands :
pip install matplotlib
pip install pandas
pip install pywaffle

Below is the implementation:
# python program to generate Waffle Chart  # importing all necessary requirementsimport pandas as pdimport matplotlib.pyplot as pltfrom pywaffle import Waffle  # creation of a dataframedata ={'phone': ['Xiaomi', 'Samsung',                 'Apple', 'Nokia', 'Realme'],       'stock': [44, 12, 8, 5, 3]     }  df = pd.DataFrame(data)  # To plot the waffle Chartfig = plt.figure(    FigureClass = Waffle,    rows = 5,    values = df.stock,    labels = list(df.phone))
Output:The above Waffle Chart has been generated for the data in the DataFrame
Advantages:
More visually attractive.
Used for attractive Dashboards.
Disadvantages:
Waffle Chart becomes too complicated when too many segments are involved.
individualized spaces do not leave a spot to put numbers or text within the visual itself.
python-modules
Python
Write From Home
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
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
Similarities and Difference between Java and C++
How to iterate over files in directory using Python?

17 May, 2021
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory.
Below are the various approaches by using which one can iterate over files in a directory using python:
Method 1: os.listdir()
This function returns the list of files and subdirectories present in the given directory. We can filter the list to get only the files using os.path.isfile() function:
Example:
Python3
# import required moduleimport os# assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in os.listdir(directory):    f = os.path.join(directory, filename)    # checking if it is a file    if os.path.isfile(f):        print(f)
Output:
Method 2: os.scandir()
This method is used to get an iterator of os.DirEntry objects corresponding to the entries in the directory given by specified path.
Example:
Python3
# import required moduleimport os # assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in os.scandir(directory):    if filename.is_file():        print(filename.path)
Output:
Method 3: pathlib module
We can iterate over files in a directory using Path.glob() function which glob the specified pattern in the given directory and yields the matching files. Path.glob(‘*’) yield all the files in the given directory 
Example:
Python3
# import required modulefrom pathlib import Path # assign directorydirectory = 'files' # iterate over files in# that directoryfiles = Path(directory).glob('*')for file in files:    print(file)
Output:
Method 4: os.walk()
We can also search for subdirectories using this method as it yields a 3-tuple (dirpath, dirnames, filenames).
root: Prints out directories only from what you specified.
dirs: Prints out sub-directories from the root.
files: Prints out all files from root and directories.
Python3
# import required moduleimport os # assign directorydirectory = 'files' # iterate over files in# that directoryfor root, dirs, files in os.walk(directory):    for filename in files:        print(os.path.join(root, filename))
Output:
Method 5: glob module
The glob.iglob() function returns an iterator over the list of pathnames that match the given pattern.
Example:
Python3
# import required moduleimport glob # assign directorydirectory = 'files' # iterate over files in# that directoryfor filename in glob.iglob(f'{directory}/*'):    print(filename)
Output:
saurabh1990aror
Picked
Python file-handling-programs
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
Find size of a list in Python

A list is a collection data type in Python. The elements in a list are change able and there is no specific order associated with the elements. In this article we will see how to find the length of a list in Python. Which means we have to get the count of number of elements present in the list irrespective of whether they are duplicate or not.
In the below example we take a list named as "days". We first find the length of the list using len() function. And then we add few more elements and check the length again using append() function. Finally we remove some elements using remove() function and check the length again. Please note even though the elements are duplicate the remove() function will remove only e the elements at the end of the list
days = ["Mon","Tue","Wed"]
print (len(days))
# Append some list elements
days.append("Sun")
days.append("Mon")
print("Now the list is: ",days)
print("Length after adding more elements: ",len(days))

# Remove some elements
days.remove("Mon")
print("Now the list is: ",days)
print("Length after removing elements: ",len(days))
Running the above code gives us the following result −
3
Now the list is: ['Mon', 'Tue', 'Wed', 'Sun', 'Mon']
Length after adding more elements: 5
Now the list is: ['Tue', 'Wed', 'Sun', 'Mon']
Length after removing elements: 4
MySQL Tryit Editor v1.0

SELECT CustomerName, City, Country FROM Customers;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to Scrape Paragraphs using Python?

29 Dec, 2020
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup
In this article, we are going to see how we extract all the paragraphs from the given HTML document or URL using python.
Module Needed:
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4

requests:  Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests

Approach:
Import module
Create an HTML document and specify the ‘<p>’ tag into the code
Pass the HTML document into the Beautifulsoup() function
Use the ‘P’ tag to extract paragraphs from the Beautifulsoup object
Get text from the HTML document with get_text().
Code:
Python3
# import modulefrom bs4 import BeautifulSoup  # Html dochtml_doc = """<html><head><title>Geeks</title></head><body><h2>paragraphs</h2>  <p>Welcome geeks.</p>    <p>Hello geeks.</p>  </body></html>"""soup = BeautifulSoup(html_doc, 'html.parser')  # traverse paragraphs from soupfor data in soup.find_all("p"):    print(data.get_text())
Output:
Welcome geeks.
Hello geeks.

Now Lets Extract Paragraphs from the given URL.
Code:
Python3
# import moduleimport requestsimport pandas as pdfrom bs4 import BeautifulSoup  # link for extract html datadef getdata(url):    r = requests.get(url)    return r.text  htmldata = getdata("https://www.geeksforgeeks.org/")soup = BeautifulSoup(htmldata, 'html.parser')data = ''for data in soup.find_all("p"):    print(data.get_text())
Output:
Python web-scraping-exercises
python-utility
Web-scraping
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
Iterate over a list in Python
Convert integer to string in Python
Python OOPs Concepts
TypeScript | Array reverse() Method

03 Mar, 2021
The Array.reverse() is an inbuilt TypeScript function which is used to reverses the element of an array.  Syntax:
array.reverse(); 
Parameter: This methods does not accept any parameter. Return Value: This method returns the reversed single value of the array. Below examples illustrate the Array reverse() Method in TypeScript.
Example 1: 
TypeScript
// Driver codevar arr = [ 11, 89, 23, 7, 98 ];  // use of reverse() method var val = arr.reverse();   // printingconsole.log( val );
Output: 
[ 98, 7, 23, 89, 11 ]
Example 2: 
TypeScript
// Driver codevar arr = [2, 5, 6, 3, 8, 9]; var val;   // use of reverse() method val = arr.reverse();val = val.reverse();   // printingconsole.log( val );
Output: 
[ 2, 5, 6, 3, 8, 9 ]
 
pratikraut0000
TypeScript
JavaScript
Web Technologies
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
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
C Program for Identity Matrix

08 Jul, 2022
Introduction to Identity Matrix :
 The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix.  
In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix.
Examples:  
Input  : 2
Output : 1 0
         0 1

Input :  4
Output : 1 0 0 0
         0 1 0 0
         0 0 1 0
         0 0 0 1
The explanation is simple. We need to make all
the elements of principal or main diagonal as 
1 and everything else as 0.
Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. 
C
// C program to print Identity Matrix#include<stdio.h> int Identity(int num){    int row, col;         for (row = 0; row < num; row++)    {        for (col = 0; col < num; col++)        {            // Checking if row is equal to column            if (row == col)                printf("%d ", 1);            else                printf("%d ", 0);        }        printf("\n");    }    return 0;} // Driver Codeint main(){    int size = 5;    identity(size);    return 0;}
Output: 
1  0  0  0  0  
0  1  0  0  0  
0  0  1  0  0  
0  0  0  1  0  
0  0  0  0  1  
Time complexity: O(n2) where n is number of rows and columns of matrix
Auxiliary Space: O(1)
kumargaurav97520
C Language
C Programs
Mathematical
Matrix
School Programming
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
Smart Pointers in C++ and How to Use Them
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses
How to count number of distinct values per field/ key in MongoDB?

You can use the distinct command for this. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.distinctCountValuesDemo.insertOne({"StudentFirstName":"John","StudentFavouriteSubject":["C","C++","Java","MySQL","C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a39f193b406bd3df60e07")
}
> db.distinctCountValuesDemo.insertOne({"StudentFirstName":"Larry","StudentFavouriteSubject":["MongoDB","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8a3a1193b406bd3df60e08")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.distinctCountValuesDemo.find().pretty();
The following is the output −
{
   "_id" : ObjectId("5c8a39f193b406bd3df60e07"),
   "StudentFirstName" : "John",
   "StudentFavouriteSubject" : [
      "C",
      "C++",
      "Java",
      "MySQL",
      "C",
      "C++"
   ]
}
{
   "_id" : ObjectId("5c8a3a1193b406bd3df60e08"),
   "StudentFirstName" : "Larry",
   "StudentFavouriteSubject" : [
      "MongoDB",
      "SQL Server"
   ]
}
Here is the query to find a number of distinct values per field/key −
> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject');
The following is the output −
[ "C", "C++", "Java", "MySQL", "MongoDB", "SQL Server" ]
Here is the query to find the length of the distinct value in the array −
> db.distinctCountValuesDemo.distinct('StudentFavouriteSubject').length;
The following is the output −
6
List add(int index, E element) method in Java

11 Dec, 2018
The add(int index, E ele) method of List interface in Java is used to insert the specified element at the given index in the current list.
Syntax:
public void add(int index, E element)
Parameter: This method accepts two parameters as shown in the above syntax:
index: This parameter specifies the index at which we the given element is to be inserted.
element: This parameter specifies the element to insert in the list.
Return Value: The return type of the function is void and it does not returns anything.
Exceptions:
UnsupportedOperationException – It throws this exception if the add() operation is not supported by this list.
ClassCastException – It throws this exception if the class of the specified element prevents it from being added to this list.
NullPointerException – It throws this exception if the specified element is null and this list does not permit null elements.
IllegalArgumentException – It throws this exception if some property of this element prevents it from being added to this list.
Below programs illustrate the List.add(int index, E element) method:
Program 1:
// Java code to illustrate add(int index, E elements)import java.io.*;import java.util.*;  public class ArrayListDemo {    public static void main(String[] args)    {          // create an empty list with an initial capacity        List<String> list = new ArrayList<String>(5);          // use add() method to initially        // add elements in the list        list.add("Geeks");        list.add("For");        list.add("Geeks");          // Add a new element at index 0        list.add(0, "Hello");          // prints all the elements available in list        for (String str : list) {            System.out.print(str + " ");        }    }}
Hello Geeks For Geeks

Program 2:
// Java code to illustrate add(int index, E elements)import java.io.*;import java.util.*;  public class ArrayListDemo {    public static void main(String[] args)    {          // create an empty list with an initial capacity        List<Integer> list = new ArrayList<Integer>(5);          // use add() method to initially        // add elements in the list        list.add(10);        list.add(20);        list.add(30);          // Add a new  25 at index 2        list.add(2, 25);          // prints all the elements available in list        for (Integer num : list) {            System.out.print(num + " ");        }    }}
10 20 25 30

Reference: https://docs.oracle.com/javase/7/docs/api/java/util/List.html#add(int, %20E)
Java-Collections
Java-Functions
java-list
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
HashMap in Java with Examples
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Initialize an ArrayList in Java
Initializing a List in Java
C - Command Line Arguments

It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program especially when you want to control your program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. Following is a simple example which checks if there is any argument supplied from the command line and take action accordingly −
#include <stdio.h>

int main( int argc, char *argv[] )  {

   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write above example once again where we will print program name and we also pass a command line argument by putting inside double quotes −
#include <stdio.h>

int main( int argc, char *argv[] )  {

   printf("Program name %s\n", argv[0]);
 
   if( argc == 2 ) {
      printf("The argument supplied is %s\n", argv[1]);
   }
   else if( argc > 2 ) {
      printf("Too many arguments supplied.\n");
   }
   else {
      printf("One argument expected.\n");
   }
}
When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following result.
$./a.out "testing1 testing2"

Program name ./a.out
The argument supplied is testing1 testing2
How to animate scrollLeft using jQuery?

To animate scrollLeft using jQuery, use the animate() method with scrollLeft.
You can try to run the following code to learn how to animate scrollLeft using jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('#scrollme').click(function() {
    $('html,body').animate({
        scrollLeft: $('#demo').css('left')
    }, 500, function() {

        $('html, body').animate({
            scrollLeft: 0
        }, 500);

    });
});
});
</script>
<style>
#demo {
    width: 100px;
    height: 100px;
    background: green;
    position: relative;
    left: 800px;
}
</style>
</head>
<body>
<p><button id="scrollme">Click to scroll left</button></p>

<div id="demo"></div>

</body>
</html>
JavaScript to Calculate the nth root of a number

We are required to write a JavaScript function that calculates the nth root of a number and returns it.
The code for this will be −
const findNthRoot = (m, n) => {
   try {
      let negate = n % 2 == 1 && m < 0;
      if(negate)
         m = −m;
      let possible = Math.pow(m, 1 / n);
      n = Math.pow(possible, n);
      if(Math.abs(m − n) < 1 && (m > 0 == n > 0))
      return negate ? −possible : possible;
   } catch(e){
      return null;
   }
};
console.log(findNthRoot(45, 6));
And the output in the console will be −
1.8859727740585395
Tryit Editor v3.6 - Show Node.js

var http = require('http');
​
http.createServer(function (req, res) {
  // add a HTTP header:
  res.writeHead(200, {'Content-Type': 'text/html'});
How to set src to the img tag in html from the system drive?

To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.
With HTML, add the image source as the path of your system drive. For that, add the src attribute as a link to the path of system drive where the image is stored. For example, file:/D:/images/logo.png
The following are the attributes:
Just keep in mind the <img> tag has no end tag.
You can try the following code to set src to the img tag in HTML from the system drive.Note: This will only work on your local system since the path is your local drive.
<!DOCTYPE html>
<html>
   <head>
      <title>
         HTML img tag
      <title>
   </head>

   <body>
      <img src="file:/D:/images/logo.png" alt="Site Logo" width="50" height="50">
   </body>
</html>
Graph Traversals - GeeksforGeeks

15 Nov, 2018
1) Breadth First Search                           
2) Depth First Search                            
3) Prim's Minimum Spanning Tree                 
4) Kruskal' Minimum Spanning Tree                

1) Stack
2) Queue
3) Priority Queue
4) Union Find
1) Queue
2) Stack
3) Priority Queue
4) Union Find

1) Stack
2) Queue
3) Union Find
4) Priority Queue 
1) Priority Queue
2) Queue
3) Stack
4) Union Find
In DFS, if 'v' is visited
after 'u', then one of the following is true.
1) (u, v) is an edge.
     u
   /   \
  v     w
 /     / \
x     y   z

2) 'u' is a leaf node.
     w
   /   \
  x     v
 /     / \
u     y   z 
(I) a b e g h f 
(II) a b f e h g
(III) a b f h g e 
(IV) a f g h b e  
In DFS, if a vertex 'v' is visited
after 'u', then one of the following is true.
1) (u, v) is an edge.
     u
   /   \
  v     w
 /     / \
x     y   z

2) 'u' is a leaf node.
     w
   /   \
  x     v
 /     / \
u     y   z
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Convert Categorical Variable to Numeric in Pandas?
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Read Text File Into List in Python?
Python Data Structures and Algorithms
PHP mysqli_use_result() Function

The mysqli_use_result() function starts the retrieval of the resultset from the previously executed query
mysqli_use_result($con)

con(Mandatory)
This is an object representing a connection to MySQL Server.
The mysqli_use_result() function returns a result object and the boolean value false in case of an error.
This function was first introduced in PHP Version 5 and works works in all the later versions.
Following example demonstrates the usage of the mysqli_use_result() function (in procedural style) −
<?php
   //Creating a connection
   $con = mysqli_connect("localhost", "root", "password", "test");

   //Executing the multi query
   $query = "SELECT * FROM players;SELECT * FROM emp;SELECT * FROM tutorials";
   $res = mysqli_multi_query($con, $query);

   $count = 0;

   if ($res) {
      do {
         $count = $count+1;
	      mysqli_use_result($con);
     } while (mysqli_next_result($con));
   }
   print("Number of result sets: ".$count);
   mysqli_close($con);
?>
This will produce following result −
Number of result sets: 3

In object oriented style the syntax of this function is $con->use_result(); Following is the example of this function in object oriented style $minus;
<?php
   $con = new mysqli("localhost", "root", "password", "test");

   //Multi query
   $res = $con->multi_query("SELECT * FROM players;SELECT * FROM emp;SELECT * FROM tutorials");

   $count = 0;
   if ($res) {
      do {
         $count = $count+1;
         $con-> use_result();
   } while ($con->next_result());
}
print("Number of result sets: ".$count);

//Closing the connection
$res = $con -> close();
?>
This will produce following result −
Number of result sets: 3

Following example retrieves the records of all the resultsets of the muti-query −
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "test");

//Executing the multi query
$query = "SELECT * FROM players;SELECT * FROM emp";

$res = mysqli_multi_query($con, $query);

if ($res) {
   do {
      if ($result = mysqli_use_result($con)) {
         while ($row = mysqli_fetch_row($result)) {
            print("Name: ".$row[0]."\n");
            print("Age: ".$row[1]."\n");
         }
         mysqli_free_result($result);
      }
      if (mysqli_more_results($con)) {
         print("\n");
      }
   } while (mysqli_use_result($con));
}
mysqli_close($con);
This will produce following result −
Name: Dhavan
Age: 33
Name: Rohit
Age: 28
Name: Kohli
Age: 25

Name: Raju
Age: 25
Name: Rahman
Age: 30
Name: Ramani
Age: 22


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page