code-rag-bench/online-tutorials huggingface dataset:
SVG stroke-dasharray Attribute

31 Mar, 2022
The stroke-dasharray attribute is a presentation attribute defining the pattern of dashes used to paint the outline of the shape.
Syntax:
stroke-dasharray="number pattern"
Attribute Values:
dasharray: The pattern stroke that will have.
We will use the stoke-dasharray attribute for setting the pattern of the stroke.
Example 1: In this example we will use the stroke-dasharray attribute for setting the pattern of line.
<!DOCTYPE html> <html>   <body>     <svg viewBox="0 0 50 20"          xmlns="http://www.w3.org/2000/svg">          <line x1="0" y1="1" x2="30" y2="1" stroke="green" />          <line x1="0" y1="3" x2="30" y2="3" stroke="green"        stroke-dasharray="4 1 2 3" />    </svg></body>   </html>
Output:
Example 2: In this example we will use the stroke-dasharray attribute for setting the pattern of circle
<!DOCTYPE html> <html>   <body>     <svg viewBox="0 0 50 21"          xmlns="http://www.w3.org/2000/svg">          <circle x="12" y="3" r="5"                 cx="10" cy="10" stroke="green"/>          <circle x="12" y="3" r="5"                 cx="25" cy="10" stroke="green"        stroke-dasharray="4 1 2 3" />    </svg></body>   </html>
Output:
HTML-SVG
SVG-Attribute
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
deleteLater() method in PyQt5

26 Mar, 2020
While designing an application it could potentially consume a lot of space/memory if care is not taken when closing widgets. The QObject-based classes are designed to be (optionally) linked together in a hierarchy. When a top-level object is deleted, Qt will automatically delete all its child objects as well. However, when closing widgets, automatic deletion will only happen if the Qt.WA_DeleteOnClose attribute is set (which, by default, it usually isn’t).
In PyQt5, there are two aspects to object ownership: the Python part, and the Qt part. Often, removing the last Python reference to an object won’t be enough to fully clean up, because there could still be a reference held on the Qt side. In general, Qt tends not to implicitly delete objects. So if your application creates and removes lots of Widgets, you may need to take steps to delete them explicitly if memory usage is a concern.
deleteLater() method allows us to explicitly delete the reference of the widget.
Syntax : widget.deleteLater()
Argument : It takes no argument.
Action performed : It deletes/remove the reference of the widget from the memory.
Code :
# importing the required libraries  from PyQt5.QtWidgets import * from PyQt5 import QtCorefrom PyQt5 import QtGuiimport sys      class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Memory")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.label_1 = QLabel("Label", self)          # moving position        self.label_1.move(100, 100)          # setting up border        self.label_1.setStyleSheet("border: 1px solid black;")          # delete reference        self.label_1.deleteLater()          # show all the widgets        self.show()      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
It will delete the reference associated with the label widget from memory.Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
maketrans() and translate() functions in Python

15 Oct, 2020
In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article.
maketrans() function is used to construct the transition table i.e specify the list of characters that need to be replaced in the whole string or the characters that need to be deleted from the string
Syntax : maketrans(str1, str2, str3)
Parameters :str1 : Specifies the list of characters that need to be replaced.str2 : Specifies the list of characters with which the characters need to be replaced.str3 : Specifies the list of characters that needs to be deleted.
Returns : Returns the translation table which specifies the conversions that can be used by translate()
To translate the characters in the string translate() is used to make the translations. This function uses the translation mapping specified using the maketrans().
Syntax : translate(table, delstr)
Parameters :table : Translate mapping specified to perform translations.delstr : The delete string can be specified as optional argument is not mentioned in table.
Returns : Returns the argument string after performing the translations using the translation table.
 Code #1 : Code to translate using translate() and maketrans().
# Python3 code to demonstrate # translations using # maketrans() and translate()  # specify to translate charsstr1 = "wy"  # specify to replace withstr2 = "gf"  # delete charsstr3 = "u"  # target string trg = "weeksyourweeks"  # using maketrans() to # construct translate# tabletable = trg.maketrans(str1, str2, str3)  # Printing original string print ("The string before translating is : ", end ="")print (trg)  # using translate() to make translations.print ("The string after translating is : ", end ="")print (trg.translate(table))
Output :
The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks

 
Translation can also be achieved by specifying the translation dictionary and passing as an object which acts as a mapping. In this case, there is no need for maketrans() to perform translations.
 Code #2 : Code to translate without maketrans().
# Python3 code to demonstrate # translations without# maketrans()   # specifying the mapping # using ASCII table = { 119 : 103, 121 : 102, 117 : None }  # target string trg = "weeksyourweeks"  # Printing original string print ("The string before translating is : ", end ="")print (trg)  # using translate() to make translations.print ("The string after translating is : ", end ="")print (trg.translate(table))
Output :
The string before translating is : weeksyourweeks
The string after translating is : geeksforgeeks

 
Application :There are many are times where mistakes can occur while coding or developing, these functions provide an easy and quick way to replace and rectify them and would potentially save a lot of time.
Akanksha_Rai
nidhi_biet
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | How to Concatenate tuples to nested tuples

21 Nov, 2019
Sometimes, while working with tuples, we can have a problem in which we need to convert individual records into a nested collection yet remaining as separate element. Usual addition of tuples, generally adds the contents and hence flattens the resultant container, this is usually undesired. Let’s discuss certain ways in which this problem is solved.
Method #1 : Using + operator + ", " operator during initializationIn this method, we perform the usual addition of tuple elements, but while initializing tuples, we add a comma after the tuple so that they don’t get flattened while addition.
# Python3 code to demonstrate working of# Concatenating tuples to nested tuples# using + operator + ", " operator during initialization  # initialize tuplestest_tup1 = (3, 4),test_tup2 = (5, 6),  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Concatenating tuples to nested tuples# using + operator + ", " operator during initializationres = test_tup1 + test_tup2  # printing resultprint("Tuples after Concatenating : " + str(res))
The original tuple 1 : ((3, 4), )
The original tuple 2 : ((5, 6), )
Tuples after Concatenating : ((3, 4), (5, 6))

 
Method #2 : Using “, ” operator during concatenationThis task can be performed by applying “, ” operator during concatenation as well. It can perform the safe concatenation.
# Python3 code to demonstrate working of# Concatenating tuples to nested tuples# Using ", " operator during concatenation  # initialize tuplestest_tup1 = (3, 4)test_tup2 = (5, 6)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Concatenating tuples to nested tuples# Using ", " operator during concatenationres = ((test_tup1, ) + (test_tup2, ))  # printing resultprint("Tuples after Concatenating : " + str(res))
The original tuple 1 : ((3, 4), )
The original tuple 2 : ((5, 6), )
Tuples after Concatenating : ((3, 4), (5, 6))

shubham_singh
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MATLAB | Display histogram of a grayscale Image

26 Jan, 2019
An image histogram is chart representation of the distribution of intensities in an Indexed image or grayscale image. It shows how many times each intensity value in image occurs.
Code #1: Display histogram of an image using MATLAB library function.
% Read an Image in MATLAB Environmentimg=imread('apple.jpg');  % Convert image to grayscale image# if read image is an RGB imageimg=rgb2gray(img);  % Show histogram of image# using imhist() functionimhist(img);
 Code #2: Display Histogram of an Image without using MATLAB Library function.
Approach :
Read the source image file into image matrix
Convert it to grayscale, if it is an RGB image
Iterate over image matrix and count the frequency of every possible value of intensity
plot the counted frequency
% Read source image file img = imread('apple.jpg');  % Convert image to grayscale image img=rgb2gray(img);  % get the dimension of the image [x, y] = size(img);    % Create a frequency array of size 256frequency = 1 : 256;  count = 0;  % Iterate over grayscale image matrix % for every possible intensity value% and count them    for i = 1 : 256    for j = 1 : x        for k = 1 : y              % if image pixel value at location (j, k) is i-1            % then increment count            if img(j, k) == i-1                    count = count + 1;            end        end    end    % update ith position of frequency array with count    frequency(i) = count;      % reset count    count = 0;  end    n = 0 : 255;  % Display Histogramstem(n, frequency);  grid on;ylabel('Number of pixels with such intensity levels -->');xlabel('Intensity Levels  -->');title('HISTOGRAM OF THE IMAGE');
Input:
Output:
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the current open file line in Python?

Python doesn't support this directly. You could write a wrapper class for it. For example,
class FileLineWrapper(object):
    def __init__(self, file):
        self.f = file
        self.curr_line = 0
    def close(self):
        return self.f.close()
    def readline(self):
        self.curr_line += 1
        return self.f.readline()
    # to allow using in 'with' statements
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
And use the above code as:
f = FileLineWrapper(open("my_file", "r"))
f.readline()
print(f.line)
This will give the output: 1
There are other methods to keep track of the line number if you are only using the readline method. For example,
f=open("my_file", "r")
for line_no, line in enumerate(f):
    print line_no
f.close()
Python program to fetch the indices of true values in a Boolean list

07 Jun, 2019
Given a list of only boolean values, write a Python program to fetch all the indices with True values from given list.
Let’s see certain ways to do this task.
Method #1: Using itertools [Pythonic way]
itertools.compress() function checks for all the elements in list and returns the list of indices with True values.
# Python program to fetch the indices# of true values in a Boolean listfrom itertools import compress     # initializing list  bool_list = [False, True, False, True, True, True]     # printing given list  print ("Given list is : " +  str(bool_list))     # using itertools.compress() # to return true indices. res = list(compress(range(len(bool_list )), bool_list ))     # printing result print ("Indices having True values are : " +  str(res)) 
Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]

 
Method #2: Using enumerate() method
enumerate() method hashes the index with its value and coupled with list comprehension can let us check for the true values.
# Python program to fetch the indices# of true values in a Boolean list  # initializing list  bool_list = [False, True, False, True, True, True]     # printing given list  print ("Given list is : " +  str(bool_list))     # using enumerate() + list comprehension # to return true indices. res = [i for i, val in enumerate(bool_list) if val]       # printing result print ("Indices having True values are : " +  str(res)) 
Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]

 
Method #3: Using filter() + range()
# Python program to fetch the indices# of true values in a Boolean list  # initializing list  bool_list = [False, True, False, True, True, True]     # printing given list  print ("Given list is : " +  str(bool_list))     # using lambda + filter() + range() # to return true indices. res = list(filter(lambda i: bool_list[i], range(len(bool_list))))     # printing result print ("Indices having True values are : " +  str(res)) 
Given list is : [False, True, False, True, True, True]
Indices having True values are : [1, 3, 4, 5]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Rotate axis tick labels in Seaborn and Matplotlib
Enumerate() in Python
Deque in Python
Stack in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Iterate over characters of a string in Python
Python | Convert set into a list
Python Pillow - Using Image Module

To display the image, pillow library is using an image class within it. The image module inside pillow package contains some important inbuilt functions like, load images or create new images, etc.
To load the image, we simply import the image module from the pillow and call the Image.open(), passing the image filename.
Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL). That’s why our code starts with “from PIL import Image” instead of “from Pillow import Image”.
Next, we’re going to load the image by calling the Image.open() function, which returns a value of the Image object data type. Any modification we make to the image object can be saved to an image file with the save() method. The image object we received using Image.open(), later can be used to resize, crop, draw or other image manipulation method calls on this Image object.
Following example demonstrates the rotation of an image using python pillow −
from PIL import Image
#Open image using Image module
im = Image.open("images/cuba.jpg")
#Show actual Image
im.show()
#Show rotated Image
im = im.rotate(45)
im.show()
If you save the above program as Example.py and execute, it displays the original and rotated images using standard PNG display utility, as follows −
Actual image
Rotated image (45 degrees)
The instance of the Image class has some attributes. Let’s try to understand few of them by example −
This function is used to get the file name or the path of the image.
>>>image = Image.open('beach1.jpg')
>>> image.filename
'beach1.jpg'

This function returns file format of the image file like ‘JPEG’, ‘BMP’, ‘PNG’, etc.
>>> image = Image.open('beach1.jpg')
>>>
>>> image.format
'JPEG'

It is used to get the pixel format used by the image. Typical values are “1”, “L”, “RGB” or “CMYK”.
>>> image.mode
'RGB'

It returns the tuple consist of height & weight of the image.
>>> image.size
(1280, 721)

It returns only the width of the image.
>>> image.width
1280

It returns only the height of the image.
>>> image.height
721

It returns a dictionary holding data associated with the image.
>>> image.info
{'jfif': 257, 'jfif_version': (1, 1), 'dpi': (300, 300), 'jfif_unit': 1, 'jfif_density': (300, 300), 'exif': b"Exif\x00\x00MM\x00*\x00\x00\x00
....
....
\xeb\x00\x00'\x10\x00\x00\xd7\xb3\x00\x00\x03\xe8"}

It returns the colour palette table, if any.
>>> image.palette

Output above − None
How can we validate decimal numbers in JavaScript?

Following is the code to validate decimal numbers in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Validate decimal numbers in JavaScript</h1>
<div style="color: green;" class="result"></div>
<input type="number" class="num" />
<button class="Btn">CHECK</button>
<h3>Click the above button to check if a valid decimal number is entered or not</h3>
<script>
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      var str = document.querySelector(".num").value;
      var regex = /^[-+]?[0-9]+\.[0-9]+$/;
      var match = str.match(regex);
      if (match) resEle.innerHTML = "The number given is a decimal number";
      else resEle.innerHTML = "The number given is not a decimal number";
   });
</script>
</body>
</html>
The above code will produce the following output −
On entering a normal number and clicking on ‘CHECK’ button −
On entering a decimal number and clicking on ‘CHECK’ −
Include v/s Extend in Ruby

18 Mar, 2021
Include is used to importing module code. Ruby will throw an error when we try to access the methods of import module with the class directly because it gets imported as a subclass for the superclass. So, the only way is to access it through the instance of the class.
Extend is also used to importing module code but extends import them as class methods. Ruby will throw an error when we try to access methods of import module with the instance of the class because the module gets import to the superclass just as the instance of the extended module. So, the only way is to access it through the class definition.
In simple words, the difference between include and extend is that ‘include’ is for adding methods only to an instance of a class and ‘extend’ is for adding methods to the class but not to its instance.
Example :
# Ruby program of Include and Extend  # Creating a module contains a methodmodule Geek  def geeks    puts 'GeeksforGeeks!'  endend   class Lord    # only can access geek methods  # with the instance of the class.  include Geekend   class Star      # only can access geek methods  # with the class definition.  extend Geekend   # object access Lord.new.geeks  # class accessStar.geeks   # NoMethodError: undefined  method# `geeks' for Lord:ClassLord.geeks 
Output
GeeksforGeeks!
GeeksforGeeks!
main.rb:20:in `': undefined method `geeks' for Lord:Class (NoMethodError)

If we want to import instance methods on a class and its class methods too. We can ‘include’ and ‘extend’ it at the same time.Example :
# Ruby program to understand include and extend  # Creating a module contains a methodmodule Geek  def prints(x)    puts x  endend   class GFG    # by using both include and extend  # we can access them by both instances  #  and class name.  include Geek  extend Geekend  # access the prints() in Geek# module by include in Lord classGFG.new.prints("Howdy") # object access   # access the prints() in Geek # module by extend it in Lord classGFG.prints("GeeksforGeeks!!") # class access
Output
Howdy
GeeksforGeeks!!

Picked
Ruby Keyword
Ruby modules
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rounding Floating Point Number To two Decimal Places in C and C++

07 Aug, 2021
How to round off a floating point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53
First Method:- Using Float precision 
C++
C
#include<bits/stdc++.h>using namespace std; int main(){    float var = 37.66666;     // Directly print the number with .2f precision    cout << fixed << setprecision(2) << var;    return 0;} // This code is contributed by shivanisinghss2110
#include <iostream>using namespace std;int main(){    float var = 37.66666;     // Directly print the number with .2f precision    printf("%.2f", var);    return 0;}
Output:
37.67
Second Method: Using integer typecast If we are in Function then how return two decimal point value
C++
#include <iostream>using namespace std;float round(float var){    // 37.66666 * 100 =3766.66    // 3766.66 + .5 =3767.16    for rounding off value    // then type cast to int so value is 3767    // then divided by 100 so the value converted into 37.67    float value = (int)(var * 100 + .5);    return (float)value / 100;} int main(){    float var = 37.66666;    cout << round(var);    return 0;}
Output:
37.67
Third Method: using sprintf() and sscanf() 
C++
#include <iostream>using namespace std;float round(float var){    // we use array of chars to store number    // as a string.    char str[40];     // Print in string the value of var    // with two decimal point    sprintf(str, "%.2f", var);     // scan string value in var    sscanf(str, "%f", &var);     return var;} int main(){    float var = 37.66666;    cout << round(var);    return 0;}
Output:
37.67
This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
arjunaggarwal
simmytarika5
shivanisinghss2110
cpp-data-types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.isnull()

12 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.isnull() function detect missing values in the given series object. It return a boolean same-sized object indicating if the values are NA. Missing values gets mapped to True and non-missing value gets mapped to False.
Syntax: Series.isnull()
Parameter : None
Returns : boolean
Example #1: Use Series.isnull() function to detect missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.isnull() function to detect all the missing values in the given series object.
# detect missing valuesresult = sr.isnull()  # Print the resultprint(result)
Output :As we can see in the output, the Series.isnull() function has returned an object containing boolean values. All values have been mapped to False because there is no missing value in the given series object. Example #2 : Use Series.isnull() function to detect missing values in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([11, 21, 8, 18, 65, None, 32, 10, 5, 24, None])  # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M')  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.isnull() function to detect all the missing values in the given series object.
# detect missing valuesresult = sr.isnull()  # Print the resultprint(result)
Output :As we can see in the output, the Series.isnull() function has returned an object containing boolean values. All missing values have been mapped to True.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
pandas.bdate_range() function in Python

14 Aug, 2020
This method is used to return a fixed frequency DatetimeIndex, with the business day as the default frequency.
Syntax : pandas.bdate_range(start=None, end=None, periods=None, freq=’B’, tz=None, normalize=True, name=None, weekmask=None, holidays=None, closed=None, **kwargs,)
Parameters :
start : string or datetime-like, default None, Left bound for generating dates.
end : string or datetime-like, default None, Right bound for generating dates.
periods : integer, default None, Number of periods to generate.
freq :  string or DateOffset, default ‘B’ (business daily), Frequency strings can have multiples, e.g. ‘5H’.
tz : string or None, Time zone name for returning localized DatetimeIndex, for example Asia/Beijing.
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packagesimport pandas  # using pandas.bdate_range() methodprint(pandas.bdate_range(start='8/1/2020',                         end='8/20/2020'))
Output:
Example 2 :
Python3
# importing packagesimport pandas  # using pandas.bdate_range() methodprint(pandas.bdate_range(start='8/1/2020',                         end='8/5/2020',                         freq='5H'))
Output :
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Design and Analysis Shortest Paths

Dijkstra’s algorithm solves the single-source shortest-paths problem on a directed weighted graph G = (V, E), where all the edges are non-negative (i.e., w(u, v) ≥ 0 for each edge (u, v) Є E).
In the following algorithm, we will use one function Extract-Min(), which extracts the node with the smallest key.
Algorithm: Dijkstra’s-Algorithm (G, w, s) 
for each vertex v Є G.V  
   v.d := ∞ 
   v.∏ := NIL 
s.d := 0 
S := Ф 
Q := G.V 
while Q ≠ Ф 
   u := Extract-Min (Q) 
   S := S U {u} 
   for each vertex v Є G.adj[u] 
      if v.d > u.d + w(u, v) 
         v.d := u.d + w(u, v) 
         v.∏ := u

The complexity of this algorithm is fully dependent on the implementation of Extract-Min function. If extract min function is implemented using linear search, the complexity of this algorithm is O(V2 + E).
In this algorithm, if we use min-heap on which Extract-Min() function works to return the node from Q with the smallest key, the complexity of this algorithm can be reduced further.
Let us consider vertex 1 and 9 as the start and destination vertex respectively. Initially, all the vertices except the start vertex are marked by ∞ and the start vertex is marked by 0.
Hence, the minimum distance of vertex 9 from vertex 1 is 20. And the path is
1→ 3→ 7→ 8→ 6→ 9
This path is determined based on predecessor information.
This algorithm solves the single source shortest path problem of a directed graph G = (V, E) in which the edge weights may be negative. Moreover, this algorithm can be applied to find the shortest path, if there does not exist any negative weighted cycle.
Algorithm: Bellman-Ford-Algorithm (G, w, s) 
for each vertex v Є G.V  
   v.d := ∞ 
   v.∏ := NIL 
s.d := 0 
for i = 1 to |G.V| - 1 
   for each edge (u, v) Є G.E 
      if v.d > u.d + w(u, v) 
         v.d := u.d +w(u, v) 
         v.∏ := u 
for each edge (u, v) Є G.E 
   if v.d > u.d + w(u, v) 
      return FALSE 
return TRUE

The first for loop is used for initialization, which runs in O(V) times. The next for loop runs |V - 1| passes over the edges, which takes O(E) times.
Hence, Bellman-Ford algorithm runs in O(V, E) time.
The following example shows how Bellman-Ford algorithm works step by step. This graph has a negative edge but does not have any negative cycle, hence the problem can be solved using this technique.
At the time of initialization, all the vertices except the source are marked by ∞ and the source is marked by 0.
In the first step, all the vertices which are reachable from the source are updated by minimum cost. Hence, vertices a and h are updated.
In the next step, vertices a, b, f and e are updated.
Following the same logic, in this step vertices b, f, c and g are updated.
Here, vertices c and d are updated.
Hence, the minimum distance between vertex s and vertex d is 20.
Based on the predecessor information, the path is s→ h→ e→ g→ c→ d
Program to check whether a binary tree is BST or not in Python

Suppose we have binary tree; we have to check whether it is a binary search tree or not. As we know a BST has following properties −
all nodes on its left subtree is smaller than current node value
all nodes on its right subtree is larger than current node value
these properties hold recursively for all nodes
So, if the input is like
then the output will be True
To solve this, we will follow these steps −
x := a list of inorder traversal sequence of tree elements
if x is sorted, thenreturn true
return true
return false
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
class Solution:
   def solve(self, root):
      def inorder(root,l):
         if root is None:
            return
            inorder(root.left,l) l.append(root.data)
            inorder(root.right,l)
            l = []
            inorder(root,l)
         return l == sorted(l)
ob = Solution()
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9) root.right.left = TreeNode(7) root.right.right = TreeNode(10) root.right.left.left = TreeNode(6) root.right.left.right = TreeNode(8) print(ob.solve(root))
root = TreeNode(5)
root.left = TreeNode(1)
root.right = TreeNode(9)
root.right.left = TreeNode(7)
root.right.right = TreeNode(10)
root.right.left.left = TreeNode(6)
root.right.left.right = TreeNode(8)
True
PyQt5 – Changing size of Indicator in Check Box

22 Apr, 2020
In this article we will see how to change the size of indicator. Indicator is the part of check box although if we change the size of check box with the help of resize method or setGeometry method, but it will change the size of check box but not the indicator.
In order to change the size of indicator we have to change the height and width in the style sheet of the indicator which is used with check box object. Below is the style sheet code.
QCheckBox::indicator
{
width : 40px;
height : 40px;
}

Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating the check-box        checkbox = QCheckBox('Geek ?', self)          # setting geometry of check box        checkbox.setGeometry(200, 150, 100, 80)          # setting stylesheet        # changing width and height of indicator        checkbox.setStyleSheet("QCheckBox::indicator"                               "{"                               "width :40px;"                               "height : 40px;"                               "}")      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
TypeScript | Array indexOf() Method

18 Jun, 2020
The Array.indexOf() is an inbuilt TypeScript function which is used to find the index of the first occurrence of the search element provided as the argument to the function.  Syntax:
array.indexOf(searchElement[, fromIndex])
Parameter: This method accepts two parameter as mentioned above and described below: 
searchElement : This parameter is the Element to locate in the array.
fromIndex : This parameter is the index at which to begin the search.
Return Value: This method returns the index of the found element. Below examples illustrate the Array indexOf() method in TypeScript.
Example 1: 
JavaScript
<script>    // Driver code    var arr = [ 11, 89, 23, 7, 98 ];       // use of indexOf() method     var val = arr.indexOf(7)           // printing element    console.log(val);</script>
Output: 
3

Example 2: 
JavaScript
<script>    // Driver code    var arr = [ 'a','b','c','a','e' ];       // use of indexOf() method     var val = arr.indexOf('a',4)           // printing element    console.log(val);</script>
Output: 
-1

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
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
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 ?
How to Get the Shape of a Tensor as a List of int in Pytorch?

04 Jul, 2021
To get the shape of a tensor as a list in PyTorch, we can use two approaches. One using the size() method and another by using the shape attribute of a tensor in PyTorch. In this short article, we are going to see how to use both of the approaches.
The size() method returns the size of the self tensor. The returned value is a subclass of a tuple.
Python3
import torchtorch.empty(3, 4, 5).size()
Output: 
torch.Size([3, 4, 5])
We cast this into a list using the list() method. 
Example:
Python3
v = torch.tensor([[1,0],[0,1]])x = list(v.size())print(x)
Output:
[2, 2] 
You can also use the Python interactive session as shown below:
The tensor.shape is an alias to tensor.size(), though the shape is an attribute, and size() is a method. To verify this we can run the following in the interactive session.
We can similarly cast this into a list using the list() method. 
Example:
Python3
import torchv = torch.tensor([[1,0],[0,1]])x = list(v.shape)print(x)
 Output:
 [2,2]
Alternatively using the interactive session:
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Archives - GeeksforGeeks

Merge Sort
Largest Sum Contiguous Subarray
Reverse a linked list
Binary Search Tree | Set 1 (Search and Insertion)
Level Order Binary Tree Traversal
Stack Data Structure (Introduction and Program)
Topological Sorting
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Detect Cycle in a Directed Graph
K'th Smallest/Largest Element in Unsorted Array | Set 1
Lodash _.toPairs() Method

09 Sep, 2020
The _.toPairs() method is used to create an array of own enumerable string key-value pairs for an object which can be consumed by the _.fromPairs() function. If the object is a map or set, its entries are returned.
Syntax:
_.toPairs(object)

Parameters: This method accepts a single parameter as mentioned above and described below:
object: This parameter holds the object to query.
Return Value: This method returns the array of key-value pairs.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    function Fb() {  this.id = 2045;  this.username = 'fb_myself';  this.password = 'fb1234';}   // This will not be included in the arrayFb.prototype.email = 'myself@gmail.com';  // Use of _.toPairs() method console.log(_.toPairs(new Fb));
Output:
[["id", 2045], ["username", "fb_myself"], ["password", "fb1234"]]

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    var GfG = {      'x': 1,      'y': 2 }  // Use of _.toPairs() method console.log(_.toPairs(GfG));
Output:
[['x', 1], ['y', 2]]

JavaScript-Lodash
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
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 ?
PLSQL | TRUNC Function

01 Nov, 2019
The TRUNC function is an inbuilt function in PLSQL which is used to return a number truncated to a particular number of decimal places.
Syntax:
TRUNC( number, decimal_places )
Parameters Used:This function accepts two parameters which are illustrated below:-
number – This is the input number which is going to be truncated to a certain number.
decimal_places – This is also a input number which specifies that up to what number after decimal point should be the output of this function.
Return Value:This function returns a numeric value truncated to a particular number of decimal places.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Let’s see some examples which illustrate the TRUNC function:
Example-1:
DECLARE 
   Test_Number number := 5.5;
   
BEGIN 
   dbms_output.put_line(TRUNC(Test_Number number)); 
   
END;  
Output:
5
In the above example, the truncated value of 5.5 is 5
Example-2:
DECLARE 
   Test_Number number1 := 5;
   Test_Number number2 := 0;
   
BEGIN 
   dbms_output.put_line(TRUNC(Test_Number number1, 
                              Test_Number number2)); 
   
END;  
Output:
5
In the above example, the truncated value of (5, 0) is 5 because 5 is not having any decimal point and hence it returns 5 as the output.
Example-3:
DECLARE 
   Test_Number number1 := 15.3123;
   Test_Number number2 := 2;
   
BEGIN 
   dbms_output.put_line(TRUNC(Test_Number number1, 
                              Test_Number number2)); 
   
END;  
Output:
15.31
In the above example, the truncated value of 15.3123 is 15.31 because here 2 is at the place of decimal_place parameter and it shows that the output value must contain 2 decimal number after the decimal point.
Advantage:This function is used to return a number truncated to a particular number of decimal places.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of python program | Set 14 (Dictionary)

23 Jun, 2021
Prerequisite: Dictionary Note: Output of all these programs is tested on Python31) What is the output of the following program?  
PYTHON3
D = dict()for x in enumerate(range(2)):    D[x[0]] = x[1]    D[x[1]+7] = x[0]print(D)
a) KeyError b) {0: 1, 7: 0, 1: 1, 8: 0} c) {0: 0, 7: 0, 1: 1, 8: 1} d) {1: 1, 7: 2, 0: 1, 8: 1} Ans. (c) Explanation: enumerate() will return a tuple, the loop will have x = (0, 0), (1, 1). Thus D[0] = 0, D[1] = 1, D[0 + 7] = D[7] = 0 and D[1 + 7] = D[8] = 1. Note: Dictionary is unordered, so the sequence of the key-value pair may differ in each output.2) What is the output of the following program?  
PYTHON3
D = {1 : 1, 2 : '2', '1' : 2, '2' : 3}D['1'] = 2print(D[D[D[str(D[1])]]])
a) 2 b) 3 c) ‘2’ d) KeyError Ans. (b) Explanation: Simple key-value pair is used recursively, D[1] = 1, str(1) = ‘1’. So, D[str(D[1])] = D[‘1’] = 2, D[2] = ‘2’ and D[‘2’] = 3.3) What is the output of the following program?  
PYTHON3
D = {1 : {'A' : {1 : "A"}, 2 : "B"}, 3 :"C", 'B' : "D", "D": 'E'}print(D[D[D[1][2]]], end = " ")print(D[D[1]["A"][2]])
a) D C b) E B c) D B d) E KeyError Ans. (d) Explanation: Key-Value Indexing is used in the example above. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][2] = “B”, D[D[1][2]] = D[“B”] = “D” and D[“D”] = “E”. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][“A”] = {1 : “A”} and D[1][“A”][2] doesn’t exists, thus KeyError.4) What is the output of the following program?  
PYTHON3
D = dict()for i in range (3):    for j in range(2):        D[i] = jprint(D)
a) {0: 0, 1: 0, 2: 0} b) {0: 1, 1: 1, 2: 1} c) {0: 0, 1: 0, 2: 0, 0: 1, 1: 1, 2: 1} d) TypeError: Immutable object Ans. (b) Explanation: 1st loop will give 3 values to i 0, 1 and 2. In the empty dictionary, valued are added and overwrited in j loop, for eg. D[0] = [0] becomes D[0] = 1, due to overwriting.5) Which of the options below could possibly be the output of the following program?  
PYTHON3
D = {1 : [1, 2, 3], 2: (4, 6, 8)}D[1].append(4)print(D[1], end = " ")L = [D[2]]L.append(10)D[2] = tuple(L)print(D[2])
a) [1, 2, 3, 4] [4, 6, 8, 10] b) [1, 2, 3, 4] ((4, 6, 8), 10) c) ‘[1, 2, 3, 4] TypeError: tuples are immutable d) [1, 2, 3, 4] (4, 6, 8, 10) Ans. (b) Explanation: In the first part key-value indexing is used and 4 is appended into the list. As tuples are immutable, in the second part the tuple is converted into a list, and value 10 is added finally to the new list ‘L’ then converted back to a tuple.This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
kkvidyarthi98
Python-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert JSON to CSV file using PowerShell?

To convert the JSON to the CSV format we need to first use the ConvertFrom-JSON command. For example, we have already JSON file present with us at the C:\temp\VMinfo.JSON location. We will first import this file and then convert it to CSV as shown below.
Get-Content C:\Temp\VMInfo.json | ConvertFrom-Json | Export-Csv C:\Temp\vminfo.csv -NoTypeInformation
Suppose you have cmdlet that produces output in the hash table format as shown below.
PS C:\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags

Key             Value
---             -----
For             Ansible
Patching_Day    Sunday
Application     SecretTag
Owner           Chirag
So we first need to convert the hash output to the JSON format and then from the JSON, we can save the output to excel.
PS C:\> Get-AzVM -VMName TestMachine2k16 | Select -ExpandProperty Tags | ConvertTo-Json | ConvertFrom-Json | Export-Csv C:\temp\Vmtags.csv -NoTypeIn
formation
Tryit Editor v3.7

Table Colspan & Rowspan
Tryit: HTML table - rowspan
How to validate expiry date on a MySQL query?

You can use NOW() for this. Following is the syntax −
select * from yourTableName
where yourColumnName> now();
Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   expiryDateOfMedicine datetime
   );
Query OK, 0 rows affected (0.55 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-27 11:29:00');
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-26 10:39:21');
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-28 11:30:10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(expiryDateOfMedicine) values('2019-04-29 12:44:11');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output −
+----+----------------------+
| Id | expiryDateOfMedicine |
+----+----------------------+
| 1  | 2019-04-27 11:29:00  |
| 2  | 2019-04-26 10:39:21  |
| 3  | 2019-04-28 11:30:10  |
| 4  | 2019-04-29 12:44:11  |
+----+----------------------+
4 rows in set (0.00 sec)
Following is the query to validate expiry date on a MySQL query −
mysql> select * from DemoTable
where expiryDateOfMedicine > now();
This will produce the following output −
+----+----------------------+
| Id | expiryDateOfMedicine |
+----+----------------------+
| 3  | 2019-04-28 11:30:10  |
| 4  | 2019-04-29 12:44:11  |
+----+----------------------+
2 rows in set (0.00 sec)
How to switch different browser tabs using Python Selenium?

We can switch different browser tabs using Selenium webdriver in Python using the method switch_to.window. By default, the webdriver has access to the parent window.
Once another browser tab is opened, the switch_to.window helps to switch the webdriver focus to the tab. The window handle of the browser window where we want to shift is passed as a parameter to that method.
The method window_handles contains the list of all window handle ids of the opened browsers. The method current_window_handle is used to hold the window handle id of the browser window in focus.
p = driver.current_window_handle
parent = driver.window_handles[0]
chld = driver.window_handles[1]
driver.switch_to.window(chld)
Let us make an attempt to access the below browser tabs −
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/windows")
#identify element
l = driver.find_element_by_link_text("Click Here")
l.click()
#obtain window handle of browser in focus
p = driver.current_window_handle
#obtain parent window handle
parent = driver.window_handles[0]
#obtain browser tab window
chld = driver.window_handles[1]
#switch to browser tab
driver.switch_to.window(chld)
print("Page title for browser tab:")
print(driver.title)
#close browser tab window
driver.close()
#switch to parent window
driver.switch_to.window(parent)
print("Page title for parent window:")
print(driver.title)
#close browser parent window
driver.close()